=== PAGE: https://www.union.ai/docs/v2/union === # Documentation Welcome to the documentation. ## Subpages - **Union.ai** - **Tutorials** - **Integrations** - **Reference** - **Community** - **Release notes** - **Getting support** - **Platform deployment** - **Zero Trust security** === PAGE: https://www.union.ai/docs/v2/union/user-guide === Everything you need to build, run, and operate workloads on Flyte, from first task to production deployment. # Union.ai Union.ai is the durable AI runtime your team owns. Your workloads run in your own cloud, and your data and code never leave it: they never traverse the Union.ai control plane. On it, you build model factories, production agents, and model serving in plain Python, as durable steps that can recover from failure. Union.ai is enterprise-grade [Flyte](https://www.union.ai/docs/v2/flyte), open source at the core. See [Platform deployment](https://www.union.ai/docs/v2/union/deployment/) for the ways to run it. > [!TIP] Try Union.ai free for 30 days > Sign up and set up Union.ai yourself, free for the first 30 days. > See [Platform deployment](https://www.union.ai/docs/v2/union/deployment/). ## Basics Learn the basics of Flyte, covering the core concepts around tasks, apps, and triggers. ### **Get started** What Flyte 2 is, how to install it, the core concepts, and the ways to run your code. ### **Tasks** Configure, build, and deploy the durable batch workloads that everything else is made of. ### **Apps** Long-running services for dashboards, REST APIs, and model endpoints. ### **Triggers** Run tasks automatically on a schedule, or save named launch configurations to fire on demand. ## AI workloads Train, post-train, and serve models, and build agents, with the Flyte constructs each workload relies on. ### **Model training** Train models with Flyte, from multi-node pretraining and LLM fine-tuning to classical machine learning, with every stage cached, recoverable, and sized to its own hardware. ### **Reinforcement learning** Run reinforcement learning loops with Flyte, with environments, rewards, rollouts, and the trainer each on their own hardware, and a loop that survives failures. ### **Inference** Run models from Flyte by calling a hosted provider, serving open-weight models on your own GPUs, deploying the models your tasks train, or making typed model calls. ### **Agents** Durable, self-healing agents built from tasks and apps, with sandboxing and MCP. ## Artifacts and factories Name and version the datasets and models your tasks produce, trace where they came from, and build them on demand with factories. ### **Artifacts** Register task outputs and uploads as named, versioned artifacts, trigger runs on new versions, mount them into apps, and trace lineage. ### **Factories** Declare how artifacts are made from other artifacts, then ask for any artifact for a partition or a range and let Union build only what is missing or stale. ## Access and identity How to authenticate and manage user permissions on your Union cluster. ### **Authenticating with Union** Authenticate with Union.ai using OAuth2, API keys, and service accounts. ### **User management** Manage users, roles, and policies for your Union cluster. ## Clusters and queues Stand up clusters and govern where your workloads run. ### **Clusters and queues** Group clusters into pools, register clusters, and create queues that route and rate-limit your workloads. ## Advanced guides Organize your codebase, optimize performance for production, and migrate from other workflow orchestrators. ### **Project patterns** Patterns for BYO images, monorepos with uv, CI/CD, multi-team resource management, the software development lifecycle, and an advanced end-to-end project. ### **Scale your runs** Tune task overhead, batching, reusable containers, and fanout to scale your workflows. ### **Migration** Port a Flyte 1 codebase to Flyte 2, or map Airflow concepts to their Flyte 2 equivalents. ## Subpages - **Get started** - What Flyte 2 is, how to install it, the core concepts, and the ways to run your code. - **Tasks** - Configure, build, and deploy the durable batch workloads that everything else is made of. - **Apps** - Long-running services for dashboards, REST APIs, and model endpoints. - **Triggers** - Run tasks automatically on a schedule, or save named launch configurations to fire on demand. - **Model training** - Train models with Flyte, from multi-node pretraining and LLM fine-tuning to classical machine learning, with every stage cached, recoverable, and sized to its own hardware. - **Reinforcement learning** - Run reinforcement learning loops with Flyte, with environments, rewards, rollouts, and the trainer each on their own hardware, and a loop that survives failures. - **Inference** - Run models from Flyte by calling a hosted provider, serving open-weight models on your own GPUs, deploying the models your tasks train, or making typed model calls. - **Agents** - Durable, self-healing agents built from tasks and apps, with sandboxing and MCP. - **Artifacts** - Register task outputs and uploads as named, versioned artifacts, trigger runs on new versions, mount them into apps, and trace lineage. - **Authenticating with Union** - Authenticate with Union.ai using OAuth2, API keys, and service accounts. - **Factories** - Declare how artifacts are made from other artifacts, then ask for any artifact for a partition or a range and let Union build only what is missing or stale. - **User management** - Manage users, roles, and policies for your Union cluster. - **Clusters and queues** - Group clusters into pools, register clusters, and create queues that route and rate-limit your workloads. - **Project patterns** - Patterns for BYO images, monorepos with uv, CI/CD, multi-team resource management, the software development lifecycle, and an advanced end-to-end project. - **Scale your runs** - Tune task overhead, batching, reusable containers, and fanout to scale your workflows. - **Migration** - Port a Flyte 1 codebase to Flyte 2, or map Airflow concepts to their Flyte 2 equivalents. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started === What Flyte 2 is, how to install it, the core concepts, and the ways to run your code. # Get started > [!INFO] Try it in your browser > Follow along with this guide in Google Colab without installing anything locally. > > [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/unionai/unionai-examples/blob/main/v2/user-guide/getting-started/ten_minutes_to_flyte.ipynb) This guide covers how to build AI applications, data pipelines, and ML workflows using the Flyte 2 SDK. Programs written using the Flyte 2 SDK can run on either a Union.ai or Flyte OSS back-end. This guide applies to both. ## Pure Python, no DSL Flyte lets you write workflows in standard Python: no domain-specific language, no special syntax, no restrictions. Your "workflow" is simply a task that calls other tasks: ```python @env.task() async def my_workflow(data: list[str]) -> list[str]: results = [] for item in data: if should_process(item): result = await process_item(item) results.append(result) return results ``` You can use everything Python offers: - **Loops and conditionals**: standard `for`, `while`, `if-elif-else` - **Error handling**: `try/except` blocks work as expected - **Async/await**: native Python concurrency model - **Any library**: import and use whatever you need This means no learning curve beyond Python itself, and no fighting a DSL when your requirements don't fit its constraints. ## Durability Every task execution in Flyte is automatically persisted. Inputs, outputs, and intermediate results are stored in an object store, giving you: - **Full observability**: see exactly what data flowed through each step - **Audit trail**: track what ran, when, and with what parameters - **Data lineage**: trace outputs back to their inputs This persistence happens automatically. You don't need to add logging or manually save state. Flyte handles it. ## Reproducibility Flyte ensures that runs can be reproduced exactly: - **Deterministic execution**: same inputs produce same outputs - **Caching**: task results are cached and reused when inputs match - **Versioned containers**: code runs in the same environment every time Caching is configurable per task: ```python @env.task(cache="auto") async def expensive_computation(data: str) -> str: # This result will be cached and reused for identical inputs ... ``` When you rerun a workflow, Flyte serves cached results for unchanged tasks rather than recomputing them. ## Recoverability When something fails, Flyte doesn't make you start over. Failed workflows can resume from where they left off: - **Completed tasks are preserved**: successful outputs remain cached - **Retry from failure point**: no need to re-execute what already succeeded - **Fine-grained checkpoints**: the `@flyte.trace` decorator creates checkpoints within tasks This reduces wasted compute and speeds up debugging. When a task fails after hours of prior computation, you fix the issue and continue, not restart. ## Built for scale Flyte handles the hard parts of distributed execution: - **Parallel execution**: express parallelism with `asyncio.gather()`, Flyte handles the rest - **Dynamic workflows**: construct workflows based on runtime data, not just static definitions - **Fast scheduling**: reusable containers achieve millisecond-level task startup - **Resource management**: specify CPU, memory, and GPU requirements per task ## What this means in practice Consider a data pipeline that processes thousands of files, trains a model, and deploys it: - If file processing fails on item 847, you fix the issue and resume from item 847 - If training succeeds, but deployment fails, you redeploy without retraining - If you rerun next week with the same data, cached results skip redundant computation - If you need to audit what happened, every step is recorded Flyte gives you the flexibility of Python scripts with the reliability of a production system. ## Start here ### **Get started > Quickstart** Install the SDK and run your first workflow locally in a few minutes. ### **Get started > Core concepts** The building blocks of every Flyte program: TaskEnvironments, tasks, runs, actions, and apps. ### **Get started > Run modes** Run the same task code locally in your Python process, or remotely on a devbox or a deployed cluster. ## Subpages - **Get started > Quickstart** - Install the SDK and run your first workflow locally in a few minutes. - **Get started > Core concepts** - The building blocks of every Flyte program: TaskEnvironments, tasks, runs, actions, and apps. - **Get started > Run modes** - Run the same task code locally in your Python process, or remotely on a devbox or a deployed cluster. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/quickstart === Install the SDK and run your first workflow locally in a few minutes. # Quickstart > [!NOTE] Try it in your browser > Prefer not to install anything? Follow along with this quickstart in Google Colab. > > [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/unionai/unionai-examples/blob/main/v2/user-guide/getting-started/ten_minutes_to_flyte.ipynb) Let's get you up and running with your first workflow on your local machine. ## What you'll need - Python 3.10+ in a virtual environment ## Install the SDK Install the `flyte` package: ```bash pip install 'flyte[tui]' ``` > **๐Ÿ“ Note** > > We also install the `tui` extra to enable the terminal user interface. Verify it worked: ```bash flyte --version ``` Output: ```bash Flyte SDK version: 2.*.* ``` > **๐Ÿ“ Note** > > If you have [`uv`](https://docs.astral.sh/uv/) installed, you can run the `flyte` CLI directly with `uvx`, without installing the package into your environment: > > ```bash > uvx flyte --version > uvx flyte get run > ``` ## Run something straight away Before writing anything of your own, you can run a built-in example. It needs no files and no configuration: ```bash flyte run --local hello ``` Flyte writes the example to a scratch directory, runs it, and prints the path to the source: ```bash Using the built-in example from /tmp/flyte-hello-/task/hello.py Copy it into your own project to start editing. Completed Local Run Outputs: ActionOutputs(o0=14.0) ``` The example fans a small computation over a list of inputs with `flyte.map` and averages the results. That is enough to see a workflow run. Next, write one of your own. > [!NOTE] Watch it in the console > Once your config file points at your Union.ai endpoint (see > **Get started > Run modes > Run on a deployed cluster > Configuration file**), swap `--local` for `--tracked`. The run still executes > on your machine, but reports its progress to Union.ai and appears under > **Tracked Runs**: > > ```bash > flyte run --tracked hello > ``` > > See **Get started > Run modes > Run locally in Python > Track local runs in the console**. ## Configure Create a config file for local execution. Runs will be persisted locally in a SQLite database. ```bash flyte create config --local-persistence ``` This creates `.flyte/config.yaml` in your current directory. See **Get started > Run modes > Run on a deployed cluster > Configuration file** for more options. > **๐Ÿ“ Note** > > Run `flyte get config` to check which configuration is currently active. ## Write your first workflow > [!TIP] Author workflows with an AI assistant > [`flyte-agent-plugins`](https://github.com/flyteorg/flyte-agent-plugins) โ€” a > portable agent harness plugin for Claude Code, Codex, OpenCode, and other > harnesses โ€” adds skills that scaffold projects and generate tasks, workflows, > apps, and tests for you, plus MCP servers that ground the agent in the Flyte SDK > and docs. See **Flyte agent plugins** to get started. This one converts a list of temperature readings and returns the hottest. Create `temperatures.py`: ```python # temperatures.py import flyte # A TaskEnvironment groups configuration for the tasks defined within it: # the container image, resources, and so on. This one keeps the defaults. env = flyte.TaskEnvironment(name="temperatures") # The @env.task decorator turns a Python function into a task. # Type annotations on the inputs and output are required. @env.task def to_fahrenheit(celsius: float) -> float: return celsius * 9 / 5 + 32 # This is the entrypoint task of the workflow. It calls to_fahrenheit # once per reading using flyte.map, which is like Python's map but runs # the calls in parallel, then returns the highest result. @env.task def hottest(readings: list[float] = [21.5, 19.0, 24.3, 22.8]) -> float: return round(max(flyte.map(to_fahrenheit, readings)), 1) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/getting-started/temperatures.py* Here's what's happening: - **`TaskEnvironment`** specifies configuration for your tasks (container image, resources, etc.) - **`@env.task`** turns Python functions into tasks that can run on a cluster - **`flyte.map`** calls `to_fahrenheit` once per reading, in parallel when running on a cluster - Both tasks share the same `env`, so they'll have identical configurations ## Run it Create a project directory and place your files there: ``` . โ”œโ”€โ”€ temperatures.py โ””โ”€โ”€ .flyte โ””โ”€โ”€ config.yaml ``` > [!WARNING] > Do not run `flyte run` from your home directory. Flyte packages the current directory when running on a cluster, so running from `$HOME` would attempt to bundle your entire home folder. Always work from a dedicated project directory. Run the workflow, naming the file and the entrypoint task: ```bash flyte run --local temperatures.py hottest ``` This executes the workflow locally on your machine: ```bash Completed Local Run Outputs: ActionOutputs(o0=75.7) ``` ## See the results You can see the run in the TUI by running: ```bash flyte start tui ``` The TUI will open into the explorer view ![Explorer View](../../_static/images/user-guide/quickstart/explorer-tui.png) To navigate to the run details, double-click it or press `Enter` to view the run details. ![Run Details View](../../_static/images/user-guide/quickstart/run-tui.png) ## Next steps Now that you've run your first workflow: - [**Core concepts**](./core-concepts/_index): Understand the core concepts of Flyte programming - **Get started > Run modes > Run locally in Python**: Learn about the TUI, caching, and other features that work locally - **Get started > Run modes > Run on the Devbox**: Learn about the devbox cluster and how to run workflows on it - **Get started > Run modes > Run on a deployed cluster**: Configure your environment to run on a cluster in the cloud or on-premises === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts === The building blocks of every Flyte program: TaskEnvironments, tasks, runs, actions, and apps. # Core concepts The **Get started > Quickstart** ran a workflow without stopping to explain it. This section explains it, one concept at a time, each with an example you can run yourself. ## How a Flyte program fits together Four pieces do most of the work: 1. A **TaskEnvironment** declares the container image, the resources, and the secrets that a group of tasks share. 2. A **task** is a Python function you decorate with `@env.task`. It runs remotely, in that environment. 3. Calling a task creates a **run**, which tracks the whole execution from start to finish. 4. Every task execution inside that run is an **action**, recorded on its own so it can be retried, cached, and inspected separately. Two more ideas sit on top. An **app** is a long-running service rather than a job that finishes, and **projects and domains** decide where a run lives and what it is allowed to reach. The pages below build on each other, so read them in order if you are new. The last one puts every piece together in a project you can deploy. {{< subpage-cards >}} ## Subpages - **Get started > Core concepts > TaskEnvironment** - The container image, resources, and secrets a group of tasks runs with. - **Get started > Core concepts > Tasks** - The Python function that runs remotely in a container, and how it replaces the Flyte 1 task and workflow split. - **Get started > Core concepts > Runs and actions** - The run that tracks an execution, and the actions that make it up. - **Get started > Core concepts > Where your data lives** - A developer's map of what Flyte stores in the control plane database versus the data plane object store, and what "metadata," "literals," and "raw data" actually mean. - **Get started > Core concepts > Apps** - Long-lived services, and how they differ from the tasks you have already met. - **Get started > Core concepts > Projects and domains** - How organizations, projects, and domains partition your work and its resources. - **Get started > Core concepts > Key capabilities** - An overview of what Flyte can do, once the core concepts are in place. - **Get started > Core concepts > Settings** - Set defaults at each level of the org, domain, and project hierarchy. - **Get started > Core concepts > Basic project: RAG** - A worked two-stage RAG project: an offline embedding pipeline and the app that queries it. - **Get started > Core concepts > Leases** - How Union.ai tracks work across clusters, why you occasionally see `lease expired`, and how the system protects you from runaway compute. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/task-environment === The container image, resources, and secrets a group of tasks runs with. # TaskEnvironment A `TaskEnvironment` defines the hardware and software environment where your tasks run. Think of it as the container configuration for your code. ## A minimal example Here's the simplest possible TaskEnvironment: ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task def hello() -> str: return "Hello from Flyte!" ``` With just a `name`, you get Flyte's default container image and resource allocation. This is enough for simple tasks that only need Python and the Flyte SDK. ## What TaskEnvironment controls A TaskEnvironment specifies two things: **Hardware environment** - The compute resources allocated to each task: - CPU cores - Memory - GPU type and count **Software environment** - The container image your code runs in: - Base image (Python version, OS) - Installed packages and dependencies - Environment variables ## Configuring resources Use the `resources` parameter to specify compute resources: ```python env = flyte.TaskEnvironment( name="compute_heavy", resources=flyte.Resources(cpu="4", memory="16Gi"), ) ``` For GPU workloads: ```python env = flyte.TaskEnvironment( name="gpu_training", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="A10G:1"), ) ``` ## Configuring container images For tasks that need additional Python packages, specify a custom image: ```python image = flyte.Image.from_debian_base().with_pip_packages("pandas", "scikit-learn") env = flyte.TaskEnvironment( name="ml_env", image=image, ) ``` The image doesn't hard-code a container registry. For remote runs you set that once in your config (`image.registry`), so it stays out of your code. See **Tasks > Configure tasks > Container images** for detailed image configuration options. ## Multiple tasks, one environment All tasks decorated with the same `@env.task` share that environment's configuration: ```python env = flyte.TaskEnvironment( name="data_processing", resources=flyte.Resources(cpu="2", memory="8Gi"), ) @env.task def load_data(path: str) -> dict: # Runs with 2 CPU, 8Gi memory ... @env.task def transform_data(data: dict) -> dict: # Also runs with 2 CPU, 8Gi memory ... ``` This is useful when multiple tasks have similar requirements. ## Multiple environments When tasks have different requirements, create separate environments: ```python light_env = flyte.TaskEnvironment( name="light", resources=flyte.Resources(cpu="1", memory="2Gi"), ) heavy_env = flyte.TaskEnvironment( name="heavy", resources=flyte.Resources(cpu="8", memory="32Gi"), ) @light_env.task def preprocess(data: str) -> str: # Light processing ... @heavy_env.task def train_model(data: str) -> dict: # Resource-intensive training ... ``` ## Next steps Now that you understand TaskEnvironments, let's look at how to define **Get started > Core concepts > Tasks** that run inside them. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/tasks === The Python function that runs remotely in a container, and how it replaces the Flyte 1 task and workflow split. # Tasks A task is a Python function that runs remotely in a container. You create tasks by decorating functions with `@env.task`. > **๐Ÿ“ Note** > > In Flyte 1, tasks and workflows were defined with separate `@task`, `@workflow`, and `@dynamic` decorators. Flyte 2 uses a single `@env.task` decorator off a `flyte.TaskEnvironment`: everything is a task. ## Defining a task Here's a simple task: ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task def greet(name: str) -> str: return f"Hello, {name}!" ``` The `@env.task` decorator tells Flyte to run this function in a container configured by `env`. ## Type hints are required Flyte uses type hints to understand your data and serialize it between tasks: ```python @env.task def process_numbers(values: list[int]) -> int: return sum(values) ``` Supported types include: - Primitives: `int`, `float`, `str`, `bool` - Collections: `list`, `dict`, `tuple` - DataFrames: `pandas.DataFrame`, `polars.DataFrame` - Files: `flyte.io.File`, `flyte.io.Dir` - Custom: dataclasses, Pydantic models See **Tasks > Build tasks > Data classes and structures** for complex types. ## Tasks calling tasks In Flyte 2, tasks can call other tasks directly. The called task runs in its own container: ```python @env.task def fetch_data(url: str) -> dict: # Runs in container 1 ... @env.task def process_data(url: str) -> str: data = fetch_data(url) # Calls fetch_data, runs in container 2 return transform(data) ``` This is how you build workflows in Flyte 2. There's no separate `@workflow` decorator - just tasks calling tasks. ## The top-level task The task you execute directly is the "top-level" or "driver" task. It orchestrates other tasks: ```python @env.task def step_one(x: int) -> int: return x * 2 @env.task def step_two(x: int) -> int: return x + 10 @env.task def pipeline(x: int) -> int: a = step_one(x) # Run step_one b = step_two(a) # Run step_two with result return b ``` When you run `pipeline`, it becomes the top-level task and orchestrates `step_one` and `step_two`. ## Running tasks locally For quick testing, you can call a task like a regular function: ```python # Direct call - runs locally, not in a container result = greet("World") print(result) # "Hello, World!" ``` This bypasses Flyte entirely and is useful for debugging logic. However, local calls don't track data, use remote resources, or benefit from Flyte's features. ## Running tasks remotely To run a task on your Flyte backend: ```python import flyte flyte.init_from_config() result = flyte.run(greet, name="World") print(result) # "Hello, World!" ``` Or from the command line: ```bash flyte run my_script.py greet --name World ``` This sends your code to the Flyte backend, runs it in a container, and returns the result. ## Next steps Now that you can define and run tasks, let's understand how Flyte tracks executions with **Get started > Core concepts > Runs and actions**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/runs-and-actions === The run that tracks an execution, and the actions that make it up. # Runs and actions When you execute a task on Flyte, the system creates a **run** to track it. Each individual task execution within that run is an **action**. Understanding this hierarchy helps you navigate the UI and debug your workflows. ## What is a run? A **run** is the execution of a task that you directly initiate, plus all its descendant task executions, considered as a single unit. When you execute: ```bash flyte run my_script.py pipeline --x 5 ``` Flyte creates a run for `pipeline`. If `pipeline` calls other tasks, those executions are part of the same run. ## What is an action? An **action** is the execution of a single task, considered independently. A run consists of one or more actions. Consider this workflow: ```python @env.task def step_one(x: int) -> int: return x * 2 @env.task def step_two(x: int) -> int: return x + 10 @env.task def pipeline(x: int) -> int: a = step_one(x) b = step_two(a) return b ``` When you run `pipeline(5)`: - **1 run** is created for the entire execution - **3 actions** are created: one for `pipeline`, one for `step_one`, one for `step_two` ## Runs vs actions in practice | Concept | What it represents | In the UI | |---------|-------------------|-----------| | **Run** | Complete execution initiated by user | Runs list, top-level view | | **Action** | Single task execution | Individual task details, logs | For details on how to run tasks locally and remotely, see **Get started > Core concepts > Tasks > Running tasks locally**. ## Viewing runs in the UI After running a task remotely, click the URL in the output to see your run in the UI: ```bash flyte run my_script.py pipeline --x 5 ``` Output: ```bash abc123xyz https://my-instance.example.com/v2/runs/project/my-project/domain/development/abc123xyz Run 'a0' completed successfully. ``` In the UI, you can: - See the overall run status and duration - Navigate to individual actions - View inputs and outputs for each task - Access logs for debugging - See the execution graph ## Understanding the execution graph The UI shows how tasks relate to each other: ``` pipeline (action) โ”œโ”€โ”€ step_one (action) โ””โ”€โ”€ step_two (action) ``` Each box is an action. Arrows show data flow between tasks. This visualization helps you understand complex workflows and identify bottlenecks. ## Checking run status From the command line: ```bash flyte get run ``` From Python: ```python import flyte flyte.init_from_config() run = flyte.run(pipeline, x=5) # The run object has status information print(run.status) ``` ## Next steps You now understand tasks and how Flyte tracks their execution. Next, let's learn about **Get started > Core concepts > Apps** - Flyte's approach to long-running services. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/where-data-lives === A developer's map of what Flyte stores in the control plane database versus the data plane object store, and what "metadata," "literals," and "raw data" actually mean. # Where your data lives When you run a Flyte task, your data ends up in two stores: a **database** in the control plane and an **object-store bucket** in the data plane. ## The two stores | | Control plane database | Data plane object store | |---|---|---| | **Backing tech** | Postgres (plus a few internal coordination stores) | S3, GCS, or ABS bucket | | **What's in it** | Every record Flyte uses to *describe* your runs, plus pointers to where each run's inputs and outputs live | Every run's inputs and outputs, and all bulk/offloaded content | | **Lifetime** | Durable; long-lived history | Durable, but you can apply lifecycle/retention rules | ## Who manages the stores * The control plane database (being part of the control plane) is always managed by Union.ai, regardless of whether you are using a BYOC or self-managed deployment. * The data plane bucket lives in your cloud account. In a BYOC deployment, it is managed by Union.ai (as is the entire data plane). In a self-managed deployment, you manage the bucket yourself. The database is the **source of truth for what executed**. The bucket is **where your runs' actual input and output values live**. ## What goes in the database The control plane database holds everything Flyte needs to enumerate, schedule, and replay your work. Specifically: - **Registrations**: every task you've deployed, every trigger you've registered, every project and domain. A task's definition includes its *default* input values, which are stored inline as part of the registration. The registration also carries the full task template: container image reference, command and arguments, resource requests, environment variables (as literal key/value pairs), and the *names* of any secrets the task requests. - **Execution records**: every run, every action (task / trace / condition) inside that run, attempts, phases, timing, error messages, parent/child relationships. Each run also stores the run-level configuration it was launched with: labels, annotations, environment variables set through the run context, custom blob storage prefixes, cache settings, and notification rules. - **Schedules and triggers**: `Cron`, event triggers, and their revision history. - **Pointers to runtime inputs and outputs**: the database stores the *URI* of each run's `inputs.pb` / `outputs.pb`, not the values themselves. (One exception: an awaited *condition* / approval action stores the value that satisfies it inline.) - **Caches**: the cache key โ†’ output-URI mapping for `@env.task(cache=...)`. In Union.ai, the database also holds: - **Run placement**: the queue and cluster pool each run was launched on. - **Apps**: every deployed app's full spec (container image reference, command and arguments, environment variables, ports, resources, autoscaling and ingress settings, secret *names*, and the inputs you pass to the app) plus its current status, including the public, CNAME, and VPC URLs it is reachable at, the assigned cluster, the creator, and the last start time. - **Reusable environments**: the environment spec (image, resources, environment variables, secret names, pod template, parallelism), its scaling state (replicas, idle and scale-down TTLs), and the per-cluster status of its worker pool, including worker states and recent worker error messages. The values your tasks actually pass at runtime, even a bare `int`, do **not** live in the database. They are written to `inputs.pb` / `outputs.pb` in the bucket, and the database keeps only the pointer. See the next section. Environment variables in task and run specs are stored as plain text in the database. So are environment variables in app and reusable environment specs, and string inputs passed to apps. Put credentials and other sensitive configuration in **Tasks > Configure tasks > Secrets** rather than in `env` maps. A secret can be mounted as an environment variable, and because it is mounted at runtime, its value is never stored in the control plane database. (Internally, Flyte uses several backing databases: Postgres for registrations and run history, separate stores for in-flight action coordination and caches. For developer purposes the only thing that matters is that they're all small-record, structured stores; none of them hold bulk content.) ## What goes in the bucket Every run's inputs and outputs are written to the bucket as `inputs.pb` / `outputs.pb`, and the database stores a **pointer** (URI) to them. Within those files, small scalar values are inlined directly while large values are offloaded to separate objects and referenced by URI. The bucket holds: - **Task inputs**, serialized as `inputs.pb` per run. - **Task outputs**, serialized as `outputs.pb` per attempt. - **Offloaded values**: `flyte.io.File`, `flyte.io.Dir`, `flyte.io.DataFrame`, pickled objects, models, anything large. - **Decks**: the HTML reports your task renders. - **Trace checkpoints**: used by `@flyte.trace` to resume partial work. - **Fast-registered code bundles**: what `flyte deploy` and `flyte run --copy-style all` upload so the cluster can run your local Python. - **Image-build contexts**: when Union.ai builds a container image from an `Image` definition that requires a build context. By default, inputs (including inputs uploaded ahead of a run), outputs, Decks and `@flyte.trace` records live under per-run, per-action subprefixes of `metadata/v2//////...`. Offloaded values (`File`, `Dir`, `DataFrame` contents and similar) and task checkpoints go to a separate per-run raw-output prefix, and SDK uploads (code bundles, image-build contexts) have their own prefixes. You don't typically need to know the exact paths; you do need to know that **everything above lives behind one configured bucket prefix**. ## What "literal" and "raw data" mean Every value a task takes in or returns is, in Flyte's data model, a **literal**: a typed, serialized representation of that value. Literals are how data flows between tasks, and each one is stored in one of two ways: - **Inline**: small values (primitives like `int` / `float` / `str` / `bool`, collections, and JSON-serializable dataclasses and Pydantic models) are serialized *by value* directly into the run's `inputs.pb` / `outputs.pb`. - **By reference**: large values (`flyte.io.File`, `flyte.io.Dir`, `flyte.io.DataFrame`, large model objects, larger pickled objects) are offloaded to their own objects in the bucket; the literal recorded in `inputs.pb` / `outputs.pb` then holds only a *URI pointer* to them. **Raw data** is that offloaded content itself: the file, directory, DataFrame, or model bytes a by-reference literal points at, plus other offloaded artifacts such as checkpoints. It's exactly the offloaded values listed under **Get started > Core concepts > Where your data lives > What goes in the bucket** above, and it's what `raw_data_path` (below) relocates. Because it's carried as a URI rather than copied inline, raw data is often described as being "passed by reference" (as opposed to inline literals, which are "passed by value"). (In the deployment and architecture guides you may also see execution data split into *literal data* and *raw data*. There, *literal data* means specifically the inline values above and *raw data* the offloaded ones, the same distinction, named as two categories.) In short: every input and output is a **literal**; a literal is stored either **inline** (the value lives in `inputs.pb` / `outputs.pb`) or **by reference** to **raw data** offloaded elsewhere in the bucket. ## What "metadata" means The word "metadata" appears in several places and means a different thing each time. The two senses that matter for developers: ### 1. "Metadata" as in the control plane database (Flyte's usage) When Flyte documentation says **"metadata is preserved"** or **"metadata lives in the control plane,"** it means the database records above: registrations (including task default values), run history, and status. It does **not** mean "the contents of the bucket." This is the sense most relevant to you: the database is durable, and losing the bucket does not lose your execution history. It loses the *large values* those history records pointed at. ### 2. "Metadata bucket" (a deployment/ops term you may see) The Helm chart and some operational guides refer to a **"metadata bucket"** or `metadataContainer`. **This is a legacy name.** The bucket it refers to does *not* hold the database-style metadata above. It holds `inputs.pb`, `outputs.pb`, Decks, checkpoints, code bundles, and offloaded data. In other words, it holds exactly the "bucket" contents listed in the previous section. If you see "metadata bucket" in an ops context, read it as **"the data plane object-store bucket."** The naming is unfortunate; the contents are what you'd expect from a data bucket. You can largely ignore other appearances of the word in API surfaces (`TaskMetadata`, `ActionMetadata`, and the `/tmp/flyte/metadata` scratch directory that local-mode runs write to). Those are small property bags or local scratch paths and don't change where your data is stored. ## Per-run customization: `raw_data_path` By default, offloaded values (`File`, `Dir`, `DataFrame`, checkpoints) land alongside everything else under the deployment's configured bucket prefix. You can route them to a different prefix, including a different bucket entirely, for a single run: ```python import flyte flyte.init_from_config() run = flyte.with_runcontext( raw_data_path="s3://my-other-bucket/some/prefix", ).run(my_task, x=1) ``` Use it to send a sensitive run to an isolated bucket, point at a bucket with different lifecycle rules, or otherwise route offloaded data per run. The `inputs.pb` / `outputs.pb` themselves still land in the deployment's bucket; only the *raw* offloaded contents move. Any scheme Flyte's storage layer can resolve works here, not just `s3://`, `gs://` and local paths. `s3://`, `gs://`, `abfs://` and `abfss://` are served by the built-in obstore backend; anything else falls back to the filesystem `fsspec` has registered for that scheme. Hugging Face storage buckets are one such target, so `raw_data_path="hf://buckets///..."` sends offloaded values to the Hub. See [Hugging Face buckets as raw data storage](../../../integrations/huggingface/_index#hugging-face-buckets-as-raw-data-storage) for a worked example. See **Tasks > Run and deploy tasks > Run context** for the full set of `with_runcontext` options. ## What happens if the bucket is purged If a retention rule deletes objects out of the bucket, the database records that pointed at them are **not** deleted, but their pointers now dangle. Concretely: - Execution history, status, timing, structure: **still visible** in the UI. They come from the database. - Input/output **previews, Deck views, artifact payloads**: show "not found" if the underlying bytes were purged. - **Cache hits** for purged outputs: the cached pointer is dead, the task re-executes. - **Trace resumption**: not possible if the checkpoint blob is gone. - **Re-running an old execution**: fails if any input it needs has been purged. This is the trade-off behind retention policies: you save storage cost at the price of being able to inspect or re-run old executions whose offloaded values have aged out. New executions are unaffected. Lifecycle / retention rules should be scoped to the offloaded-data prefixes, **not** applied bucket-wide: `inputs.pb` and `outputs.pb` are needed for in-flight executions to complete, so purging them mid-run breaks things. For how retention policies are configured in your deployment, see **BYOC deployment > Data retention policy** or **Self-managed deployment > Advanced configurations > Data retention policies**. ## The short version - **Database** = the system of record. Holds registrations (including task default values), run history, schedules, and pointers to each run's inputs/outputs. - **Bucket** = the object-store bucket. Holds every run's `inputs.pb`/`outputs.pb`, Decks, checkpoints, code bundles, and offloaded `File` / `Dir` / `DataFrame` contents. - **Values** = every task input/output is a **literal**, stored either *inline* in `inputs.pb`/`outputs.pb` or *by reference* to **raw data** offloaded in the bucket. - **"Metadata" in docs** usually means database-side records. **"Metadata bucket" in Helm/ops** is legacy naming for the data plane bucket. It does *not* hold database metadata. - **`flyte.with_runcontext(raw_data_path=...)`** is your knob to send offloaded data elsewhere per run. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/introducing-apps === Long-lived services, and how they differ from the tasks you have already met. # Apps Now that you understand tasks, let's learn about apps - Flyte's way of running long-lived services. ## Tasks vs apps You've already learned about **tasks**: Python functions that run to completion in containers. Tasks are great for data processing, training, and batch operations. **Apps** are different. An app is a long-running service that stays active and handles requests over time. Apps are ideal for: - REST APIs and webhooks - Model inference endpoints - Interactive dashboards - Real-time data services | Aspect | Task | App | |--------|------|-----| | Lifecycle | Runs once, then exits | Stays running indefinitely | | Invocation | Called with inputs, returns outputs | Receives HTTP requests | | Use case | Batch processing, training | APIs, inference, dashboards | | Durability | Inputs/outputs stored, can resume | Stateless request handling | ## AppEnvironment Just as tasks use `TaskEnvironment`, apps use `AppEnvironment` to configure their runtime. An `AppEnvironment` specifies: - **Hardware**: CPU, memory, GPU allocation - **Software**: Container image with dependencies - **App-specific settings**: Ports, scaling, authentication Here's a simple example: ```python import flyte from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment app = FastAPI() env = FastAPIAppEnvironment( name="my-app", app=app, image=flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn"), resources=flyte.Resources(cpu="1", memory="2Gi"), ) ``` ## A hello world app Let's create a minimal FastAPI app to see how this works. First, create `hello_app.py`: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "uvicorn", # ] # /// """A simple "Hello World" FastAPI app example for serving.""" from fastapi import FastAPI import pathlib import flyte from flyte.app.extras import FastAPIAppEnvironment # Define a simple FastAPI application app = FastAPI( title="Hello World API", description="A simple FastAPI application", version="1.0.0", ) # Create an AppEnvironment for the FastAPI app env = FastAPIAppEnvironment( name="hello-app", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, ) # Define API endpoints @app.get("/") async def root(): return {"message": "Hello, World!"} @app.get("/health") async def health_check(): return {"status": "healthy"} # Serving this script will deploy and serve the app on your Union/Flyte instance. if __name__ == "__main__": # Initialize Flyte from a config file. flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) # Serve the app remotely. app_instance = flyte.serve(env) # Print the app URL. print(app_instance.url) print("App 'hello-app' is now serving.") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/getting-started/serving/hello_app.py* ### Understanding the code - **`FastAPI()`** creates the web application with its endpoints - **`FastAPIAppEnvironment`** configures the container and resources - **`@app.get("/")`** defines an HTTP endpoint that returns a greeting - **`flyte.serve()`** deploys and starts the app on your Flyte backend ### Serving the app With your config file in place, serve the app: ```bash flyte serve hello_app.py env ``` Or run the Python file directly (which calls `flyte.serve()` in the main block): ```bash python hello_app.py ``` You'll see output like: ```output https://my-instance.flyte.com/v2/domain/development/project/my-project/apps/hello-app App 'hello-app' is now serving. ``` Click the link to view your app in the UI. You can find the app URL there, or visit `/docs` for FastAPI's interactive API documentation. ## When to use apps vs tasks Use **tasks** when: - Processing takes seconds to hours - You need durability (inputs/outputs tracked) - Work is triggered by events or schedules - Results need to be cached or resumed Use **apps** when: - Responses must be fast (milliseconds) - You're serving an API or dashboard - Users interact in real-time - You need a persistent endpoint ## Common patterns **Model serving with FastAPI**: Train a model with a Flyte pipeline, then serve predictions from it. During local development, the app loads the model from a local file. When deployed remotely, Flyte's `Parameter` system automatically resolves the model from the latest training run output. See **Apps > Native app integrations > FastAPI app** for the full example. **Agent UI with Gradio**: Build an interactive UI that kicks off agent runs using `flyte.with_runcontext()`. A single `RUN_MODE` environment variable controls the deployment progression: fully local (rapid iteration), local UI with remote task execution (cluster compute), or fully remote (production). See [Build apps](../../apps/build-apps/_index) for details. ## Next steps You now understand the core building blocks of Flyte: - **TaskEnvironment** and **AppEnvironment** configure where code runs - **Tasks** are functions that execute and complete - **Apps** are long-running services - **Runs** and **Actions** track executions Before diving deeper, check out **Get started > Core concepts > Key capabilities** for an overview of what Flyte can do: from parallelism and caching to LLM serving and error recovery. Then head to **Get started > Core concepts > Basic project: RAG** to build a RAG application with an embedding pipeline and a Streamlit app. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/projects-and-domains === How organizations, projects, and domains partition your work and its resources. # Projects and domains Union.ai organizes work into a hierarchy of **organization**, **projects**, and **domains**. - **Organization**: Your Union.ai instance, typically representing a company or department. Set up during onboarding and mapped to your endpoint URL (e.g., `my-org.my-company.com`). You do not create or manage organizations directly. The organization is normally determined automatically from your endpoint URL, but you can override it with the `--org` flag on any CLI command (e.g., `flyte --org my-org get project`). This is only relevant if you have a multi-organization installation. - **Project**: A logical grouping of related tasks, apps, triggers, and runs. Projects are the primary unit you create and manage. - **Domain**: An environment classification within each project. Three fixed domains exist: `development`, `staging`, and `production`. Domains cannot be created or deleted. Every project contains all three domains, creating **project-domain pairs** like `my-project/development`, `my-project/staging`, and `my-project/production`. Tasks, apps, triggers, runs, and data are scoped to a specific project-domain pair. ## How projects and domains are used When you run or deploy workflows, you target a project and domain: - **CLI**: Use `--project` and `--domain` flags with `flyte run` or `flyte deploy`, or set defaults in your **Get started > Run modes > Run on a deployed cluster**. - **Python SDK**: Specify `project` and `domain` in `flyte.init` or `flyte.init_from_config`. Projects and domains also determine: - **Access control**: RBAC policies scope permissions to an organization, project, domain, or project-domain pair. See **User management**. - **Data isolation**: Storage and cache are isolated per project-domain pair. - **Settings**: Default behavior (such as the task queue, resource requests, and environment variables) can be configured at org, domain, or project scope. See **Get started > Core concepts > Settings**. ## Managing projects via CLI ### Create a project ```shell flyte create project --id my-project --name "My Project" ``` The `--id` is a unique identifier used in CLI commands and configuration (immutable once set). The `--name` is a human-readable display name. You can also add a description and labels: ```shell flyte create project \ --id my-project \ --name "My Project" \ --description "ML platform workflows" \ -l team=ml-platform \ -l env=prod ``` Labels are specified as `-l key=value` and can be repeated. ### List projects List all active projects: ```shell flyte get project ``` Get details of a specific project: ```shell flyte get project my-project ``` List archived projects: ```shell flyte get project --archived ``` ### Update a project Update the name, description, or labels of a project: ```shell flyte update project my-project --description "Updated description" flyte update project my-project --name "New Display Name" flyte update project my-project -l team=ml -l env=staging ``` > [!NOTE] > Setting labels replaces all existing labels on the project. ### Archive a project Archiving a project hides it from default listings but does not delete its data: ```shell flyte update project my-project --archive ``` ### Unarchive a project Restore an archived project to active status: ```shell flyte update project my-project --unarchive ``` ## Listing projects programmatically You can list and retrieve projects from Python using `flyte.remote.Project`: ```python import flyte flyte.init_from_config() # Get a specific project project = flyte.remote.Project.get(name="my-project") # List all projects for project in flyte.remote.Project.listall(): print(project.to_dict()) # List with filtering and sorting for project in flyte.remote.Project.listall(sort_by=("created_at", "desc")): print(project.to_dict()) ``` Both `get()` and `listall()` support async execution via `.aio()`: ```python project = await flyte.remote.Project.get.aio(name="my-project") ``` > [!NOTE] > `flyte.remote.Project` also has `create()`, `update()`, `archive()`, and `unarchive()` methods. The `flyte create project` and `flyte update project` commands call `create()` and `update()`. ## Managing projects via the UI When you log in to your Union.ai instance, you land on the **Projects** page, which lists all projects in your organization. By default, the domain is set to `development`. You can change the active domain using the selector in the top left. A **Recently viewed** list on the left sidebar provides quick access to your most commonly used projects. From the project list you can: * **Open a project**: Select a project from the list to navigate to it. * **Create a project**: Click **+ New project** in the top right. In the dialog, specify a name and description. The project will be created across all three domains. * **Archive a project**: Click the three-dot menu on a project's entry and select **Archive project**. ## Domains Domains provide environment separation within each project. The three domains are: | Domain | Purpose | |--------|---------| | `development` | For iterating on workflows during active development. | | `staging` | For testing workflows before promoting to production. | | `production` | For production workloads. | Domains are predefined and cannot be created, renamed, or deleted. ### Targeting a domain Set the default domain in your configuration file: ```yaml task: domain: development ``` Or override per command: ```shell flyte run --domain staging hello.py main ``` When using `flyte deploy`, the domain determines where the deployed workflows will execute: ```shell flyte deploy --project my-project --domain production workflows ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/key-capabilities === An overview of what Flyte can do, once the core concepts are in place. # Key capabilities Now that you understand the core concepts -- `TaskEnvironment`, tasks, runs, and apps -- here's an overview of what Flyte can do. Each capability is covered in detail later in the documentation. ## Environment and resources Configure how and where your code runs. - **Multiple environments**: Create separate configurations for different use cases (dev, prod, GPU vs CPU) โ†’ **Tasks > Configure tasks > Multiple environments** - **Resource specification**: Request specific CPU, memory, GPU, and storage for your tasks โ†’ **Tasks > Configure tasks > Resources** - **Reusable containers**: Eliminate container startup overhead with pooled, warm containers for millisecond-level task scheduling โ†’ **Tasks > Configure tasks > Reusable containers** ## Deployment Get your code running remotely. - **Cloud image building**: Build container images remotely without needing local Docker โ†’ **Tasks > Configure tasks > Container images** - **Code packaging**: Your local code is automatically bundled and deployed to on-cluster execution โ†’ **Tasks > Run and deploy tasks > Code packaging for on-cluster execution** - **Local testing**: Test tasks locally before deploying with `flyte run --local` โ†’ **Tasks > Run and deploy tasks > How task run works** ## Data handling Pass data efficiently between tasks. - **Files and directories**: Pass large files and directories between tasks using `flyte.io.File` and `flyte.io.Dir` โ†’ **Tasks > Build tasks > Files and directories** - **DataFrames**: Work with pandas, Polars, and other DataFrame types natively โ†’ **Tasks > Build tasks > DataFrames** ## Parallelism and composition Scale out and compose workflows. - **Fanout parallelism**: Process items in parallel using `flyte.map` or `asyncio.gather` โ†’ **Tasks > Build tasks > Fanout** - **Remote tasks**: Call previously deployed tasks from within your workflows โ†’ **Tasks > Build tasks > Remote tasks** ## Security and automation Manage credentials and automate execution. - **Secrets**: Inject API keys, passwords, and other credentials securely into tasks โ†’ **Tasks > Configure tasks > Secrets** - **Triggers**: Schedule tasks on a cron schedule or trigger them from external events โ†’ [Triggers](../../triggers/_index) - **Webhooks**: Build APIs that trigger task execution from external systems โ†’ **Apps > Build apps > Hybrid app-task graphs** ## Durability and reliability Handle failures and avoid redundant work. - **Error handling**: Catch failures and retry with different resources (e.g., more memory) โ†’ **Tasks > Build tasks > Error handling** - **Retries and timeouts**: Configure automatic retries and execution time limits โ†’ **Tasks > Configure tasks > Retries and timeouts** - **Caching**: Add `cache="auto"` to any task and Flyte stores its outputs keyed on task name and inputs. Same inputs means instant results with no recomputation. This speeds up your development loop: skip re-downloading data, avoid replaying earlier steps in agentic chains, or bypass any expensive computation while you iterate. โ†’ **Tasks > Configure tasks > Caching** ```python @env.task(cache="auto") async def load_data(data_dir: str = "./data") -> str: """Downloads once, then returns instantly on subsequent runs.""" # ... expensive download ... return data_dir ``` - **Traces**: Use `@flyte.trace` to get visibility into the internal steps of a task without the overhead of making each step a separate task. Traced functions show up as child nodes under their parent task, each with their own timing, inputs, and outputs. This is particularly useful for AI agents where you want to see which tools were called. โ†’ **Tasks > Build tasks > Traces** ```python @flyte.trace async def search(query: str) -> str: """Shows up as a child node under the parent task.""" return await do_search(query) @env.task async def agent(request: str) -> str: results = await search(request) # Traced answer = await summarize(results) # Also traced if decorated return answer ``` - **Reports**: Add `report=True` to a task and it can generate an HTML report (charts, tables, images) saved alongside the task output. Combined with caching and persisted inputs/outputs, reports act as lightweight experiment tracking: each run produces a self-contained HTML file you can compare across runs and share with your team. โ†’ **Tasks > Build tasks > Reports** ```python import flyte.report @env.task(report=True) async def evaluate(model_file: File, test_data: str) -> str: # ... run evaluation ... await flyte.report.replace.aio( f"

Training Report

" f"

Test Results

" f"

Accuracy: {accuracy:.4f}

" ) await flyte.report.flush.aio() return f"Accuracy: {accuracy:.4f}" ``` ## Apps and serving Deploy long-running services. - **FastAPI apps**: Deploy REST APIs and webhooks โ†’ **Apps > Native app integrations > FastAPI app** - **LLM serving**: Serve large language models with vLLM or SGLang โ†’ **Inference > Self-hosted endpoints > vLLM**, **Inference > Self-hosted endpoints > SGLang** - **Autoscaling**: Scale apps up and down based on traffic, including scale-to-zero โ†’ **Apps > Configure apps > /// script** - **Streamlit dashboards**: Deploy interactive data dashboards โ†’ **Apps > Native app integrations > Streamlit app** ## Notebooks Work interactively. - **Jupyter support**: Author and run workflows directly from Jupyter notebooks, and fetch workflow metadata (inputs, outputs, logs) โ†’ **Tasks > Build tasks > Notebooks** ## Next steps Ready to put it all together? Head to **Get started > Core concepts > Basic project: RAG** to build an end-to-end RAG pipeline with embeddings and a Streamlit app. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/settings === Set defaults at each level of the org, domain, and project hierarchy. # Settings Union.ai provides a hierarchical settings system for configuring default behavior at each level of your **Get started > Core concepts > Projects and domains**. Settings defined at a broader scope are inherited by narrower scopes, and any scope can override an inherited value. Most settings are **defaults only**: they apply when a task or workflow does not specify a value directly. Per-task configuration (such as `Resources` or `TaskEnvironment`) takes precedence over scope-level settings. The exception is `task_resource.max.*` settings, which are enforced as hard limits that cannot be exceeded by per-task configuration. ## Scope hierarchy Settings are stored at three scope levels: | Scope | Who manages it | Inherits from | |-------|---------------|---------------| | **Org** | Org admins | - | | **Domain** | Org admins | Org | | **Project** | Project owners, org admins | Domain, then org | When a setting has no value at the current scope, the next broader scope is consulted automatically. ## Editing settings Use `flyte edit settings` to view and modify settings interactively. The command opens your `$EDITOR` with a structured YAML file showing the current state of that scope. ```shell # Edit org-level settings flyte edit settings # Edit domain-level settings (inherits from org) flyte edit settings --domain production # Edit project-level settings (inherits from domain, then org) flyte edit settings --domain production --project ml-pipeline ``` The editor file has three sections: - **Local overrides**: values explicitly set at this scope. - **Inherited settings**: values resolved from a parent scope, shown as comments with their origin. - **Available settings**: all remaining keys, shown as commented placeholders with descriptions. Example editor file for a domain that has one local override and one inherited setting: ```yaml ### Settings for scope: DOMAIN(production) ## Remove or comment out a line to inherit that setting from the parent scope. ## Set a value to ~unset to explicitly clear it, blocking parent inheritance. ### Local overrides ## Default queue for task runs run.default_queue: fast-queue ### Inherited settings (uncomment to override at this scope) ## Kubernetes service account for task pods # security.service_account: default ## inherited from ORG ### Available settings (uncomment and edit to set at this scope) ## Base path for raw data storage (e.g. s3://my-bucket/prefix) # storage.raw_data_path: '' ## CPU resource quantity (e.g. "500m", "2") # task_resource.min.cpu: '' ## Memory resource quantity (e.g. "256Mi", "4Gi") # task_resource.min.memory: '' ... ``` The three comment prefixes have distinct roles: | Prefix | Meaning | |--------|---------| | `###` | Section header | | `##` | Field description or metadata | | `#` | Inactive setting: remove the leading `#` to activate | To set or change a value, uncomment the relevant line and edit it. To stop overriding a setting and revert to inheriting from the parent scope, comment out or delete the line entirely. When you save and close the editor, the CLI prints a summary of your changes and asks for confirmation before applying them: ``` Changes to apply: + run.default_queue: fast-queue ~ task_resource.min.cpu: 500m โ†’ 2 Apply these changes? [Y/n]: ``` > [!NOTE] > If your YAML fails to parse after saving, the editor reopens with an error header above your content so you can correct the syntax without losing your work. If you decline to reopen, your edits are saved automatically to `~/.flyte/settings-edit-.yaml`. ### Apply settings from a file For CI pipelines or scripted setup, use `--from-file` to skip the interactive editor entirely: ```shell flyte edit settings --domain production --from-file settings.yaml ``` The file should be a plain YAML mapping of dot-notation keys to values. Changes are printed and applied immediately without a confirmation prompt. ## Editing settings from Python The same scopes can be read and written from Python with `flyte.remote.Settings`: useful for scripted setup, audits, or wiring configuration into your own tooling. Fetch a scope with `get_settings_for_edit()`, inspect its values, then write them back with `update_settings()`. ```python import flyte.remote as remote # Fetch a scope. With no arguments you get the org scope; pass `domain`, # or `domain` and `project`, to narrow it. settings = remote.Settings.get_settings_for_edit(domain="production", project="ml-pipeline") # Effective settings: every key resolved through inheritance, each tagged # with the scope it came from (ORG, DOMAIN, or PROJECT). for s in settings.effective_settings: print(s.key, "=", s.value, "from", s.origin) # Local settings: only the keys explicitly overridden at *this* scope. for s in settings.local_settings: print(s.key, "=", s.value) # Every settable key, in dot notation: print(remote.Settings.available_keys()) ``` If you want plain dictionaries instead of the origin-annotated objects, `settings.effective_values()` and `settings.local_overrides()` each return a `{key: value}` mapping. To change settings, pass a mapping of dot-notation keys to `update_settings()`: CODE4 `update_settings()` **replaces the complete set of local overrides** for the scope the object was fetched for: keys you include are set locally, and any key you omit reverts to inheriting from the parent scope. The call uses optimistic locking against the version returned by `get_settings_for_edit()`. If another writer changed the same scope in between, re-fetch the scope and re-apply. To explicitly clear a value so it blocks parent inheritance (rather than reverting to it), use the `~unset` token in the `flyte edit settings` editor described above. > [!NOTE] > Treat `available_keys()` as the source of truth for which keys are settable on your version. The set grows over time, so prefer it over hardcoding key names. ## Available settings | Key | Type | Description | |-----|------|-------------| | `run.default_queue` | string | Default queue for task runs | | `security.service_account` | string | Kubernetes service account for task pods | | `storage.raw_data_path` | string | Base path for raw data storage (e.g. `s3://my-bucket/prefix`) | | `task_resource.min.cpu` | quantity | Minimum CPU request applied to task pods (e.g. `500m`, `2`) | | `task_resource.min.gpu` | quantity | Minimum GPU request applied to task pods (e.g. `1`) | | `task_resource.min.memory` | quantity | Minimum memory request applied to task pods (e.g. `256Mi`, `4Gi`) | | `task_resource.min.storage` | quantity | Minimum ephemeral storage request applied to task pods (e.g. `10Gi`) | | `task_resource.max.cpu` | quantity | Maximum CPU limit enforced on task pods: cannot be overridden by per-task configuration | | `task_resource.max.gpu` | quantity | Maximum GPU limit enforced on task pods: cannot be overridden by per-task configuration | | `task_resource.max.memory` | quantity | Maximum memory limit enforced on task pods: cannot be overridden by per-task configuration | | `task_resource.max.storage` | quantity | Maximum ephemeral storage limit enforced on task pods: cannot be overridden by per-task configuration | | `task_resource.mirror_limits_request` | bool | When `true`, resource limits are set equal to requests | | `labels` | map | Kubernetes labels applied to task pods | | `annotations` | map | Kubernetes annotations applied to task pods | | `environment_variables` | map | Environment variables injected into task pods | Quantity values use Kubernetes resource quantity format. Examples: `500m` (0.5 CPU), `2` (2 CPU), `256Mi` (256 mebibytes), `4Gi` (4 gibibytes). ## Inheritance rules **Scalar settings** (`run`, `security`, `storage`, and `task_resource` fields): the most specific scope with a value wins. If the project sets `run.default_queue`, that value is used. If not, the domain's value is checked, then the org's. **Map settings** (`labels`, `annotations`, and `environment_variables`): entries merge across scopes, with parent entries applied first and child entries overriding on key conflict. For example, if the org sets `LOG_LEVEL=info` and the project sets `LOG_LEVEL=debug`, the project's value wins. ### Explicitly clearing a value Set a value to `~unset` to stop inheritance at that scope without providing a value of its own. Child scopes can still define their own value. For map settings, `~unset` clears all accumulated entries from parent scopes. CODE5 ## Relationship to task configuration Most settings provide defaults only. Any value set directly on a task (through `Resources`, `TaskEnvironment`, task decorator arguments, or a per-invocation override) takes precedence over the scope-level setting for that task, regardless of which scope the setting was defined at. For example, if the org sets `task_resource.min.cpu: "500m"` as a default, a task with `@task(resources=Resources(cpu="2"))` will still use `2` CPUs. `task_resource.max.*` settings are the exception: they are enforced as hard limits and cannot be overridden by per-task configuration. If a task specifies a resource value above the configured maximum, the maximum takes precedence. ## Permissions Settings operations require the following actions, scoped to the org, domain, or project being accessed: | Operation | Required action | |-----------|----------------| | View settings (open the editor) | `view_flyte_inventory` | | Create or update settings | `register_flyte_inventory` | The **Contributor** built-in role includes both actions. The **Viewer** role includes `view_flyte_inventory` only. See **User management** for details on roles and how to assign them. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/basic-project === A worked two-stage RAG project: an offline embedding pipeline and the app that queries it. # Basic project: RAG This example demonstrates a two-stage RAG (Retrieval-Augmented Generation) pattern: an offline embedding pipeline that processes and stores quotes, followed by an online serving application that enables semantic search. ## Concepts covered - `TaskEnvironment` for defining task execution environments - `Dir` artifacts for passing directories between tasks - `AppEnvironment` for serving applications - `Parameter` and `RunOutput` for connecting apps to task outputs - Semantic search with sentence-transformers and ChromaDB ## Part 1: The embedding pipeline The embedding pipeline fetches quotes from a public API, creates vector embeddings using sentence-transformers, and stores them in a ChromaDB database. ### Setting up the environment The `TaskEnvironment` defines the execution environment for all tasks in the pipeline. It specifies the container image, required packages, and resource allocations: ```python # Define the embedding environment embedding_env = flyte.TaskEnvironment( name="quote-embedding", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "sentence-transformers>=2.2.0", "chromadb>=0.4.0", "requests>=2.31.0", ), resources=flyte.Resources(cpu=2, memory="4Gi"), cache="auto", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/embed.py* The environment uses: - `Image.from_debian_base()` to create a container with Python 3.12 - `with_pip_packages()` to install sentence-transformers and ChromaDB - `Resources` to request 2 CPUs and 4GB of memory - `cache="auto"` to enable automatic caching of task outputs ### Fetching data The `fetch_quotes` task retrieves quotes from a public API: ```python @embedding_env.task async def fetch_quotes() -> list[dict]: """ Fetch quotes from a public quotes API. Returns: List of quote dictionaries with 'quote' and 'author' fields. """ import requests print("Fetching quotes from API...") response = requests.get("https://dummyjson.com/quotes?limit=100") response.raise_for_status() data = response.json() quotes = data.get("quotes", []) print(f"Fetched {len(quotes)} quotes") return quotes ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/embed.py* This task demonstrates: - Async task definition with `async def` - Returning structured data (`list[dict]`) from a task - Using the `@embedding_env.task` decorator to associate the task with its environment ### Creating embeddings The `embed_quotes` task creates vector embeddings and stores them in ChromaDB: ```python @embedding_env.task async def embed_quotes(quotes: list[dict]) -> Dir: """ Create embeddings for quotes and store them in ChromaDB. Args: quotes: List of quote dictionaries with 'quote' and 'author' fields. Returns: Directory containing the ChromaDB database. """ import chromadb from sentence_transformers import SentenceTransformer print("Loading embedding model...") model = SentenceTransformer("all-MiniLM-L6-v2") # Create ChromaDB in a temporary directory db_dir = tempfile.mkdtemp() print(f"Creating ChromaDB at {db_dir}...") client = chromadb.PersistentClient(path=db_dir) collection = client.create_collection( name="quotes", metadata={"hnsw:space": "cosine"}, ) # Prepare data for insertion texts = [q["quote"] for q in quotes] ids = [str(q["id"]) for q in quotes] metadatas = [{"author": q["author"], "quote": q["quote"]} for q in quotes] print(f"Embedding {len(texts)} quotes...") embeddings = model.encode(texts, show_progress_bar=True) # Add to collection collection.add( ids=ids, embeddings=embeddings.tolist(), metadatas=metadatas, documents=texts, ) print(f"Stored {len(quotes)} quotes in ChromaDB") return await Dir.from_local(db_dir) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/embed.py* Key points: - Uses the `all-MiniLM-L6-v2` model from sentence-transformers (runs on CPU) - Creates a persistent ChromaDB database with cosine similarity - Returns a `Dir` artifact that captures the entire database directory - The `await Dir.from_local()` call uploads the directory to artifact storage ### Orchestrating the pipeline The main pipeline task composes the individual tasks: ```python @embedding_env.task async def embedding_pipeline() -> Dir: """ Main pipeline that fetches quotes and creates embeddings. Returns: Directory containing the ChromaDB database with quote embeddings. """ print("Starting embedding pipeline...") # Fetch quotes from API quotes = await fetch_quotes() # Create embeddings and store in ChromaDB db_dir = await embed_quotes(quotes) print("Embedding pipeline complete!") return db_dir ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/embed.py* ### Running the pipeline To run the embedding pipeline: ```python if __name__ == "__main__": flyte.init_from_config() run = flyte.run(embedding_pipeline) print(f"Embedding run URL: {run.url}") run.wait() print(f"Embedding complete! Database directory: {run.outputs()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/embed.py* ```bash uv run embed.py ``` The pipeline will: 1. Fetch 100 quotes from the API 2. Create embeddings using sentence-transformers 3. Store everything in a ChromaDB database 4. Return the database as a `Dir` artifact ## Part 2: The serving application The serving application provides a Streamlit web interface for searching quotes using the embeddings created by the pipeline. ### App environment configuration The `AppEnvironment` defines how the application runs: ```python # Define the app environment env = AppEnvironment( name="quote-search-app", description="Semantic search over quotes using embeddings", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit>=1.41.0", "sentence-transformers>=2.2.0", "chromadb>=0.4.0", ), args=["streamlit", "run", "app.py", "--server.port", "8080"], port=8080, resources=flyte.Resources(cpu=2, memory="4Gi"), parameters=[ Parameter( name="quotes_db", value=RunOutput(task_name="quote-embedding.embedding_pipeline", type="directory"), download=True, env_var="QUOTES_DB_PATH", ), ], include=["app.py"], requires_auth=False, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/serve.py* Key configuration: - `args` specifies the command to run the Streamlit app - `port=8080` exposes the application on port 8080 - `parameters` defines inputs to the app: - `RunOutput` connects to the embedding pipeline's output - `download=True` downloads the directory to local storage - `env_var="QUOTES_DB_PATH"` makes the path available to the app - `include=["app.py"]` bundles the Streamlit app with the deployment ### The Streamlit application The app loads the ChromaDB database using the path from the environment variable: ```python # Load the database @st.cache_resource def load_db(): db_path = os.environ.get("QUOTES_DB_PATH") if not db_path: st.error("QUOTES_DB_PATH environment variable not set") st.stop() client = chromadb.PersistentClient(path=db_path) collection = client.get_collection("quotes") model = SentenceTransformer("all-MiniLM-L6-v2") return collection, model collection, model = load_db() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/app.py* The search interface provides a text input and result count slider: ```python # Search interface query = st.text_input("Enter your search query:", placeholder="e.g., love, wisdom, success") top_k = st.slider("Number of results:", min_value=1, max_value=20, value=5) col1, col2 = st.columns([1, 1]) with col1: search_button = st.button("Search", type="primary", use_container_width=True) with col2: random_button = st.button("Random Quote", use_container_width=True) st.divider() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/app.py* When the user searches, the app encodes the query and finds similar quotes: ```python if search_button and query: # Encode query and search query_embedding = model.encode([query])[0].tolist() results = collection.query( query_embeddings=[query_embedding], n_results=top_k, ) if results["documents"] and results["documents"][0]: for i, (doc, metadata, distance) in enumerate( zip(results["documents"][0], results["metadatas"][0], results["distances"][0]) ): similarity = 1 - distance # Convert distance to similarity st.markdown(f'**{i+1}.** "{doc}"') st.caption(f"โ€” {metadata['author']} | Similarity: {similarity:.2%}") st.write("") else: st.info("No results found.") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/app.py* The app also includes a random quote feature: ```python elif random_button: # Get a random quote from the collection all_data = collection.get(limit=100) if all_data["documents"]: idx = random.randint(0, len(all_data["documents"]) - 1) quote = all_data["documents"][idx] author = all_data["metadatas"][idx]["author"] st.markdown(f'**"{quote}"**') st.caption(f"โ€” {author}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/app.py* ### Deploying the app To deploy the quote search application: ```python if __name__ == "__main__": flyte.init_from_config() # Deploy the quote search app print("Deploying quote search app...") deployment = flyte.serve(env) print(f"App deployed at: {deployment.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/basic-project/serve.py* ```bash uv run serve.py ``` The app will be deployed and automatically connected to the embedding pipeline's output through the `RunOutput` parameter. ## Key takeaways 1. **Two-stage RAG pattern**: Separate offline embedding creation from online serving for better resource utilization and cost efficiency. 2. **Dir artifacts**: Use `Dir` to pass entire directories (like databases) between tasks and to serving applications. 3. **RunOutput**: Connect applications to task outputs declaratively, enabling automatic data flow between pipelines and apps. 4. **CPU-friendly embeddings**: The `all-MiniLM-L6-v2` model runs efficiently on CPU, making this pattern accessible without GPU resources. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/core-concepts/leases === How Union.ai tracks work across clusters, why you occasionally see `lease expired`, and how the system protects you from runaway compute. # Leases When you run a task on Union.ai, your code doesn't execute on the control plane: it runs on a compute cluster, which might be in your cloud account, in another region, or one of several clusters attached to your account. Union.ai has to hand a piece of work to a cluster, then keep track of whether that work is actually getting done. It does this with **leases**. You normally never have to think about leases. But occasionally you'll see a message like: ``` lease expired for action a0 ... ``` This page explains what that means, why it happens, and why, most of the time, it's the system protecting you rather than something going wrong. ## What a lease is A lease is a time-bound grant of work. Union.ai hands a unit of work (an **Get started > Core concepts > Runs and actions**) to a worker on a cluster and says, in effect: *"You own this for now. Keep telling me you're still on it."* Think of it like **renting an apartment**: - The landlord (the Union.ai control plane) owns the property (your work) and hands a tenant (a cluster worker) the keys under a lease. - The tenant doesn't pay rent once a year; they pay on a regular schedule. In Union.ai, the worker sends a **heartbeat** every few seconds: *"still working on it."* - As long as the rent keeps coming in, the tenant keeps the apartment. As long as the heartbeats keep coming in, the worker keeps the work. This heartbeat is the whole point. It's how Union.ai knows (continuously, not just at the start) that your work is alive and progressing. ## Why leases exist Union.ai hands work to machines it doesn't fully control, and machines fail in messy ways: - A **cluster goes offline**: a network partition, a dropped connection, a zone outage. - A **component on the cluster fails**: the worker process crashes or hangs. - The **control plane itself blips**: a brief restart or deployment. The hard part isn't any single failure. It's that from the control plane's point of view, **all of these look the same**: the heartbeats stopped. When a worker goes silent, Union.ai cannot tell the difference between: - The worker **died** (the work needs to be handed to someone else), and - The worker is **alive but unreachable** and still grinding away on your task. This is one of the genuinely hard problems in distributed systems. Leases are how Union.ai makes a safe decision without being able to see the truth directly. ## What happens when heartbeats stop When a worker stops heartbeating, Union.ai does **not** evict it immediately. A missed heartbeat is usually nothing: a momentary network hiccup, a quick deployment, a transient glitch. Just like a landlord wouldn't change the locks the day rent is one hour late, the system gives a **grace period**. During that grace period the lease is still valid. If heartbeats resume (the network heals, the worker reconnects) the worker simply picks up where it left off. **No work is lost and nothing is re-run.** This is the common case, and it's invisible to you. But if enough time passes (a window that Union.ai configures) and the worker is *still* silent, the system reaches a point where it can no longer safely assume the work is in good hands. At that point it has to **reap the lease**. This is what you see as `lease expired`. The system reaps a silent lease for two reasons, and both are about protecting you: 1. **To make forward progress.** If the original worker really is gone, your run would otherwise hang forever. Reaping the lease frees the work to be reassigned to a healthy worker so it can actually finish. 2. **To guarantee exactly one owner.** Union.ai must never have two workers both believing they own the same action: that would corrupt results and waste compute. Reaping the old lease, and refusing to accept any further reports from it, ensures that when the work is reassigned, **exactly one** worker owns it. The mechanisms behind these are **lease expiration** (the old grant is invalidated) and **lease failover** (the work is handed to a new worker). ## Why this is the safe trade-off Here's the key design decision, and the part most relevant to you as someone who cares about **failures and cost**: > [!NOTE] Correctness over runaway compute > Union.ai would rather **occasionally redo a small amount of work** than let a task it can no longer account for keep running unchecked. Imagine the alternative. A worker becomes unreachable but is secretly still running your job (burning a node, maybe a multi-GPU node) and Union.ai can't see it, can't stop it, and can't trust its output. That's exactly the **runaway compute** and surprise cost that you don't want. By bounding every piece of work with a lease, Union.ai ensures there's no orphaned, unaccounted-for task quietly running up a bill. So when a lease expires and the work is reassigned, the cost is at worst **redoing one action**. The benefit is a hard guarantee that compute is always accounted for, and results are always correct. ## How often does this actually happen? Rarely. Union.ai uses sophisticated failure-detection and the grace periods are tuned so that the everyday churn of distributed systems (momentary network issues, routine deployments, brief glitches) is **absorbed automatically**. The system is designed to auto-heal in all of those cases, and in the overwhelming majority of runs you'll never see a lease expiration at all. When you *do* see one, it generally means a real, sustained failure occurred: a cluster was unreachable for long enough that continuing to trust the lease would have been unsafe. ## What to do when you see `lease expired` In most cases, **nothing**. The system has already done the right thing: - The expired lease was reaped, and the action was retried on a healthy worker. The retry you see in the UI is the failover working as intended. - If the run completed successfully after the retry, your results are correct and complete. It's worth a closer look only if you see lease expirations **repeatedly** on the same run or cluster. That pattern points to an underlying environment problem (a chronically unhealthy cluster, persistent network issues, or under-provisioned nodes) rather than the lease mechanism itself. In that case, check the health of the affected cluster or reach out to your platform team. ## The takeaway A lease expiration is **not a system failure**; it's the system doing its job. It's Union.ai refusing to let work run unaccounted-for, guaranteeing that every action has exactly one owner, and making sure your run still makes progress when a cluster lets it down. It's the trade-off in your favor: a small chance of redoing work, in exchange for never paying for runaway compute and never trusting a corrupt result. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/run-modes === Run the same task code locally in your Python process, or remotely on a devbox or a deployed cluster. # Run modes A run is either **local** or **remote**. The same task code runs unchanged either way, so you can choose the right trade-off between speed and fidelity at each stage of development. ## Local and remote - **Local** runs the task in-process, directly in your Python interpreter. There is no cluster and no container. Select it with `flyte run --local` or `flyte.with_runcontext(mode="local")`. - **Remote** runs the task on a Flyte backend, inside a container that a cluster schedules. It is the default for `flyte run`, and you can select it explicitly with `mode="remote"`. Your configuration decides which backend. A remote backend is either a **devbox** on your own machine or a **deployed cluster** in the cloud or on-premises. "Remote" describes how the run executes, not where the machine is: a devbox run is remote even though the devbox runs on your laptop. This is how the CLI and SDK use the word throughout. | Mode | How the task runs | Backend | |------|-------------------|---------| | Local (`--local`) | In-process | None | | Remote | In a container, on a cluster | A devbox on your machine | | Remote | In a container, on a cluster | A deployed cluster, in the cloud or on-premises | ### Watching a local run A local run can also report its progress to Union.ai. Run with `--tracked`, which implies `--local`, and the run still executes in-process on your machine, but it appears in the console under **Tracked Runs**. Tracking changes what you can see, not where the run executes. See **Get started > Run modes > Run locally in Python > Track local runs in the console**. ### **Get started > Run modes > Run locally in Python** Run tasks and apps directly in your local Python process with no Kubernetes cluster or Docker required. Ideal for rapid iteration and debugging. ### **Get started > Run modes > Run on the Devbox** Run tasks and apps in a lightweight Flyte cluster using Docker. Get the full Flyte UI and backend experience on your machine. ### **Get started > Run modes > Run on a deployed cluster** Run tasks and apps on a deployed cluster, in the cloud or on-premises, with full production capabilities including GPUs and distributed compute. | Aspect | Local (`--local`) | Remote: devbox | Remote: deployed cluster | |--------|-------------------|--------|--------| | **โšก๏ธ Execution** | In-process Python | On-cluster, local Docker | On-cluster, cloud or on-premises | | **๐Ÿณ Docker required** | No | Yes | No (remote build) | | **๐Ÿ’ป Flyte UI** | TUI, or the console with `--tracked` | Yes (`localhost:30080`) | Yes | | **๐Ÿ“ฆ Container images** | Ignored | Built locally | Built locally or remotely | | **๐Ÿ”€ Parallelism** | Sequential | Cluster-level | Cluster-level | | **โญ๏ธ Best for** | Fast iteration, debugging | Testing container builds, full Flyte features | Production, GPUs, scale | The same task code runs unchanged on all three. Start with local execution for fast feedback, move to the Devbox to validate on-cluster execution, then run on a deployed cluster for production. ## Subpages - **Get started > Run modes > Run locally in Python** - Run tasks and apps directly in your local Python process with no Kubernetes cluster or Docker required. Ideal for rapid iteration and debugging. - **Get started > Run modes > Run on the Devbox** - Run tasks and apps in a lightweight Flyte cluster using Docker. Get the full Flyte UI and backend experience on your machine. - **Get started > Run modes > Run on a deployed cluster** - Run tasks and apps on a deployed cluster, in the cloud or on-premises, with full production capabilities including GPUs and distributed compute. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/run-modes/running-locally === Run tasks and apps directly in your local Python process with no Kubernetes cluster or Docker required. Ideal for rapid iteration and debugging. # Run locally in Python Flyte runs locally with no cluster or Docker needed. Install the SDK, write tasks, and run them on your machine. When you're ready to scale, drop the `--local` flag and the same code runs on-cluster, on whichever cluster your configuration points at. > [!INFO] Try it in your browser > Follow along with this guide in Google Colab without installing anything locally. > > [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/unionai/unionai-examples/blob/main/v2/user-guide/getting-started/ten_minutes_to_flyte.ipynb) ## Getting started If you haven't already, install the SDK and configure local persistence as described in the **Get started > Quickstart**. ## Running tasks locally The `--local` flag tells Flyte to execute a task in your local Python environment rather than on-cluster. Add `--tui` to launch the interactive Terminal UI for real-time monitoring. Basic local execution: ```bash flyte run --local hello.py main ``` With the interactive TUI: ```bash flyte run --local --tui hello.py main ``` You can also run tasks programmatically using the Python SDK with `flyte.run()`. See [Run and deploy tasks](../../tasks/task-deployment/_index) for details. ## Two ways to run a task There are two distinct ways to run a task, and it's easy to confuse them when you're new. They differ in *who* calls `flyte.run()`. ### As a script: `python hello.py` You call `flyte.run()` yourself, from inside an `if __name__ == "__main__":` block, and execute the file with plain Python: ```python # hello.py import flyte env = flyte.TaskEnvironment(name="hello_env") @env.task def main(x_list: list[int] = list(range(10))) -> float: return sum(x_list) / len(x_list) if __name__ == "__main__": flyte.init_from_config() # load your local config (.flyte/config.yaml) run = flyte.run(main) # call the task; pass inputs as keyword args print(run.name) run.wait() ``` Then run the file as an ordinary Python script: ```bash python hello.py ``` Because *your code* decides which task runs and with what inputs, you pass inputs directly as arguments to `flyte.run()`, for example `flyte.run(main, x_list=[1, 2, 3])`. Use `flyte.run.aio(...)` from within async code. ### Via the CLI: `flyte run` The `flyte run` CLI does the calling for you. You don't need a `__main__` block; instead you name the file and the task on the command line, and the CLI invokes it: ```bash flyte run --local hello.py main ``` The task's **parameters become CLI options**. Each task input maps to a `--` flag (run `flyte run --local hello.py main --help` to see them, with their defaults). For example, to override `x_list`: ```bash flyte run --local hello.py main --x_list '[1, 2, 3]' ``` > [!NOTE] > A common first-run trip-up: invoking `flyte run` against a task whose inputs have **no defaults** without supplying them. The CLI stops before running the task and names each missing input with its type, for example `Missing required parameter(s): --x (type: INTEGER)`. (`bool` inputs default to `False` and `Optional` inputs to `None`, so they are never reported missing.) If you hit this, check `--help` and pass the required `--` values (or give the parameters defaults in the task signature, as `main` does above). ## Terminal UI The TUI is an interactive split-screen dashboard. Task tree on the left, details and logs on the right. ```bash flyte run --local --tui hello.py main ``` ![TUI agent run](../../../_static/images/user-guide/quickstart/run-tui.png) What you see: - **Task tree** with live status: `โ—` running, `โœ“` done, `โœ—` failed - **Cache indicators**: `$` cache hit, `~` cache enabled but missed - **Live logs**: `print()` output streams in real time - **Details panel**: inputs, outputs, timing, report paths - **Traced sub-tasks**: child nodes for `@flyte.trace` decorated functions **Keyboard shortcuts:** | Key | Action | |-----|--------| | `q` | Quit | | `d` | Details tab | | `l` | Logs tab | ### Exploring past runs If you created a config file via `flyte create config --local-persistence`, Flyte persists the inputs and outputs of every task run locally, so you can always go back and inspect what a task received and produced. Launch the TUI on its own to browse past runs, compare inputs and outputs, and review reports: ```bash flyte start tui ``` ## Track local runs in the console A local run normally leaves no trace on the control plane. Add `--tracked` and the run still executes on your machine, but its progress is reported to Union.ai so you can watch it in the console: ```bash flyte run --tracked hello.py main ``` Tracked runs appear in the console under **Tracked Runs**, which is its own section in the project sidebar. They are not listed under **Runs**, which shows runs the platform executed for you. The command prints a link to the run when it starts. Tracking covers the run's actions and attempts, their phases, and their inputs, outputs, reports and cache status. Logs are not reported, so `print()` output stays in your terminal. Reporting never gets in the way of the run itself: if the control plane is unreachable, the failure is logged and your local run finishes normally. You can abort a tracked run from the console, but this cannot stop the process running on your machine. Per-organization limits apply to tracked runs: concurrent runs and actions, actions per run, and run creations per month. If you do not have a workflow to hand yet, `hello` runs a built-in one and needs no files at all: ```bash flyte run --tracked hello ``` Use `flyte create config --local-tracked` to track every local run without passing the flag. For the full option reference, including strict reporting and run-name rules, see **Tasks > Run and deploy tasks > Run command options**. To track a run started from Python with `flyte.run()`, see **Tasks > Run and deploy tasks > How task run works > Tracking a local run**. --- ## What works locally Most Flyte features work in both in-process and on-cluster execution. The table below summarizes how each feature behaves in-process. | Feature | Local behavior | Details | |---------|---------------|---------| | **Caching** | Outputs stored in local SQLite, keyed on task name and inputs. Same inputs = instant results. | **Tasks > Configure tasks > Caching** | | **Tracing** | `@flyte.trace` functions appear as child nodes in the TUI with their own timing, inputs, and outputs. | **Tasks > Build tasks > Traces** | | **Reports** | HTML files saved locally. TUI shows the file path. | **Tasks > Build tasks > Reports** | | **Serving** | Run apps locally with `python serve.py` or `flyte.with_servecontext(mode="local")`. | [Serve and deploy apps](../../apps/serve-and-deploy-apps/_index) | | **Plugins** | Same decorators and APIs as remote. Secrets come from environment variables. | [Integrations](../../../api-reference/integrations/_index) | | **Secrets** | Read from environment variables you export, or from local files for file-mounted secrets. Flyte does not load `.env` files. No `flyte create secret` needed. | **Tasks > Configure tasks > Secrets** | > [!NOTE] Visibility is the exception > With `--tracked`, a local run also reports its state to the control plane and appears in the console. > See **Get started > Run modes > Run locally in Python > Track local runs in the console**. --- ## From in-process to on-cluster The same code runs in both environments. Here's what changes: | Aspect | Local | Remote (devbox or deployed cluster) | |--------|-------|--------| | **Run pipeline** | `flyte run --local` | `flyte run` | | **TUI** | `--tui` flag | Dashboard in Flyte UI | | **Caching** | Local SQLite | Cluster-wide distributed cache | | **Reports** | Local HTML files | Rendered in the Flyte UI | | **Serving** | `python serve.py` | `flyte deploy serve.py env` | | **Secrets** | Environment variables you export | `flyte create secret` / `flyte.Secret` | | **Compute** | Your CPU/GPU | `Resources(cpu=2, memory="4Gi", gpu=1)` | The **Get started > Core concepts > TaskEnvironment** is the bridge. Locally, image and resource settings are ignored. On the cluster, Flyte builds containers and allocates compute from the same definition. --- ## Next steps - **Get started > Run modes > Run on the Devbox**: Run a full Flyte cluster on your machine with Docker to test remote execution before moving to a deployed cluster. - **Get started > Run modes > Run on a deployed cluster**: Configure the CLI and SDK to run on a cluster in the cloud or on-premises. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/run-modes/running-devbox === Run tasks and apps in a lightweight Flyte cluster using Docker. Get the full Flyte UI and backend experience on your machine. # Run on the Devbox The Flyte 2 devbox is a great way to try a simplified Union.ai cluster on your local machine. It's a lightweight cluster that runs on your machine with Docker. It includes a UI, scheduler, and object store, so you can test on-cluster execution without connecting to a deployed cluster. > [!NOTE] Try Devbox in your browser > Prefer not to install anything locally? Create a Devbox in GitHub Codespaces. > > [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/flyteorg/flyte-devbox-codespace?quickstart=1) ## What you'll need - Python 3.10+ in a virtual environment - [Docker](https://docs.docker.com/get-docker/) installed and running - [kubectl](https://kubernetes.io/docs/tasks/tools/) ## Install the SDK If you haven't already, install the `flyte` package: ```bash pip install flyte ``` ## Start the devbox Launch the devbox: ### CPU ```bash flyte start devbox ``` ### GPU ```bash flyte start devbox --gpu ``` > **๐Ÿ“ Note** > > The `--gpu` flag requires an NVIDIA-enabled host. It does not support AMD GPUs. For a Mac's GPU, use the **Apple Silicon** tab. ### Apple Silicon ```bash flyte start devbox --apple-silicon ``` Requires `flyte` 2.12.0 or later and [uv](https://docs.astral.sh/uv/). See **Get started > Run modes > Run on the Devbox > Using the Apple Silicon GPU**. ![Devbox start](../../../_static/images/user-guide/run-modes/flyte-start-devbox.png) This pulls the necessary containers and starts a local Flyte instance. Once ready, the Flyte UI is available at `http://localhost:30080`. > **๐Ÿ“ Note** > > The first start may take a few minutes while Docker images are downloaded. ## Check the devbox status > [!NOTE] > `flyte get devbox` requires flyte 2.6.2 or later. To see whether the devbox is up, and where it is: ```bash flyte get devbox ``` This reports the run state, the UI and image registry endpoints, the container image version in use, and where the cluster keeps its state on disk. It is the quickest way to tell a devbox that is still starting from one that is ready. Add `--no-probes` to skip the readiness probe and the container resource sample, which makes the check faster and works offline: ```bash flyte get devbox --no-probes ``` For a machine-readable report, pass an output format to the top-level command: ```bash flyte -of json-raw get devbox ``` ## Configure Create a config file that points to the devbox: ```bash flyte create config --devbox ``` This creates `.flyte/config.yaml` configured to talk to your local devbox cluster. The `--devbox` flag requires flyte 2.6.1 or later. It is a shortcut for the explicit form, which you need on earlier versions: ```bash flyte create config \ --endpoint localhost:30080 \ --project flytesnacks \ --domain development \ --builder local \ --insecure ``` Both forms write the same config file. One difference: in an interactive terminal the explicit form offers to reuse a Docker login as your image registry, while `--devbox` skips that prompt, because the devbox pushes to its own in-cluster registry. `--devbox` cannot be combined with `--endpoint`, but you can still override the project and domain alongside it: ```bash flyte create config --devbox --project my-project --domain staging ``` ## Run a workflow on the devbox Using the same `hello.py` from the **Get started > Quickstart**: ```python # hello.py import flyte # The `hello_env` TaskEnvironment is assigned to the variable `env`. # It is then used in the `@env.task` decorator to define tasks. # The environment groups configuration for all tasks defined within it. env = flyte.TaskEnvironment(name="hello_env") # We use the `@env.task` decorator to define a task called `fn`. @env.task def fn(x: int) -> int: # Type annotations are required slope, intercept = 2, 5 return slope * x + intercept # We also use the `@env.task` decorator to define another task called `main`. # This is the entrypoint task of the workflow. # It calls the `fn` task defined above multiple times using `flyte.map`. @env.task def main(x_list: list[int] = list(range(10))) -> float: y_list = list(flyte.map(fn, x_list)) # flyte.map is like Python map, but runs in parallel. y_mean = sum(y_list) / len(y_list) return y_mean CODE10bash flyte run hello.py main ``` Without the `--local` flag, the workflow runs on the devbox cluster rather than in your local Python process. Tasks execute inside containers, exactly as they would on a deployed cluster. ## View results in the UI Open `http://localhost:30080` to see your workflow execution in the Flyte UI. You can inspect task inputs, outputs, logs, and execution timelines. ![Devbox UI](../../../_static/images/user-guide/run-modes/flyte-ui-devbox.png) ## Stop the devbox When you're done, shut down the cluster: CODE11 ## Inline configuration Skip the config file entirely by passing parameters directly. ### Programmatic Use `flyte.init`: CODE12 ### CLI Some parameters go after `flyte`, others after the subcommand: CODE13 See the [CLI reference](../../../api-reference/flyte-cli.md) for details. ## Delete the devbox CODE14 ## Using a CUDA-enabled GPU host If you started the devbox with `flyte start devbox --gpu`, you can use GPUs in your workflows. CODE15 ## Using the Apple Silicon GPU If you started the devbox on a Mac with `flyte start devbox --apple-silicon`, tasks and apps that request the Apple Silicon accelerator run natively on the Mac instead of in their container. Their code can use the Mac's GPU through Metal, for example PyTorch's `mps` device or MLX. Request it with `gpu="AppleSilicon"` or `gpu=flyte.APPLE_SILICON()`: CODE16 `"AppleSilicon:1"` is also accepted. A count above 1, such as `"AppleSilicon:2"`, is rejected. Requirements: - `flyte` 2.12.0 or later. - [uv](https://docs.astral.sh/uv/) on the Mac. `--apple-silicon` refuses to start without it. - A devbox created from the current devbox image. Starting a stopped devbox doesn't pull a new image, so recreate an older devbox: CODE17 `--apple-silicon` can't be combined with `--gpu` or with dev mode (`--dev`). Because workload code runs outside any sandbox, the flag publishes the devbox's ports on `127.0.0.1` only. They aren't reachable from the network, but other software on the Mac can reach them. To restart a stopped Apple Silicon devbox, run `flyte start devbox`. It restarts the Apple Silicon bridge without the flag. Apple Silicon is a devbox-only accelerator, and a workload that requests it never falls back to the CPU: - On a devbox started without `--apple-silicon`, the task fails with `APPLE_SILICON_NOT_AVAILABLE`, and the message says to restart the devbox with the flag. - On a remote cluster whose backend includes Apple Silicon support, the task fails with `APPLE_SILICON_NOT_AVAILABLE`. - On a backend that predates Apple Silicon support, including an older devbox image, the task's pod stays `Pending` instead of failing. - Where a task would fail with `APPLE_SILICON_NOT_AVAILABLE`, deploying an app that requests Apple Silicon is refused with the same error. ## Next steps - [**Core concepts**](../core-concepts/_index): Understand `TaskEnvironment`s, tasks, runs, and actions through working examples. - **Get started > Run modes > Run on a deployed cluster**: Configure the CLI and SDK to run on a cluster in the cloud or on-premises. === PAGE: https://www.union.ai/docs/v2/union/user-guide/get-started/run-modes/running-remote === Run tasks and apps on a deployed cluster, in the cloud or on-premises, with full production capabilities including GPUs and distributed compute. # Run on a deployed cluster This guide covers setting up your local development environment and configuring the `flyte` CLI and SDK to connect to your Union.ai instance. ## Prerequisites - **Python 3.10+** - **`uv`**: A fast Python package installer. See the [`uv` installation guide](https://docs.astral.sh/uv/getting-started/installation/). - Access to a Union.ai instance (URL and a project where you can run workflows) > [!NOTE] > Don't have a Union.ai instance yet? See [Platform deployment](../../../deployment/_index) > to stand one up, or use the **Get started > Run modes > Run on the Devbox** to run a cluster on your machine in Docker. ## Install the flyte package Create a virtual environment and install the `flyte` package: ```bash uv venv source .venv/bin/activate uv pip install flyte ``` > [!NOTE] > On Windows, use `.venv\Scripts\activate` instead. Verify installation: ```bash flyte --version ``` ## Configuration file As we did in **Get started > Quickstart**, use `flyte create config` to create a configuration file: ```bash flyte create config \ --endpoint my-org.my-company.com \ --domain development \ --project my-project \ --builder remote ``` This creates `./.flyte/config.yaml`: ```yaml admin: endpoint: dns:///my-org.my-company.com image: builder: remote task: org: my-org domain: development project: my-project ``` > [!NOTE] > The registry (`--registry`, the `image.registry` config entry, or the `FLYTE_IMAGE_REGISTRY` environment variable) sets where **locally-built** images are pushed. It applies whenever the builder is `local` or `local-podman`: always on Flyte OSS, and on Union if you opt out of remote builds. With `--builder remote` (the Union default) images are built on the cluster, so no registry is required, which is why the Union example above omits it. Setting the registry from config requires flyte 2.5.9 or later.
Full example with all options Create a custom config file with all available options: ```bash flyte create config \ --endpoint my-org.my-company.com \ --org my-org \ --domain development \ --project my-project \ --builder remote \ --registry ghcr.io/my-org \ --insecure \ --output my-config.yaml \ --force ``` See the **Flyte CLI > flyte create config** for all parameters.
Config properties explained **`admin`**: Connection details for your Union.ai instance. - `endpoint`: URL with `dns:///` prefix. If your UI is at `https://my-org.my-company.com`, use `dns:///my-org.my-company.com`. - `insecure`: Set to `true` only for local instances without TLS. **`image`**: Docker image building configuration. - `builder`: How container images are built. - `remote` (Union): Images built on Union's infrastructure. - `local` (Flyte OSS): Images built on your machine. Requires Docker. See **Tasks > Configure tasks > Container images > Image building**. - `local-podman`: Images built on your machine with Podman instead of Docker. Requires flyte 2.10.6 or later. See **Tasks > Configure tasks > Container images > Image building > Local image building**. - `registry`: Optional registry prefix to use for image builds. This is helpful when you want the SDK to push or pull images from a custom registry without changing your code. You can also set it with the `FLYTE_IMAGE_REGISTRY` environment variable. **`task`**: Default settings for task execution. - `org`: Organization name (usually matches the first part of your endpoint URL). - `domain`: Environment separation (`development`, `staging`, `production`). - `project`: Default project for deployments. Must already exist on your instance. See **Get started > Core concepts > Projects and domains** for how to create projects.
## Using the configuration You can reference your config file explicitly or let the SDK find it automatically. ### Explicit configuration ### Programmatic Initialize with `flyte.init_from_config`: ```python flyte.init_from_config("my-config.yaml") run = flyte.run(main) ``` ### CLI Use `--config` or `-c`: ```bash flyte --config my-config.yaml run hello.py main flyte -c my-config.yaml run hello.py main ```
Configuration precedence Without an explicit path, the SDK searches these locations in order: 1. `./config.yaml` 2. `./.flyte/config.yaml` 3. `UCTL_CONFIG` environment variable 4. `FLYTECTL_CONFIG` environment variable 5. `~/.union/config.yaml` 6. `~/.flyte/config.yaml`
### Programmatic ```python flyte.init_from_config() ``` ### CLI ```bash flyte run hello.py main ``` ### Check current configuration ```bash flyte get config ``` Output: ```bash CLIConfig( Config( platform=PlatformConfig(endpoint='dns:///my-org.my-company.com', scopes=[]), task=TaskConfig(org='my-org', project='my-project', domain='development'), source=PosixPath('/Users/me/.flyte/config.yaml') ), ... ) ``` ## Inline configuration Skip the config file entirely by passing parameters directly. ### Programmatic Use `flyte.init`: ```python flyte.init( endpoint="dns:///my-org.my-company.com", org="my-org", project="my-project", domain="development", ) ``` ### CLI Some parameters go after `flyte`, others after the subcommand: ```bash flyte \ --endpoint my-org.my-company.com \ --org my-org \ run \ --domain development \ --project my-project \ hello.py \ main ``` See the **Flyte CLI** for details. See related methods: * `flyte.init_from_api_key` * `flyte.init_from_config` * `flyte.init_in_cluster` * `flyte.init_passthrough` ## Next steps With your environment fully configured, you're ready to build: - [**Core concepts**](../core-concepts/_index): Understand `TaskEnvironment`s, tasks, runs, and actions through working examples. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks === Configure, build, and deploy the durable batch workloads that everything else is made of. # Tasks A task is a Python function that runs remotely in a container. Tasks are the unit of work in Flyte: they are versioned, cached, retried, and recorded, so a run you start today can be reproduced and inspected later. Every task belongs to a `TaskEnvironment`, which declares the container image, the resources, and the secrets the task needs. You define the environment once and reuse it across the tasks that share it. ```python env = flyte.TaskEnvironment(name="etl", image=flyte.Image.from_debian_base()) @env.task def extract(url: str) -> str: ... ``` Tasks compose. Calling one task from another builds the graph as your code executes, so fanout, branching, and error handling are ordinary Python rather than a separate DSL. A task usually runs in a single container, but it doesn't have to. For distributed workloads such as multi-node model training, a `flyte.clustered.ClusteredTaskEnvironment` runs one task across a gang of pods at once, wiring up a `torchrun` rendezvous so your task body executes on every worker: ```python import flyte from flyte.clustered import ClusteredTaskEnvironment, TorchRun env = ClusteredTaskEnvironment( name="ddp_env", image=flyte.Image.from_debian_base().with_pip_packages("torch"), replicas=2, # number of pods (nodes) nproc_per_node=1, # worker processes per pod runtime=TorchRun(), ) @env.task async def train() -> float: import torch.distributed as dist dist.init_process_group() # RANK / WORLD_SIZE / MASTER_ADDR already set ... ``` See **Tasks > Configure tasks > Clustered task environment** for the full guide. The three sections below follow the order you meet them in: describe the environment a task runs in, write the task logic, then get it onto a cluster. ### **Tasks > Configure tasks** Define `TaskEnvironment`s for container images, resources, secrets, caching, retries, and more. ### **Tasks > Build tasks** Compose tasks with fanout, parallelism, error handling, traces, files, and DataFrames. ### **Tasks > Run and deploy tasks** Use `flyte run` for iteration or `flyte deploy` to register a stable task version. ## Related Tasks are also the substrate for the other two building blocks. An app serves a task's results over HTTP; an agent drives tasks in a loop. ### **Apps** Long-running services for dashboards, APIs, and model endpoints. ### **Agents** Durable, self-healing agents built from tasks and apps. ## Subpages - **Tasks > Configure tasks** - Define `TaskEnvironment`s for container images, resources, secrets, caching, retries, and more. - **Tasks > Build tasks** - Compose tasks with fanout, parallelism, error handling, traces, files, and DataFrames. - **Tasks > Run and deploy tasks** - Use `flyte run` for iteration or `flyte deploy` to register a stable task version. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration === Define `TaskEnvironment`s for container images, resources, secrets, caching, retries, and more. # Configure tasks As we saw in **Get started > Quickstart**, you can run any Python function as a task in Flyte just by decorating it with `@env.task`. This allows you to run your Python code in a distributed manner, with each function running in its own container. Flyte manages the spinning up of the containers, the execution of the code, and the passing of data between the tasks. The simplest possible case is a `TaskEnvironment` with only a `name` parameter, and an `env.task` decorator, with no parameters: ``` env = flyte.TaskEnvironment(name="my_env") @env.task async def my_task(name:str) -> str: return f"Hello {name}!" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/task_config.py* > [!NOTE] > Notice how the `TaskEnvironment` is assigned to the variable `env` and then that variable is > used in the `@env.task`. This is what connects the `TaskEnvironment` to the task definition. > > In the following we will often use `@env.task` generically to refer to the decorator, > but it is important to remember that it is actually a decorator attached to a specific > `TaskEnvironment` object, and the `env` part can be any variable name you like. This will run your task in the default container environment with default settings. But, of course, one of the key advantages of Flyte is the ability to control the software environment, hardware environment, and other execution parameters for each task, right in your Python code. ## Task configuration levels Task configuration is done at three levels. From most general to most specific, they are: * The `TaskEnvironment` level: setting parameters when defining the `TaskEnvironment` object. * The `@env.task` decorator level: Setting parameters in the `@env.task` decorator when defining a task function. * The task invocation level: Using the **Tasks > Configure tasks > Overrides** method when invoking task execution. Each level has its own set of parameters, and some parameters are shared across levels. For shared parameters, the more specific level will override the more general one. ### Example Here is an example of how these levels work together, showing each level with all available parameters: ``` # Level 1: TaskEnvironment - Base configuration env_2 = flyte.TaskEnvironment( name="data_processing_env", image=flyte.Image.from_debian_base(), resources=flyte.Resources(cpu=1, memory="512Mi"), env_vars={"MY_VAR": "value"}, # secrets=flyte.Secret(key="openapi_key", as_env_var="MY_API_KEY"), cache="disable", # pod_template=my_pod_template, # reusable=flyte.ReusePolicy(replicas=2, idle_ttl=300), depends_on=[another_env], description="Data processing task environment", # plugin_config=my_plugin_config ) # Level 2: Decorator - Override some environment settings @env_2.task( short_name="process", # secrets=flyte.Secret(key="openapi_key", as_env_var="MY_API_KEY_2"), cache="auto", # pod_template=my_pod_template, report=True, max_inline_io_bytes=100 * 1024, retries=3, timeout=60, docs="This task processes data and generates a report." ) async def process_data(data_path: str) -> str: return f"Processed {data_path}" @env_2.task async def invoke_process_data() -> str: result = await process_data.override( resources=flyte.Resources(cpu=4, memory="2Gi"), env_vars={"MY_VAR": "new_value"}, # secrets=flyte.Secret(key="openapi_key", as_env_var="MY_API_KEY_3"), cache="auto", max_inline_io_bytes=100 * 1024, retries=3, timeout=60 )("input.csv") return result ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/task_config.py* ## Task configuration parameters Each parameter is documented in detail on its dedicated page in this section. For the complete parameter interaction matrix showing which parameters can be set at which level, and for full type signatures and constraints, see the **Flyte SDK > flyte > TaskEnvironment**. | Parameter | Set at | Details | |-----------|--------|---------| | **name** | `TaskEnvironment` only | **Tasks > Configure tasks > Additional task settings** • **Flyte SDK > flyte > TaskEnvironment** | | **image** | `TaskEnvironment` only | **Tasks > Configure tasks > Container images** • **Flyte SDK > flyte > Image** | | **depends_on** | `TaskEnvironment` only | **Tasks > Configure tasks > Multiple environments** | | **description** | `TaskEnvironment` only | **Tasks > Configure tasks > Additional task settings** | | **plugin_config** | `TaskEnvironment` only | **Tasks > Configure tasks > Task plugins** | | **resources** | `TaskEnvironment`, `override`\* | **Tasks > Configure tasks > Resources** • **Flyte SDK > flyte > Resources** | | **env_vars** | `TaskEnvironment`, `override`\* | **Tasks > Configure tasks > Additional task settings > Environment variables** | | **secrets** | `TaskEnvironment`, `override`\* | **Tasks > Configure tasks > Secrets** • **Flyte SDK > flyte > Secret** | | **cache** | All three levels | **Tasks > Configure tasks > Caching** • **Flyte SDK > flyte > Cache** | | **pod_template** | All three levels | **Tasks > Configure tasks > Pod templates** • **Flyte SDK > flyte > PodTemplate** | | **reusable** | `TaskEnvironment`, `override` | **Tasks > Configure tasks > Reusable containers** • **Flyte SDK > flyte > ReusePolicy** | | **interruptible** | All three levels | **Tasks > Configure tasks > Interruptible tasks** | | **queue** | All three levels | **Tasks > Configure tasks > Queues** | | **short_name** | `@env.task`, `override` | **Tasks > Configure tasks > Additional task settings** | | **prefix** | `@env.task` only | **Tasks > Configure tasks > Additional task settings > Naming and metadata > `prefix`** | | **retries** | `@env.task`, `override` | **Tasks > Configure tasks > Retries and timeouts** • **Flyte SDK > flyte > RetryStrategy** | | **timeout** | `@env.task`, `override` | **Tasks > Configure tasks > Retries and timeouts** • **Flyte SDK > flyte > Timeout** | | **max_inline_io_bytes** | `@env.task`, `override` | **Tasks > Configure tasks > Additional task settings > Inline I/O threshold** | | **links** | `@env.task`, `override` | **Tasks > Configure tasks > Additional task settings > Naming and metadata > `links`** | | **report** | `@env.task` only | **Tasks > Configure tasks > Additional task settings > Naming and metadata > `report`** | | **triggers** | `@env.task` only | [Triggers](../../triggers/_index) • **Flyte SDK > flyte > Trigger** | | **docs** | `@env.task` only | **Tasks > Configure tasks > Additional task settings > Naming and metadata > `docs`** | \*When `reusable` is set, `resources`, `env_vars`, and `secrets` can only be overridden via `task.override()` with `reusable="off"` in the same call. ## Scheduled and reactive automation Everything above configures how a task runs. To decide *when* it runs without someone calling it, attach triggers with the `triggers` parameter of `@env.task`. A trigger can run the task on a schedule (a cron expression or a fixed interval), react to a new version of an artifact or one of its partitions, or save a set of inputs to fire on demand. See [Triggers](../../triggers/_index) for every type of automation. ## Distributed tasks with a clustered environment Everything above configures a task that runs in a single container. Some tasks instead need a *gang* of pods working together as one distributed job โ€” the classic case being multi-node, multi-GPU model training. For those, use a specialized `flyte.clustered.ClusteredTaskEnvironment` instead of a plain `TaskEnvironment`. It inherits all the configuration above and adds a few fields that describe the cluster shape: `replicas` (pods) and `nproc_per_node` (worker processes per pod). When you run the task, the backend launches a Kubernetes JobSet of identical pods, sets up a `torchrun` rendezvous across them, and runs your task body once per worker. ```python import flyte from flyte.clustered import ClusteredTaskEnvironment, TorchRun env = ClusteredTaskEnvironment( name="ddp_env", image=flyte.Image.from_debian_base().with_pip_packages("torch"), resources=flyte.Resources(cpu=(2, 4), memory=("4Gi", "8Gi"), gpu="L4:1"), replicas=2, # number of pods (nodes) nproc_per_node=1, # worker processes per pod => world_size = 2 x 1 runtime=TorchRun(), ) ``` See **Tasks > Configure tasks > Clustered task environment** for the full guide, including DDP, FSDP, and framework-integration examples. {{< subpage-cards >}} ## Subpages - **Tasks > Configure tasks > Container images** - Specify the container image a task runs in, and how to build one. - **Tasks > Configure tasks > Fast cold boot** - Start containers in seconds by building images with the remote image builder. - **Tasks > Configure tasks > Resources** - Set the CPU, memory, GPU, and storage a task's container gets. - **Tasks > Configure tasks > Secrets** - Store API keys and credentials securely and read them from inside a task. - **Tasks > Configure tasks > Caching** - Skip recomputation by reusing a previous task result, and control when that happens. - **Tasks > Configure tasks > Reusable containers** - Keep a container warm across task executions instead of creating a fresh one each time. - **Tasks > Configure tasks > Pod templates** - Reach the underlying Kubernetes pod spec for anything Flyte does not expose directly. - **Tasks > Configure tasks > Multiple environments** - Give different tasks in one workload different images, resources, and configuration. - **Tasks > Configure tasks > Clustered task environment** - Run one task across a gang of pods at once, for distributed training and similar workloads. - **Tasks > Configure tasks > Retries and timeouts** - The two controls for handling failure: retry strategies and three independent timeout bounds. - **Tasks > Configure tasks > Interruptible tasks** - Run tasks on discounted spot instances that can be reclaimed at any time. - **Tasks > Configure tasks > Queues** - Named scheduling lanes that route and rate-limit work instead of letting everything compete. - **Tasks > Configure tasks > Task plugins** - Extend task execution beyond plain containers to specialized compute frameworks. - **Tasks > Configure tasks > Additional task settings** - Naming, metadata, default inputs, and environment variables, and the settings without their own page. - **Tasks > Configure tasks > Logging** - The two loggers Flyte uses, and how to set each level independently. - **Tasks > Configure tasks > Overrides** - Change a task's configuration at invocation time rather than where it is defined. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/container-images === Specify the container image a task runs in, and how to build one. # Container images The `image` parameter of the **Flyte SDK > flyte > TaskEnvironment** is used to specify a container image. Every task defined using that `TaskEnvironment` will run in a container based on that image. If a `TaskEnvironment` does not specify an `image`, it will use the default Flyte image ([`ghcr.io/flyteorg/flyte:py{python-version}-v{flyte_version}`](https://github.com/orgs/flyteorg/packages/container/package/flyte)). > **๐Ÿ“ Note** > > In Flyte 1 the container image was defined with `ImageSpec` (the `flytekit.ImageSpec` API). Flyte 2 uses `flyte.Image`, described below. ## Specifying your own image directly You can directly reference an image by URL in the `image` parameter, like this: ```python env = flyte.TaskEnvironment( name="my_task_env", image="docker.io/myorg/myimage:mytag" ) ``` This works well if you have a pre-built image available in a public registry like Docker Hub or in a private registry that your Union/Flyte instance can access. ## Specifying your own image with the `flyte.Image` object You can also construct an image programmatically using the `flyte.Image` object. The `flyte.Image` object provides a fluent interface for building container images: start with a `from_*` base constructor, then customize with `with_*` methods. Each method returns a new immutable `Image`. For a complete list of all available methods and their parameters, see the **Flyte SDK > flyte > Image**. Here are some examples of the most common patterns for building images with `flyte.Image`. ## Example: Defining a custom image with `Image.from_debian_base` The `[[Image.from_debian_base()]]` provides the default Flyte image as the base. This image is itself based on the official Python Docker image (specifically `python:{version}-slim-bookworm`) with the addition of the Flyte SDK pre-installed. Starting there, you can layer additional features onto your image. For example: ```python import flyte import numpy as np # Define the task environment env = flyte.TaskEnvironment( name="my_env", image = ( flyte.Image.from_debian_base( name="my-image", python_version=(3, 13) # registry="registry.example.com/my-org" # Only needed for local builds ) .with_apt_packages("libopenblas-dev") .with_pip_packages("numpy") .with_env_vars({"OMP_NUM_THREADS": "4"}) ) ) @env.task def main(x_list: list[int]) -> float: arr = np.array(x_list) return float(np.mean(arr)) if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main, x_list=list(range(10))) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/container-images/from_debian_base.py* > [!NOTE] > A registry is only needed when the image is **built locally** (it's where the built image is pushed); it isn't required when using the Union backend `ImageBuilder`, which builds on the cluster. > The easiest way to set it is once in your config, `image.registry` (or the `FLYTE_IMAGE_REGISTRY` environment variable), so you don't have to repeat it in every `Image`. Set `registry=` on an `Image` only to override. See **Tasks > Configure tasks > Container images > Image building**. ## Example: Defining an image based on uv script metadata Another common technique for defining an image is to use [`uv` inline script metadata](https://docs.astral.sh/uv/guides/scripts/#declaring-script-dependencies) to specify your dependencies right in your Python file and then use the `flyte.Image.from_uv_script()` method to create a `flyte.Image` object. The `from_uv_script` method starts from `python:{version}-slim-bookworm` without the Flyte SDK and adds the dependencies specified in the `uv` metadata. For example: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # "numpy" # ] # main = "main" # params = "x_list=[1,2,3,4,5,6,7,8,9,10]" # /// import flyte import numpy as np env = flyte.TaskEnvironment( name="my_env", image=flyte.Image.from_uv_script( __file__, name="my-image" # registry="registry.example.com/my-org" # Only needed for local builds ) ) @env.task def main(x_list: list[int]) -> float: arr = np.array(x_list) return float(np.mean(arr)) if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main, x_list=list(range(10))) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/container-images/from_uv_script.py* The advantage of this approach is that the dependencies used when running a script locally and when running it on the Flyte/Union backend are always the same (as long as you use `uv` to run your scripts locally). This means you can develop and test your scripts in a consistent environment, reducing the chances of encountering issues when deploying to the backend. > [!NOTE] > When using `uv` metadata in this way, be sure to include the `flyte` package in your `uv` script dependencies. > This will ensure that `flyte` is installed when running the script locally using `uv run`. > The image that `from_uv_script()` builds doesn't otherwise include `flyte`, so the uv script dependencies are also what installs `flyte` on the Flyte/Union backend. ## Customizing an image with `with_*` methods Images from `from_debian_base()` and `from_uv_script()` are *extendable*: you can layer additional customizations on top using the `with_*` methods. (Images from `from_base()` and `from_dockerfile()` are **not** extendable — calling a `with_*` method on one raises an error. Customize a `from_dockerfile()` image in its Dockerfile. To add layers to a `from_base()` image, clone it first, as shown in **Tasks > Configure tasks > Container images > More ways to define a base image > Starting from an existing image**.) Each method returns a new `flyte.Image`, so you can chain them together in a fluent style: ```python import flyte from flyte import Image image = ( Image.from_debian_base() .with_apt_packages("git", "vim") .with_pip_packages("pandas", "numpy") .with_env_vars({"MY_ENV_VAR": "my_value"}) .with_commands(["echo 'building image'"]) ) env = flyte.TaskEnvironment(name="my_env", image=image) ``` The available customization methods are: | Method | Description | |---|---| | `flyte.Image.with_pip_packages()` | Install one or more packages with `pip` (supports `index_url`, `extra_index_urls`, `pre` for pre-releases, and `secret_mounts` for private indexes). | | `flyte.Image.with_apt_packages()` | Install one or more system packages with `apt`. | | `flyte.Image.with_requirements()` | Install Python dependencies from a `requirements.txt` file. | | `flyte.Image.with_uv_project()` | Install dependencies from a `pyproject.toml` + `uv.lock` pair. | | `flyte.Image.with_poetry_project()` | Install dependencies from a `pyproject.toml` + `poetry.lock` pair. | | `flyte.Image.with_pixi_project()` | Install dependencies from a [pixi](https://pixi.sh) project (conda and PyPI packages) defined in a `pixi.toml`, or a `pyproject.toml` with a `[tool.pixi]` section. | | `flyte.Image.with_source_file()` | Copy a single local file into the image. | | `flyte.Image.with_source_folder()` | Copy a local directory into the image. | | `flyte.Image.with_commands()` | Run additional shell commands during the build (do not prefix them with `RUN`). | | `flyte.Image.with_env_vars()` | Set environment variables in the image. | | `flyte.Image.with_workdir()` | Set the working directory in the image. | | `flyte.Image.with_dockerignore()` | Point at a `.dockerignore` file to exclude paths from the build context. | For the full signature of each method, see the **Flyte SDK > flyte > Image**. > [!NOTE] > The `with_*` methods that install Python dependencies (`with_pip_packages`, `with_requirements`, `with_uv_project`, `with_poetry_project`) cannot be combined with a conda-based image. ### Installing dependencies from a `uv` or Poetry project If your project already declares its dependencies in a `pyproject.toml`, you can install them directly into the image rather than listing packages individually. Use `flyte.Image.with_uv_project()` for a `uv.lock` or `flyte.Image.with_poetry_project()` for a `poetry.lock`: ```python from pathlib import Path from flyte import Image image = ( Image.from_debian_base(install_flyte=False) .with_apt_packages("git") .with_uv_project( pyproject_file=Path("pyproject.toml"), uvlock=Path("uv.lock"), ) ) ``` By default only the dependencies are installed. To also install the project itself as a package, pass `project_install_mode="install_project"`. ### Installing dependencies from a pixi project If your dependencies are managed with [pixi](https://pixi.sh) (conda and PyPI packages together), use `[[Image.with_pixi_project()]]` to build the image from a pixi manifest. The manifest is resolved and installed with `pixi install` at build time, and the resulting pixi environment becomes the image's runtime environment: ```python from flyte import Image image = ( Image.from_debian_base() .with_pixi_project("pixi.toml") ) ``` The manifest argument can be a `pixi.toml` file, a `pyproject.toml` with a `[tool.pixi]` section, or the project directory containing either. When a `pixi.lock` sits next to the manifest, the build uses `pixi install --locked` so it reproduces the lock exactly. By default only the manifest and lock file are copied into the image; pass `project_install_mode="install_project"` to copy the whole project directory (use this when the manifest installs the project itself, for example a `pyproject.toml` that declares the project as an editable dependency). Three things to keep in mind: * **`flyte` must be present in the pixi environment.** After this layer the pixi environment replaces the image's virtualenv as the runtime, so tasks run only if `flyte` is installed in it. Declare `flyte` in the manifest (for example under `[pypi-dependencies]`), or add `.with_pip_packages("flyte")` after the pixi layer (it installs into the pixi environment). The environment must also provide `python`. * **`platforms` must cover every build architecture.** A multi-architecture image (`linux/amd64` plus `linux/arm64`) needs `platforms = ["linux-64", "linux-aarch64"]` in the manifest, or `pixi install` fails for the missing architecture at build time. * **GPU-less builders with a CUDA manifest.** If the manifest declares a CUDA `[system-requirements]` and image builds run on machines without a GPU, set `.with_env_vars({"CONDA_OVERRIDE_CUDA": ""})` before the pixi layer so install-time validation of the `__cuda` virtual package succeeds. For the full parameter list (`environment`, `extra_args`, `secret_mounts`, `project_install_mode`), see the **Flyte SDK > flyte > Image > with_pixi_project()**. ### Copying local files into the image Use `flyte.Image.with_source_file()` to copy a single file, or `flyte.Image.with_source_folder()` to copy a directory, into the image: ```python from pathlib import Path from flyte import Image image = ( Image.from_debian_base() .with_source_file(Path("config.yaml"), dst="/app/config.yaml") .with_source_folder(Path("./src"), dst="/app/src") ) ``` ## More ways to define a base image Beyond `from_debian_base` and `from_uv_script`, `flyte.Image` provides several other base constructors. ### Starting from an existing image If you already have a pre-built image in a registry, use `flyte.Image.from_base()` to use it as the starting point: ```python from flyte import Image image = Image.from_base("ghcr.io/my-org/my-base-image:latest") ``` > [!NOTE] > An image from `from_base()` is **not extendable** by default — chaining `with_*` methods onto it raises an error. To add layers, first clone it with a `name` and `extendable=True`, then chain as usual: > > ```python > image = Image.from_base("ghcr.io/my-org/my-base-image:latest").clone(name="my-image", extendable=True).with_pip_packages("pandas") > ``` > > Otherwise, bake any extra dependencies into the pre-built image itself, or start from `from_debian_base()` / `from_uv_script()`. You can also use `flyte.Image.clone()` to reuse an existing image definition while overriding its registry, name, Python version, or extendability: ```python from flyte import Image image = Image.from_base("ghcr.io/my-org/my-base-image:latest").clone(name="my-flyte-image") ``` ### Building from a Dockerfile If you need full control over the build, use `flyte.Image.from_dockerfile()` to build the image from a Dockerfile you provide: ```python from pathlib import Path from flyte import Image image = Image.from_dockerfile( file=Path("Dockerfile").absolute(), registry="ghcr.io/my-org", name="my-image", ) ``` > [!NOTE] > Because Flyte does not parse the Dockerfile, you cannot layer additional `with_*` methods on top of a `from_dockerfile()` image โ€” put all of your build logic into the Dockerfile itself. > Use an absolute `Path` for the Dockerfile; the build context is the directory containing it. ### Referencing an image defined in configuration Use `flyte.Image.from_ref_name()` to reference an image by a name defined in your configuration, rather than hard-coding it in your task code. This lets you swap images without changing code: ```python import flyte env = flyte.TaskEnvironment( name="my_env", image=flyte.Image.from_ref_name("custom-image"), ) ``` The named references are supplied at initialization โ€” either in your `config.yaml`: ```yaml image: image_refs: custom-image: ghcr.io/flyteorg/flyte:py{python-version}-v{flyte_version} ``` or through `flyte.init_from_config()`: ```python flyte.init_from_config(images=("custom-image=ghcr.io/flyteorg/flyte:py{python-version}-v{flyte_version}",)) ``` Calling `flyte.Image.from_ref_name()` with no argument references the image named `default`. ## Using different images for different tasks A single project can use multiple images: each `flyte.TaskEnvironment` specifies its own image, so tasks in different environments run in different containers. This is useful when, for example, a data-preparation task needs only a lightweight image while a training task needs a large GPU image. ```python import flyte from flyte import Image prep_image = Image.from_debian_base().with_pip_packages("pandas", "pyarrow") train_image = Image.from_debian_base().with_pip_packages("torch") prep_env = flyte.TaskEnvironment(name="prep", image=prep_image) train_env = flyte.TaskEnvironment(name="train", image=train_image, depends_on=[prep_env]) @prep_env.task async def prepare(data: str) -> str: return data @train_env.task async def train(data: str) -> str: return data ``` > [!NOTE] > For patterns where each team fully owns and builds its own image (rather than layering with `flyte.Image`), see **Project patterns > Bring your own image**. ## Image building There are two ways that the image can be built: * If you are running a Flyte OSS instance then the image is built locally on your machine and pushed to a container registry that your cluster can pull from. * If you are running a Union instance, the image can be built locally, as with Flyte OSS, or using the Union `ImageBuilder`, which runs remotely on Union's infrastructure (no registry required). **Setting the registry for local builds.** Rather than repeat a registry in every `Image` definition, set it once, globally, in any of these ways: * **Config file**: add a `registry` key under `image:` in your `config.yaml`: ```yaml image: registry: ghcr.io/my-org ``` * **Environment variable**: set `FLYTE_IMAGE_REGISTRY=ghcr.io/my-org`. * **CLI**: pass `--registry` when generating the config: `flyte create config --registry ghcr.io/my-org`. (The `--registry` flag requires flyte 2.5.9 or later; the `image.registry` config key and `FLYTE_IMAGE_REGISTRY` variable also require 2.5.9.) Any of these sets the base registry for all image builds, so your `Image` definitions can omit `registry=` entirely. Set `registry=` on an individual `Image` only to override the global value. ### Configuring the `builder` **Get started > Run modes > Run on a deployed cluster**, we discussed the `image.builder` property in the `config.yaml`. For Flyte OSS instances, this property must be set to `local` or `local-podman`. For Union instances, this property can be set to `remote` to use the Union `ImageBuilder`, or `local` or `local-podman` to build the image locally on your machine. ### Local image building When `image.builder` in the `config.yaml` is set to `local`, `flyte.run()` does the following: * Builds the image with your local Docker installation, using the layers in your `Image` definition. * Pushes the image to the configured registry (`image.registry`, or a per-`Image` `registry=`). * Deploys your code to the backend. * Kicks off the execution of your workflow * Before the task that uses your custom image is executed, the backend pulls the image from the registry to set up the container. You must ensure that: * Docker is running on your local machine. * You have successfully run `docker login` to that registry from your local machine (For example GitHub uses the syntax `echo $GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin`) * Your Union/Flyte installation has read access to that registry. To build with Podman instead of Docker, set `image.builder` to `local-podman` (requires flyte 2.10.6 or later). The image is built with `podman build` and pushed with `podman push` (`podman manifest push` for a multi-platform image). In place of the Docker requirements above, make sure that Podman is on your `PATH`, that a Podman machine is running on macOS and Windows (`podman machine start`), and that you have run `podman login` to the registry. > [!NOTE] > If you are using the GitHub container registry (`ghcr.io`) > note that images pushed there are private by default. > You may need to go to the image URI, click **Package Settings**, and change the visibility to public in order to access the image. > > Other registries (such as Docker Hub) require that you pre-create the image repository before pushing the image. > In that case you can set it to public when you create it. > > Public images are on the public internet and should only be used for testing purposes. > Do not place proprietary code in public images. ### Remote `ImageBuilder` `ImageBuilder` is a service provided by Union that builds container images on Union's infrastructure and provides an internal container registry for storing the built images. When `image.builder` in the `config.yaml` is set to `remote` (and you are running Union.ai), `flyte.run()` does the following: * Builds the Docker image on your Union instance with `ImageBuilder`. * Pushes the image to a registry * If you did not specify a `registry` in the `Image` definition, it pushes to the internal registry in your Union instance. * If you did specify a `registry`, it pushes to that registry. Be sure to also set the `registry_secret` parameter in the `Image` definition to enable `ImageBuilder` to authenticate to that registry (see **Tasks > Configure tasks > Container images > Image building > Remote `ImageBuilder` > ImageBuilder with external registries**). * Deploys your code to the backend. * Kicks off the execution of your workflow. * Before the task that uses your custom image is executed, the backend pulls the image from the registry to set up the container. There is no set up of Docker nor any other local configuration required on your part. When fast cold boot is enabled for your data plane, images built by `ImageBuilder` also start in seconds on a fresh node, because the node reads files from the image on demand instead of pulling every layer first. See **Tasks > Configure tasks > Fast cold boot**. > [!NOTE] > The Flyte SDK checks whether the image builder is enabled for your cluster by verifying that the `build-image` task is deployed in the `system` project within the `production` domain. > If you are using custom roles and policies, ensure that users are granted the `view_flyte_inventory` action for the `production/system` project-domain pair. > See [User management](https://www.union.ai/docs/v2/union/user-guide/user-management) for creating and assigning custom roles and policies. #### ImageBuilder with external registries If you are want to push the images built by `ImageBuilder` to an external registry, you can do this by setting the `registry` parameter in the `Image` object. You will also need to set the `registry_secret` parameter to provide the secret needed to push and pull images to the private registry. For example: ```python # Add registry credentials so the Union remote builder can pull the base image # and push the resulting image to your private registry. image = flyte.Image.from_base("registry.example.com/my-org/my-private-image:latest").clone( name="my-image", registry="registry.example.com/my-org", registry_secret="my-secret", ) # Reference the same secret in the TaskEnvironment so Flyte can pull the image at runtime. env = flyte.TaskEnvironment( name="my_task_env", image=image, secrets="my-secret" ) ``` The value of the `registry_secret` parameter must be the name of a Flyte secret of type `image_pull` that contains the credentials needed to access the private registry. It must match the name specified in the `secrets` parameter of the `TaskEnvironment` so that Flyte can use it to pull the image at runtime. To create an `image_pull` secret for the remote builder and the task environment, run the following command: ```bash flyte create secret --type image_pull my-secret --from-file ~/.docker/config.json ``` The format of this secret matches the standard Kubernetes [image pull secret](https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/#log-in-to-docker-hub), and should look like this: ```json { "auths": { "registry.example.com": { "auth": "base64-encoded-auth" } } } ``` > [!NOTE] > The `auth` field contains the base64-encoded credentials for your registry (username and password or token). #### Pulling a private base image with a credential helper `ImageBuilder` only authenticates to its own default registry. If your base image lives in any other private registry, `ImageBuilder` pulls it anonymously and the build fails with `401 Unauthorized`, even if registry permissions or IAM policies allow access, because no credentials are sent at all. To fix this, pass an `image_pull` secret as `registry_secret`. The secret can hold either: * **Static credentials**, as shown in the previous section. This works with any registry, but you have to rotate the credentials when they expire. * **A credential helper mapping**, which stores no credentials. `ImageBuilder` runs the helper on every build to fetch a fresh token with the data plane's own cloud identity, so there is nothing to rotate. This works only when the registry is on the same cloud provider as your data plane. Credential helpers are supported for Amazon ECR, for example a base image in a different AWS account from your data plane. For registries on other clouds, use static credentials. ##### Amazon ECR in another AWS account This setup uses the [`ecr-login` credential helper](https://github.com/awslabs/amazon-ecr-credential-helper). A static ECR token would expire after 12 hours. 1. In the AWS account that owns the image, add a repository policy that lets your data plane's account pull from it (replace ``): ```json { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowDataPlanePull", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam:::root" }, "Action": [ "ecr:BatchCheckLayerAvailability", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer" ] } ] } ``` 2. Save a Docker config file, `config.json`, that maps the registry to the `ecr-login` helper. Replace `` and `` with the account and region that own the image. It contains no credentials. List more registries under `credHelpers` if you pull from several accounts. ```json { "auths": {}, "credHelpers": { ".dkr.ecr..amazonaws.com": "ecr-login" } } ``` 3. Store the file as an `image_pull` secret: ```bash flyte create secret --type image_pull ecr-cross-account --from-file config.json ``` If your organization has more than one cluster pool, add `--cluster-pool `. 4. Pass the secret to `ImageBuilder` with `registry_secret`. `from_base()` doesn't accept a secret, so set it on `clone()`, which you already need in order to add layers on top of the base image: ```python image = ( flyte.Image.from_base(".dkr.ecr..amazonaws.com/:") .clone(name="my-image", registry_secret="ecr-cross-account", extendable=True) .with_pip_packages("flyte", "pandas") ) env = flyte.TaskEnvironment(name="my_task_env", image=image) ``` Leave `registry` unset so the built image is pushed to your Union instance's default registry, as usual. Tasks pull it from there, so the `TaskEnvironment` doesn't need the secret. For BYOC data planes, see also **BYOC deployment > Enabling AWS resources > Enabling AWS ECR** for running tasks directly on images stored in another account. ### Install private PyPI packages To install Python packages from a private PyPI index (for example, from GitHub), you can mount a secret to the image layer. This allows your build to authenticate securely during dependency installation. For example: ```python private_package = "git+https://$GITHUB_PAT@github.com/pingsutw/flytex.git@2e20a2acebfc3877d84af643fdd768edea41d533" image = ( Image.from_debian_base() .with_apt_packages("git") .with_pip_packages(private_package, pre=True, secret_mounts=Secret("GITHUB_PAT")) ) ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/fast-cold-boot === Start containers in seconds by building images with the remote image builder. # Fast cold boot **Cold boot** is the time between a task being scheduled on a node and its container starting. Most of it is spent pulling the image. On a fresh node, a 10 GB GPU image takes 4 to 5 minutes to pull. With fast cold boot, images built by the **Tasks > Configure tasks > Container images > Image building > Remote `ImageBuilder`** start in seconds instead, even when they are many gigabytes. You don't change your tasks. If you build from a Dockerfile, keep building it your way and pass the result through the remote builder, as shown in **Tasks > Configure tasks > Fast cold boot > Use an image from your existing build system**. Fast cold boot is a data-plane setting, off by default. On BYOC, ask Union.ai support to enable it. On a self-managed data plane, set `nodeBootstrap.enabled` and then `imageBuilder.enableImageOptimization` in the **Self-managed deployment > Helm chart reference > Dataplane**. ## How it works The remote builder stores each image in a format that can be read lazily: 1. When a task lands on a node, the node downloads a small index of the image instead of every layer. 2. The container starts as soon as the index is mounted. 3. Files are fetched from the registry the first time the task reads them. Data is cached on the node's local disk and shared with other images on the same node. Files the task never reads are never downloaded. If your image carries CUDA libraries, test data, or tools your task doesn't use, they cost nothing at startup. ## Build an image with the remote builder Set the builder to `remote` in your `config.yaml`: ```yaml image: builder: remote ``` Or set the `FLYTE_IMAGE_BUILDER=remote` environment variable. Any image you define with `flyte.Image` is then built remotely and gets fast cold boot: ```python import flyte image = ( flyte.Image.from_debian_base() .with_apt_packages("ca-certificates") .with_pip_packages("torch", "transformers") ) env = flyte.TaskEnvironment(name="train", image=image) @env.task async def train(epochs: int) -> float: ... ``` `flyte deploy` and `flyte run` build the image the first time, then reuse it until its definition changes. An image built before fast cold boot was enabled keeps its standard format. To convert it, rebuild it with `flyte.build(image, force=True)`. ## Use an image from your existing build system If you already build images in CI or with another tool, keep that build. Pass its output through the remote builder as a base image, and the remote builder rebuilds it in the fast cold boot format. This adds no layers and leaves the image contents unchanged. Wrap the image with `flyte.Image.from_base()` and call `clone()` with a `name`: ```python import os import flyte # Set by CI to the image your build system just pushed, for example # 123456789012.dkr.ecr.us-east-1.amazonaws.com/training:3f2c1ab base_image = os.getenv("TRAINING_IMAGE", "123456789012.dkr.ecr.us-east-1.amazonaws.com/training:latest") image = flyte.Image.from_base(base_image).clone(name="training") env = flyte.TaskEnvironment(name="training", image=image) @env.task async def train(epochs: int) -> float: ... ``` Then deploy from the same CI job, after your own build pushes the image: ```bash export TRAINING_IMAGE="123456789012.dkr.ecr.us-east-1.amazonaws.com/training:${GIT_SHA}" export FLYTE_IMAGE_BUILDER=remote flyte deploy --recursive workflows/ ``` `TRAINING_IMAGE` is only read at deploy time. Inside the task container the variable is unset, so the default value is never used to pull anything. Keep these points in mind: * **The base image must already run Flyte tasks.** It needs the `flyte` package installed and your task code importable. Because `clone()` adds no layers, a missing `flyte` package builds successfully and fails when the task starts. To adapt an image that isn't Flyte-ready, see **Project patterns > Bring your own image**. * **The rebuilt image runs only on your data plane.** It is stored in a lazy-pull format that only nodes set up for fast cold boot can run. To run the image locally or in CI, use your original image, not the `clone()` output. * **`clone()` triggers the remote build.** A bare `flyte.Image.from_base("...")` is used as-is and is never rebuilt, so it starts with a standard image pull. * **Use an immutable tag for the base image**, such as a Git SHA or a digest. The remote builder rebuilds when the base image reference changes. If you push a new image under the same tag, such as `:latest`, the reference doesn't change and the old build is reused. * **Leave `registry` unset in `clone()`.** The image is then stored in your data plane's internal registry, close to your nodes. Because files are fetched while the task runs, a registry outside your cloud network makes those reads slower. * **Private base images** need registry credentials for the remote builder to pull them. Pass `registry_secret` to `clone()`, and leave out the `registry` argument shown in **Tasks > Configure tasks > Container images > Image building > Remote `ImageBuilder` > ImageBuilder with external registries**. * **To add layers** on top of the base image, pass `extendable=True` to `clone()` and chain `with_*` methods as usual. ## Benchmarks Image pull time on a fresh node with an empty cache: | Image | Compressed size | Standard pull | Fast cold boot | Speedup | |---|---|---|---|---| | TensorFlow (no CUDA) | 534 MB | 18.8 s | 1.1 s | 17x | | PyTorch | 3.4 GB | 1 min 31 s | 4.7 s | 19x | | PyTorch 1.13 + CUDA | 9.1 GB | 4 min 40 s | 1.13 s | 248x | | CUDA + PyTorch | 9.9 GB | 4 min 38 s | 1.16 s | 240x | On a node that has already run the image, startup takes 160 to 730 ms. End-to-end time of a task on a fresh node, from scheduling to completion: | | Image pull | Execution | Total | |---|---|---|---| | Standard pull | 2 min 3 s | 7 s | 2 min 10 s | | Fast cold boot | 0.5 s | 29 s | 29.5 s | Execution takes longer with fast cold boot because the task fetches files the first time it reads them. The total still drops by 77%. The saving is largest when a task reads a small part of a large image, and smallest when it reads most of the image right away. Neither figure includes node provisioning, which happens before the image pull. For the full benchmark write-up, see [We cut container cold boot from minutes to seconds](https://www.union.ai/blog-post/we-cut-container-cold-boot-from-minutes-to-seconds-heres-how). ## Related pages * **Tasks > Configure tasks > Container images**: defining images with `flyte.Image` and configuring the builder. * **Tasks > Configure tasks > Reusable containers**: keep a warm container across tasks to skip startup entirely. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/resources === Set the CPU, memory, GPU, and storage a task's container gets. # Resources Task resources specify the computational limits and requests (CPU, memory, GPU, storage) that will be allocated to each task's container during execution. To specify resource requirements for your task, instantiate a `Resources` object with the desired parameters and assign it to either the `resources` parameter of the `TaskEnvironment` or the `resources` parameter of the `override` function (for invocation overrides). Every task defined using that `TaskEnvironment` will run with the specified resources. The task decorator takes no `resources` argument. To give one task different resources, define it in its own `TaskEnvironment` or call `override(resources=...)` when you invoke it. If the environment sets `reusable`, also pass `reusable="off"` in the same `override` call. If neither the `TaskEnvironment` nor an `override` specifies `resources`, the default resource allocation will be used. ## Resources data class For the full class definition, parameter types, and accepted formats, see the **Flyte SDK > flyte > Resources**. The main parameters are: - **`cpu`**: CPU allocation, as a number, string (`"500m"`), or `(request, limit)` tuple. - **`memory`**: Memory with Kubernetes units, such as `"4Gi"`, or a `(request, limit)` tuple. Leave headroom below a node's total RAM: its *allocatable* memory is smaller (the kubelet reserves overhead for the OS and system daemons), so a request near a node's nominal capacity can leave the pod stuck `Pending`. - **`gpu`**: GPU or other accelerator allocation, as `"A100:2"`, an integer count, or `flyte.GPU()`, `flyte.TPU()`, `flyte.AMD_GPU()`, or `flyte.Device()` for advanced config. See **Tasks > Configure tasks > Resources > Accelerators** below. - **`disk`**: Ephemeral storage, such as `"10Gi"`. - **`shm`**: Shared memory, such as `"1Gi"` or `"auto"`. For how task resource requests interact with project-domain quotas as you scale across teams, see **Project patterns > Resource management and multi-team scaling**. ## Ephemeral storage The `disk` parameter requests *ephemeral storage* โ€” node-local scratch disk for the task's container. Set it as a string with Kubernetes units, for example `"50Gi"`: ```python env = flyte.TaskEnvironment( name="etl_env", resources=flyte.Resources(cpu=2, memory="4Gi", disk="50Gi"), ) ``` Under the hood, `disk` maps to the Kubernetes [`ephemeral-storage`](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#local-ephemeral-storage) resource on the task's container. **What it covers.** Ephemeral storage is the local disk a task writes to while it runs: the container's writable filesystem and any temporary files your code creates on the local filesystem during execution (downloaded datasets, intermediate outputs, model checkpoints staged before offload). It is distinct from the offloaded storage backing `flyte.io.File` and `flyte.io.Dir`, which lives in the blob store rather than on the node. **Lifecycle.** Ephemeral storage is tied to the task's pod: it is provisioned when the task starts and reclaimed when the pod terminates. Nothing written to it survives beyond the task run, so use it for scratch work โ€” persist anything you need to keep to a `flyte.io.File` or `flyte.io.Dir` in object storage. **Single value, not a request/limit range.** Unlike `cpu` and `memory`, `disk` takes a single string, not a `(request, limit)` tuple. **Default behavior.** Flyte does not set an `ephemeral-storage` request or limit when `disk` is unset. (A cluster-level Kubernetes `LimitRange`, if configured, may still inject a default.) The pod can still write to node-local disk, but it may be evicted if the node comes under storage pressure. Tasks doing heavy local data processing should set `disk` explicitly. For how ephemeral-storage sizing plays out as you scale across teams and quotas, see **Project patterns > Resource management and multi-team scaling > Task-level resources > Be explicit about ephemeral storage**. ## Examples ### Usage in TaskEnvironment Here's a complete example of defining a TaskEnvironment with resource specifications for a machine learning training workload: ``` import flyte # Define a TaskEnvironment for ML training tasks env = flyte.TaskEnvironment( name="ml-training", resources=flyte.Resources( cpu=("2", "4"), # Request 2 cores, allow up to 4 cores for scaling memory=("2Gi", "12Gi"), # Request 2 GiB, allow up to 12 GiB for large datasets disk="50Gi", # 50 GiB ephemeral storage for checkpoints shm="8Gi" # 8 GiB shared memory for efficient data loading ) ) # Use the environment for tasks @env.task async def train_model(dataset_path: str) -> str: # This task will run with flexible resource allocation return "model trained" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/resources/resources.py* ### Usage in a task-specific override ``` # Demonstrate resource override at task invocation level @env.task async def heavy_training_task() -> str: return "heavy model trained with overridden resources" @env.task async def main(): # Task using environment-level resources result = await train_model("data.csv") print(result) # Task with overridden resources at invocation time result = await heavy_training_task.override( resources=flyte.Resources( cpu="4", memory="24Gi", disk="100Gi", shm="16Gi" ) )() print(result) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/resources/resources.py* For complete format specifications for each resource type (CPU, memory, GPU/TPU/Device, disk, shared memory), including accepted string formats, request/limit ranges, GPU partitioning, and supported accelerator types, see the **Flyte SDK > flyte > Resources**. ## Accelerators To run a task on a hardware accelerator โ€” an NVIDIA or AMD GPU, a Google TPU, an AWS Trainium/Inferentia (Neuron) chip, an Intel Habana Gaudi device, or, on a devbox only, a Mac's Apple Silicon GPU โ€” set the `gpu` parameter of `Resources`. Despite its name, `gpu` selects any supported accelerator type. You can request an accelerator in three ways: - **Type-and-count string** โ€” `":"`, for example `"T4:1"` or `"A100:8"`. This is the most common form. - **Integer count** โ€” `gpu=2` requests that many GPUs of whatever type is available. - **Device object** โ€” `flyte.GPU()`, `flyte.TPU()`, `flyte.AMD_GPU()`, `flyte.APPLE_SILICON()`, or `flyte.Device()` for advanced configuration such as GPU partitioning (MIG) and TPU slice topologies. The `gpu` value can be set on the `TaskEnvironment` (applying to every task in it) or on a per-task `override`, exactly like the other resource fields shown above. If the environment sets `reusable`, the `override` must also pass `reusable="off"`. > [!NOTE] > Which accelerator types are actually available depends on your deployment and the node pools configured in your cluster. Requesting a type that no node provides will leave the task's pod `Pending`. For Apple Silicon, see **Tasks > Configure tasks > Resources > Accelerators > Apple Silicon (devbox only)**. For the full list of accepted accelerator strings and device-configuration options, see the **Flyte SDK > flyte > Resources**. ### NVIDIA GPUs Request an NVIDIA GPU by type and count: ```python import flyte env = flyte.TaskEnvironment( name="nvidia", resources=flyte.Resources(gpu="T4:1"), # one NVIDIA T4 ) ``` Supported NVIDIA types include `T4`, `L4`, `L40s`, `A10`, `A10G`, `A100`, `A100_80G`, `B200`, `H100`, `H200`, `V100`, `RTX_PRO_4500`, and `RTX_PRO_6000`. The names `A100_80G`, `RTX_PRO_4500`, and `RTX_PRO_6000` require `flyte` 2.11.3 or later. Earlier releases spell `A100_80G` and `RTX_PRO_6000` as `A100 80G` and `RTX PRO 6000`, and have no RTX PRO 4500 type. From `flyte` 2.11.4, the earlier spellings `A100 80G` and `RTX PRO 6000` still work as deprecated aliases and log a deprecation warning. `flyte` 2.11.3 rejects them. In the string form, `RTX_PRO_4500` is accepted only with a count of 1 (`"RTX_PRO_4500:1"`). #### GPU partitioning (MIG) To request a Multi-Instance GPU (MIG) partition, use `flyte.GPU()` with a `partition`: ```python resources=flyte.Resources(gpu=flyte.GPU(device="A100", quantity=1, partition="1g.5gb")) ``` Partitioning is available on `A100`, `A100_80G` (`A100 80G` before `flyte` 2.11.3), `H100`, `H200`, and, from `flyte` 2.12.0, `RTX_PRO_6000`. ### Google TPUs Use `flyte.TPU()` with the device type and, optionally, a slice topology: ```python resources=flyte.Resources(gpu=flyte.TPU(device="V5P", partition="2x2x1")) ``` Supported TPU device types are `V5E`, `V5P`, and `V6E`. `V5E` requires `flyte` 2.8.0 or later. ### AMD GPUs Request an AMD GPU by type and count, or with `flyte.AMD_GPU()`: ```python resources=flyte.Resources(gpu="MI300X:1") ``` Supported AMD types include `MI100`, `MI210`, `MI250`, `MI250X`, `MI300A`, `MI300X`, `MI325X`, `MI350X`, and `MI355X`. The string form and `flyte.AMD_GPU()` accept a count of 1 or 8, for example `"MI355X:8"` or `flyte.AMD_GPU("MI355X", 8)`. A count of 8 requires `flyte` 2.13.2 or later. For any other count, use `flyte.Device(quantity=..., device_class="AMD_GPU", device=...)`. ### AWS Trainium and Inferentia (Neuron) Request AWS Neuron accelerators โ€” Trainium (`Trn`) or Inferentia (`Inf`) โ€” by type and count: ```python resources=flyte.Resources(gpu="Trn1:1") ``` Supported types include `Trn1`, `Trn1n`, `Trn2`, `Trn2u`, `Inf1`, and `Inf2`. ### Intel Habana Gaudi Request an Intel Habana Gaudi accelerator by type and count: ```python resources=flyte.Resources(gpu="Gaudi1:1") ``` ### Apple Silicon (devbox only) On a devbox started with `flyte start devbox --apple-silicon`, request the Mac's GPU with `gpu="AppleSilicon"` or `gpu=flyte.APPLE_SILICON()`. `"AppleSilicon:1"` is also accepted; a higher count is rejected: ```python resources=flyte.Resources(gpu="AppleSilicon") ``` Requires `flyte` 2.12.0 or later. On a remote cluster whose backend includes Apple Silicon support, the task fails with `APPLE_SILICON_NOT_AVAILABLE`. On a backend that predates it, the task's pod stays `Pending` instead. For setup and requirements, see **Get started > Run modes > Run on the Devbox > Using the Apple Silicon GPU**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/secrets === Store API keys and credentials securely and read them from inside a task. # Secrets Flyte secrets enable you to securely store and manage sensitive information, such as API keys, passwords, and other credentials. Secrets reside in a secret store on the data plane of your Union/Flyte backend. You can create, list, and delete secrets in the store using the Flyte CLI or SDK. Secrets in the store can be accessed and used within your workflow tasks, without exposing any cleartext values in your code. On Union.ai, the secret store is in your own infrastructure. It is your cloud provider's secret manager (AWS Secrets Manager, Google Secret Manager, or Azure Key Vault) or Kubernetes Secrets, depending on how your data plane is configured. Secret values never pass through the Union.ai control plane. See **Data protection > Secrets management**. ## Creating a literal string secret You can create a secret using the **Flyte CLI > flyte create secret** command like this: ```bash flyte create secret MY_SECRET_KEY --value my_secret_value ``` This will create a secret called `MY_SECRET_KEY` with the value `my_secret_value`. This secret will be scoped to your entire organization. It will be available across all projects and domains in your organization. See the **Tasks > Configure tasks > Secrets > Scoping secrets** section below for more details. See **Tasks > Configure tasks > Secrets > Using a literal string secret** for how to access the secret in your task code. ## Creating a file secret You can also create a secret by specifying a local file: ```bash flyte create secret MY_SECRET_KEY --from-file /local/path/to/my_secret_file ``` In this case, when accessing the secret in your task code, you will need to **Tasks > Configure tasks > Secrets > Using a file secret**. ## Creating a secret in the UI You can also create and manage secrets in the Union.ai UI: * **Organization-wide secrets:** open **Settings** and select **Secrets** under **Assets & Configuration**. * **Project- or domain-scoped secrets:** navigate into a project and domain, then select **Secrets** in the main sidebar. Secrets created in the UI are the same secrets that the CLI and SDK create, so they can be used from both Flyte 1 and Flyte 2 tasks. Admins can create, update, and delete any secret. Contributors can manage secrets within the projects they are assigned to. See **Identity and access > Role-based access control**. ## Scoping secrets When you create a secret without specifying a project or domain, as we did above, the secret is scoped to the organization level. This means that the secret will be available across all projects and domains in the organization. If your organization spans multiple cluster pools, see **Tasks > Configure tasks > Secrets > Org-wide secrets in a multi-cluster deployment** below: org-wide secrets are stored per pool. You can optionally specify `--domain`, or both `--project` and `--domain`, to restrict the scope of the secret to: * A specific domain (across all projects) * A specific project and a specific domain. For example, to create a secret that it is only available in `my_project/development`, you would execute the following command: ```bash flyte create secret MY_SECRET_KEY --value my_secret_value --project my_project --domain development ``` ## Org-wide secrets in a multi-cluster deployment Each **Clusters and queues > Cluster pools** has its own secret store, declared as part of the pool's data plane configuration. A secret therefore lives in the secret store of one particular pool, not in a single global store. If your organization has more than one **Clusters and queues > Cluster pools**, you must name the pool explicitly with the `--cluster-pool` flag. All three secret commands accept it: ```bash # Create an org-wide secret in the `prod` pool's secret store flyte create secret MY_SECRET_KEY --value my_secret_value --cluster-pool prod # List the org-wide secrets in that pool flyte get secret --cluster-pool prod # Delete an org-wide secret from that pool flyte delete secret MY_SECRET_KEY --cluster-pool prod ``` Use `flyte get cluster-pool` to list the pool names available in your organization. To make the same org-wide secret available to workloads in every pool, create it once per pool. CODE3 ## Listing secrets You can list existing secrets with the [`flyte get secret`](../../../api-reference/flyte-cli.md#flyte-get-secret) command. For example, the following command will list all secrets in the organization: CODE4 Specifying `--domain`, or both `--project` and `--domain`, will list the secrets that are **only** available in that domain, or in that project and domain. For example, to list the secrets that are only available in `my_project` and domain `development`, you would run: CODE5 ## Deleting secrets To delete a secret, use the [`flyte delete secret`](../../../api-reference/flyte-cli.md#flyte-delete-secret) command: CODE6 ## Declaring secrets in a task environment A task can only read a secret that it declares. Declare secrets with the `secrets` parameter of `flyte.TaskEnvironment`, using one or more `flyte.Secret` objects: CODE7 `flyte.Secret` takes the following parameters: | Parameter | Description | |-----------|-------------| | `key` | The name of the secret in the secret store, exactly as you created it (for example, with `flyte create secret`). Required. | | `as_env_var` | The name of the environment variable to inject the secret into. Must be a valid uppercase environment variable name (`^[A-Z_][A-Z0-9_]*$`). | | `mount` | Set to `"/etc/flyte/secrets"` to mount the secret as a file instead of an environment variable. No other path is supported. | | `group` | Optional. Used by some secret stores to organize secrets. If set, it is prepended to the default environment variable name. | Set either `as_env_var` or `mount`, not both. If you set both, the secret is injected as an environment variable. If you set neither, the secret is injected as an environment variable whose name is derived from the key: uppercased, with `-` replaced by `_`, and prefixed with the group if one is given. For example, `flyte.Secret(key="my-db-password")` is injected as `MY_DB_PASSWORD`, and `flyte.Secret(key="password", group="db")` as `DB_PASSWORD`. As a shorthand, you can pass a key string instead of a `flyte.Secret` object: `secrets="my-db-password"` is equivalent to `secrets=flyte.Secret(key="my-db-password")`. ## Using a literal string secret To use a literal string secret, specify it in the `TaskEnvironment` along with the name of the environment variable into which it will be injected. You can then access it using `os.getenv()` in your task code. For example: CODE8 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/secrets/secrets.py* ## Using a file secret To use a file secret, specify it in the `TaskEnvironment` along with the `mount="/etc/flyte/secrets"` argument (with that precise value). The file will be mounted at `/etc/flyte/secrets/`. For example: CODE9 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/secrets/secrets.py* > [!NOTE] > Currently, to access a file secret you must specify a `mount` parameter value of `"/etc/flyte/secrets"`. > This fixed path is the directory in which the secret file will be placed. > The name of the secret file is the key of the secret exactly as you created it, including its case. > For example, a secret created as `MY_CERT` is mounted at `/etc/flyte/secrets/MY_CERT`. The path above applies to secrets created with `flyte create secret`, the SDK, or the UI. Secrets read directly from an external store use a different, provider-specific path: see [AWS Secrets Manager](../../../deployment/byoc/enabling-aws-resources/enabling-aws-secrets-manager.md) or [Azure Key Vault](../../../deployment/byoc/enabling-azure-resources/enabling-azure-key-vault.md). ## Using secrets in local runs When you run a task locally, for example with `flyte run --local` or by calling the task directly in Python, secrets are **not** fetched from the secret store. Your code reads secrets from environment variables and files, so you need to provide those yourself in your local environment. ### Environment variable secrets Export an environment variable with the name that the task reads. This is the `as_env_var` name, or the [default name derived from the key](#declaring-secrets-in-a-task-environment). For the literal string secret example above: CODE10 ### File secrets A file secret created with `flyte create secret`, the SDK, or the UI is read from `/etc/flyte/secrets/`. For a secret from an external store, use that provider's path instead. To simulate the secret locally, create the file at that path: CODE11 Writing to `/etc` usually needs `sudo`. To avoid that, you can build the path from the `FLYTE_SECRETS_DEFAULT_DIR` environment variable. It is set to `/etc/flyte/secrets` in the task container when a file secret is mounted, so locally you can point it at any directory you like: CODE12 CODE13 > [!WARNING] > Do not commit local secret files or `export` lines containing secret values to source control. ## Overriding secrets at invocation time The secrets above are declared when the task is defined, on the `TaskEnvironment`. You can also override which secrets are injected for a **single invocation** of a task using `task.override(secrets=...)` — useful when the same task needs different credentials depending on how it's called. See [Overriding secrets](overrides.md#overriding-secrets) for details and an example. > [!NOTE] > A `TaskEnvironment` can only access a secret if the scope of the secret includes the project and domain where the `TaskEnvironment` is deployed. > [!WARNING] > Do not return secret values from tasks. Returned values are stored in plaintext in your data plane's object store and shown in the UI and to downstream tasks, defeating the secret store's protections. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/caching === Skip recomputation by reusing a previous task result, and control when that happens. # Caching Flyte 2 provides intelligent **task output caching** that automatically avoids redundant computation by reusing previously computed task results. > [!NOTE] > Caching works at the task level and caches complete task outputs. > For function-level checkpointing and resumption *within tasks*, see **Tasks > Build tasks > Traces**. ## Overview By default, caching is disabled, except for shell tasks and code sandbox tasks. If caching is enabled for a task, then Flyte determines a **cache key** for the task. The key is composed of the following: * Final inputs: The set of inputs after removing any specified in the `ignored_inputs`. * Task name: The fully-qualified name of the task. * Interface hash: A hash of the task's input and output types. * Cache version: The cache version string. If the cache behavior is set to `"auto"`, the cache version is automatically generated using a hash of the task's source code (or according to the custom policy if one is specified). For container, shell and code sandbox tasks, `flyte` 2.12.0 or later generates it from what the container runs (see **Tasks > Configure tasks > Caching > Cache policies > Container and shell tasks**). If the cache behavior is set to `"override"`, the cache version can be specified explicitly using the `version_override` parameter. When the task runs, Flyte checks if a cache entry exists for the key. If found, the cached result is returned immediately instead of re-executing the task. ## Basic caching usage Flyte 2 supports three main cache behaviors: ### `"auto"` - automatic versioning ``` @env.task(cache=flyte.Cache(behavior="auto")) async def auto_versioned_task(data: str) -> str: return await transform_data(data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* With `behavior="auto"`, the cache version is automatically generated based on the function's source code. If you change the function implementation, the cache is automatically invalidated. - **When to use**: Development and most production scenarios. - **Cache invalidation**: Automatic when function code changes. - **Benefits**: Zero-maintenance caching that "just works". You can also use the direct string shorthand: ``` @env.task(cache="auto") async def auto_versioned_task_2(data: str) -> str: return await transform_data(data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* ### `"override"` With `behavior="override"`, you can specify a custom cache key in the `version_override` parameter. Since the cache key is fixed as part of the code, it can be manually changed when you need to invalidate the cache. ``` @env.task(cache=flyte.Cache(behavior="override", version_override="v1.2")) async def manually_versioned_task(data: str) -> str: return await transform_data(data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* - **When to use**: When you need explicit control over cache invalidation. - **Cache invalidation**: Manual, by changing `version_override`. - **Benefits**: Stable caching across code changes that don't affect logic. ### `"disable"` - No caching To explicitly disable caching, use the `"disable"` behavior. **This is the default behavior, except for shell tasks and code sandbox tasks.** ``` @env.task(cache=flyte.Cache(behavior="disable")) async def always_fresh_task(data: str) -> str: return get_current_timestamp() + await transform_data(data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* - **When to use**: Non-deterministic functions, side effects, or always-fresh data. - **Cache invalidation**: N/A - never cached. - **Benefits**: Ensures execution every time. You can also use the direct string shorthand: ``` @env.task(cache="disable") async def always_fresh_task_2(data: str) -> str: return get_current_timestamp() + await transform_data(data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* ## Advanced caching configuration ### Ignoring specific inputs Sometimes you want to cache based on some inputs but not others: ``` @env.task(cache=flyte.Cache(behavior="auto", ignored_inputs=("debug_flag",))) async def selective_caching(data: str, debug_flag: bool) -> str: if debug_flag: print(f"Debug: transforming {data}") return await transform_data(data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* **This is useful for**: - Debug flags that don't affect computation - Logging levels or output formats - Metadata that doesn't impact results ### Cache serialization Cache serialization ensures that only one instance of a task runs at a time for identical inputs: ``` @env.task(cache=flyte.Cache(behavior="auto", serialize=True)) async def expensive_model_training(data: str) -> str: return await transform_data(data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* **When to use serialization**: - Very expensive computations (model training, large data processing) - Shared resources that shouldn't be accessed concurrently - Operations where multiple parallel executions provide no benefit **How it works**: 1. First execution acquires a reservation and runs normally. 2. Concurrent executions with identical inputs wait for the first to complete. 3. Once complete, all waiting executions receive the cached result. 4. If the running execution fails, another waiting execution takes over. ### Salt for cache key variation Use `salt` to vary cache keys without changing function logic: ``` @env.task(cache=flyte.Cache(behavior="auto", salt="experiment_2024_q4")) async def experimental_analysis(data: str) -> str: return await transform_data(data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* **`salt` is useful for**: - A/B testing with identical code. - Temporary cache namespaces for experiments. - Environment-specific cache isolation. ## Caching with `flyte.map` When you **Tasks > Build tasks > Mapping over inputs**, each item runs as its own **independent task action** with its own inputs. Caching therefore applies **per element**: configure the cache on the mapped task (via the `@env.task` decorator or the `TaskEnvironment`, exactly as above โ€” there is no separate cache setting on the `flyte.map` call itself), and Flyte computes a cache key for each item individually. The per-element cache key is that item's mapped input(s) plus the standard components โ€” the task name, interface hash, and cache version. Two consequences follow: - **Unchanged items are cache hits even when other items change.** If you re-run a map and only some items differ, the unchanged items are served from cache and only the changed ones recompute. - **Order doesn't matter.** The cache key depends on an item's own inputs, not its position, so reordering the input list (or changing the list's length) doesn't invalidate the items that are still present. For example, mapping `[1, 2, 3]` and later mapping `[3, 1, 4]` recomputes only the new item `4`; `1`, `2`, and `3` are already cached. ### Excluding a bound argument from the per-element key When you bind constant arguments with `functools.partial` (see **Tasks > Build tasks > Mapping over inputs > Binding constant arguments with `functools.partial`**), those bound values become part of **each element's** cache key. If a bound value changes between runs but does not affect the result โ€” a run ID, a status flag, a timestamp โ€” every element misses the cache. Add such volatile inputs to `ignored_inputs` on the mapped task so they're dropped from the key: ```python from functools import partial import flyte env = flyte.TaskEnvironment(name="map-cache") @env.task(cache=flyte.Cache(behavior="auto", ignored_inputs=("batch_id",))) async def score(compound_id: str, batch_id: str) -> str: ... @env.task async def main(batch_id: str) -> list[str]: compounds = [str(i) for i in range(3)] scorer = partial(score, batch_id=batch_id) # batch_id is bound for every item but ignored for caching, so each # element is keyed only on compound_id. return list(flyte.map(scorer, compounds)) ``` Here `batch_id` is constant across the map yet varies between runs; listing it in `ignored_inputs` keeps each element's cache keyed only on `compound_id`, so the items are reused across runs. ## Content-based caching for DataFrames, files, and directories When a task input is a DataFrame (`pandas`, `polars`, or `flyte.io.DataFrame`), a `flyte.io.File`, or a `flyte.io.Dir`, the value is passed *by reference* - the cache key is derived from the data's storage location, not its contents. As a result, a downstream task keyed on such an input does **not** get a cache hit when the underlying data is identical but lives at a new path (the common case, since each run writes to a fresh location). To cache on **content** instead, attach a hash of the data at the point where it is produced. Flyte then uses that content hash when computing the cache key of any downstream consuming task, so identical content produces a cache hit regardless of where it is stored. > [!NOTE] > In-process runs also use content hashes for DataFrames and for a `Dir` with a `dir_cache_key`. A `File` given a `HashFunction` through `hash_method` is keyed on its location when the run's raw-data path is local, the default for in-process runs, so identical content at a new path is a cache miss. See **Tasks > Configure tasks > Caching > Local development caching**. ### DataFrames For a raw `pandas` or `polars` DataFrame, supply a content hash with `flyte.io.HashFunction.from_fn` in a `typing.Annotated` return type. Define the hash function once and reuse the annotated alias: ``` def hash_pandas_dataframe(df: pd.DataFrame) -> str: # Content-based hash using pandas' built-in row hashing. return str(pd.util.hash_pandas_object(df).sum()) # Reusable type alias: a pandas DataFrame whose cache key is its content hash. HashedPandasDataFrame = Annotated[pd.DataFrame, HashFunction.from_fn(hash_pandas_dataframe)] @env.task async def produce_pandas() -> HashedPandasDataFrame: # The HashFunction in the return annotation tells Flyte to compute a # content hash for this output. return pd.DataFrame(SAMPLE_DATA) @env.task(cache=Cache(behavior="override", version_override="v1")) async def consume_pandas(df: pd.DataFrame) -> int: # Cached on the input's content hash: identical content -> cache hit. return int(df["value"].sum()) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/content_caching.py* The producer's return annotation tells Flyte to compute the content hash; the consumer is cached on it. The same pattern works for `polars`: ``` def hash_polars_dataframe(df: pl.DataFrame) -> str: return str(df.hash_rows().sum()) HashedPolarsDataFrame = Annotated[pl.DataFrame, HashFunction.from_fn(hash_polars_dataframe)] @env.task async def produce_polars() -> HashedPolarsDataFrame: return pl.DataFrame(SAMPLE_DATA) @env.task(cache=Cache(behavior="override", version_override="v1")) async def consume_polars(df: pl.DataFrame) -> int: return int(df["value"].sum()) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/content_caching.py* For `flyte.io.DataFrame`, pass the `HashFunction` to `DataFrame.from_local` via the `hash_method` parameter instead of annotating the return type: ``` @env.task async def produce_flyte_dataframe() -> DataFrame: df = pd.DataFrame(SAMPLE_DATA) # For flyte.io.DataFrame, pass the HashFunction to `from_local` instead of # annotating the return type. hash_method = HashFunction.from_fn(hash_pandas_dataframe) return await DataFrame.from_local(df, hash_method=hash_method) @env.task(cache=Cache(behavior="override", version_override="v1")) async def consume_flyte_dataframe(df: DataFrame) -> int: pdf = await df.open(pd.DataFrame).all() return int(pdf["value"].sum()) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/content_caching.py* ### Files A `flyte.io.File` accepts a `hash_method` on `File.from_local` (and on `File.new_remote`). Pass a `HashFunction` that hashes the file's bytes, and the file is cached on its content rather than its remote path, except in an in-process run with a local raw-data path, where the file isn't hashed (see the note above): ``` def hash_bytes(data: bytes) -> str: import hashlib return hashlib.sha256(data).hexdigest() @env.task async def produce_file() -> File: import aiofiles async with aiofiles.open("/tmp/data.csv", "w") as fh: await fh.write("id,value\n1,100\n2,200\n") # Pass a HashFunction (over the uploaded bytes) to `from_local` - the same # mechanism works for `File.new_remote(...)`. The File is then cached on its # content rather than its remote path. return await File.from_local("/tmp/data.csv", hash_method=HashFunction.from_fn(hash_bytes)) @env.task(cache=Cache(behavior="override", version_override="v1")) async def consume_file(f: File) -> str: async with f.open("rb") as fh: return hash_bytes(bytes(await fh.read())) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/content_caching.py* ### Directories `flyte.io.Dir.from_local` does **not** take a `HashFunction` callable. Instead, compute a content key yourself and pass it as the precomputed `dir_cache_key`: ``` @env.task async def produce_dir() -> Dir: import os os.makedirs("/tmp/data_dir", exist_ok=True) with open("/tmp/data_dir/part.csv", "w") as fh: fh.write("id,value\n1,100\n") # `Dir.from_local` does not take a HashFunction callable. Instead, compute a # content key yourself and pass it as the precomputed `dir_cache_key`. content_key = hash_bytes(b"id,value\n1,100\n") return await Dir.from_local("/tmp/data_dir/", dir_cache_key=content_key) @env.task(cache=Cache(behavior="override", version_override="v1")) async def consume_dir(d: Dir) -> int: count = 0 async for _ in d.walk(): count += 1 return count ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/content_caching.py* ## Cache policies For details on implementing custom cache policies, see the [`CachePolicy` protocol](../../../api-reference/flyte-sdk/flyte/cachepolicy.md) and [`Cache` class](../../../api-reference/flyte-sdk/flyte/cache.md) API references. For `behavior="auto"`, Flyte uses cache policies to generate version hashes. ### Function body policy (default) The default `FunctionBodyPolicy` generates cache versions from the function's source code: CODE11 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* ### Container and shell tasks A container task (`ContainerTask`), a shell task (`flyte.extras.shell`) or a code sandbox task (`flyte.sandbox.create()`) has no Python function to hash. With `behavior="auto"` and `flyte` 2.12.0 or later, its cache version is a hash of the following: * The image * The command (for a shell task, the rendered script) and the arguments * The input and output data directories, the metadata format and the file input layout Changing any of these invalidates the cache. Shell tasks and code sandbox tasks use `cache="auto"` by default. Container tasks don't cache unless you set `cache`. In `flyte` 2.12.0 through 2.12.2, `ContainerTask.override()` raises a `TypeError`, so on those versions set `cache` when you create the task. A code sandbox passes your code to the container as an input file identified by a hash of its content, so editing the code also invalidates the cache, through the inputs rather than the cache version. * `env_vars` are not part of the cache version. Changing an environment variable doesn't invalidate the cache. * An image given as a tag reference, such as `"alpine:latest"` or `flyte.Image.from_base("alpine:latest")`, is versioned by the reference string. The cache version stays the same when the tag moves to a new image. Before `flyte` 2.12.0, every container and shell task gets the same cache version, so editing the command, the script or the image never invalidates the cache. On those versions, an edited shell task keeps returning its old result, because shell tasks cache by default. To avoid this, upgrade `flyte` or set `cache="disable"`. ### Custom cache policies You can implement custom cache policies by following the `CachePolicy` protocol: CODE12 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* ## Caching configuration at different levels You can configure caching at three levels: `TaskEnvironment` definition, `@env.task` decorator, and task invocation. ### `TaskEnvironment` level You can configure caching at the `TaskEnvironment` level. This will set the default cache behavior for all tasks defined using that environment. For example: CODE13 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* ### `@env.task` decorator level By setting the cache parameter in the `@env.task` decorator, you can override the environment's default cache behavior for specific tasks: CODE14 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* ### `task.override` level By setting the cache parameter in the `task.override` method, you can override the cache behavior for specific task invocations: CODE15 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/caching/caching.py* ## Runtime cache control You can also force cache invalidation for a specific run: CODE16 ## Project and domain cache isolation Caches are automatically isolated by: - **Project**: Tasks in different projects have separate cache namespaces. - **Domain**: Development, staging, and production domains maintain separate caches. ## Local development caching When running in-process, Flyte keeps a local cache in a SQLite database, so a cached task called again with the same inputs returns its stored outputs, including across runs: CODE17 Local cache behavior: - Stored in `local-cache/cache.db`, in the directory that holds your config file (for example `.flyte/local-cache/`), or in `~/.flyte/local-cache/` when no config file is found - Only `behavior="auto"` reads from the local cache - No project/domain isolation (since running locally) === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/reusable-containers === Keep a container warm across task executions instead of creating a fresh one each time. # Reusable containers By default, each task execution in Flyte and Union runs in a fresh container instance that is created just for that execution and then discarded. With reusable containers, the same container can be reused across multiple executions and tasks. This approach reduces start up overhead and improves resource efficiency. > [!NOTE] > The reusable container feature is only available when running your Flyte code on a Union backend. ## Why use reusable containers The default fresh-container-per-execution model gives every execution strong isolation, but it pays a cold-start cost on every execution: the container has to be created, the image pulled, and the Python process initialized before your code runs. When that startup cost is large relative to how long the task actually runs, the overhead dominates. Reusable containers address this by keeping a pool of warm containers ready to accept work. Reach for them when you have: - **Many short tasks with high per-execution startup cost.** Fan-out and map-style workloads โ€” where the same small task runs hundreds or thousands of times โ€” benefit most, because the startup overhead is paid once per container instead of once per execution. - **Expensive in-memory state to keep warm.** Because the same container (and its Python process) is reused across executions, you can load a model or dataset once and reuse it on subsequent invocations โ€” for example by caching it in a global variable or with an in-memory cache โ€” instead of reloading it every time. Prefer in-memory artifacts for this; a long-lived connection can go stale (credential rotation, idle timeouts), so if you cache one, guard it with a health check and reconnect when needed. - **A need for higher throughput and better resource utilization.** A reusable environment can process multiple async task executions concurrently within each container. Total capacity is `max_replicas ร— concurrency`, so you can drive up utilization without provisioning a fresh container per task. See **Scale your runs > Scale your workflows** for how this fits into a broader scaling strategy. Stick with the default (non-reusable) model when tasks are long-running, run infrequently, or need strong isolation between executions โ€” in those cases the startup cost is negligible and container reuse adds no benefit. ## How it works With reusable containers, the system maintains a pool of persistent containers that can handle multiple task executions. When you configure a `TaskEnvironment` with a `ReusePolicy`, the system does the following: 1. Creates a pool of persistent containers. 2. Routes task executions to available container instances. 3. Manages container lifecycle with configurable timeouts. 4. Supports concurrent task execution within containers (for async tasks). 5. Preserves the Python execution environment across task executions, allowing you to maintain state through global variables. ## Basic usage > [!NOTE] > The reusable containers feature currently requires a dedicated runtime library > ([`unionai-reuse`](https://pypi.org/project/unionai-reuse/)) to be installed in the task image used by the reusable task. > You can add this library to your task image using the `flyte.Image.with_pip_packages` method, as shown below. > This library only needs to be added to the task image. > It does not need to be installed in your local development environment. Enable container reuse by adding a `ReusePolicy` to your `TaskEnvironment`: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # main = "main" # params = "n=500" # /// import flyte from datetime import timedelta # {{docs-fragment env}} # Currently required to enable resuable containers reusable_image = flyte.Image.from_debian_base().with_pip_packages("unionai-reuse>=0.1.10") env = flyte.TaskEnvironment( name="reusable-env", resources=flyte.Resources(memory="1Gi", cpu="500m"), reusable=flyte.ReusePolicy( replicas=2, # Create 2 container instances concurrency=1, # Process 1 task per container at a time scaledown_ttl=timedelta(minutes=10), # Individual containers shut down after 5 minutes of inactivity idle_ttl=timedelta(hours=1) # Entire environment shuts down after 30 minutes of no tasks ), image=reusable_image # Use the container image augmented with the unionai-reuse library. ) # {{/docs-fragment env}} @env.task async def compute_task(x: int) -> int: return x * x @env.task async def main() -> list[int]: # These tasks will reuse containers from the pool results = [] for i in range(10): result = await compute_task(i) results.append(result) return results if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/reusable-containers/reuse.py* ## `ReusePolicy` parameters For complete parameter documentation, including accepted types, defaults, capacity math, and lifecycle behavior, see the **Flyte SDK > flyte > ReusePolicy**. > [!NOTE] > The `scope` parameter, which restricts reuse to a single run, currently applies only to [reusable Ray clusters](../../../integrations/ray/_index#reusable-ray-clusters). A reusable container environment is shared across runs regardless of the value you set. ## Understanding parameter relationships The four `ReusePolicy` parameters work together to control different aspects of container management: ```python reuse_policy = flyte.ReusePolicy( replicas=4, # Infrastructure: How many containers? concurrency=3, # Throughput: How many tasks per container? scaledown_ttl=timedelta(minutes=10), # Individual: When do idle containers shut down? idle_ttl=timedelta(hours=1) # Environment: When does the whole pool shut down? ) # Total capacity: 4 ร— 3 = 12 concurrent tasks # Individual containers shut down after 10 minutes of inactivity # Entire environment shuts down after 1 hour of no tasks ``` ### Key relationships - **Total throughput** = `replicas ร— concurrency` - **Resource usage** = `replicas ร— TaskEnvironment.resources` - **Cost efficiency**: Higher `concurrency` reduces container overhead, more `replicas` provides better isolation - **Lifecycle management**: `scaledown_ttl` manages individual containers, `idle_ttl` manages the environment ## Simple example Here is a simple, but complete, example of reuse with concurrency. First, import the needed modules and set up logging: ``` import asyncio import logging import flyte logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/reusable-containers/reuse_concurrency.py* Next, we set up the reusable task environment. Note that, currently, the image used for a reusable environment requires an extra package to be installed: ``` env = flyte.TaskEnvironment( name="reuse_concurrency", resources=flyte.Resources(cpu=1, memory="1Gi"), reusable=flyte.ReusePolicy( replicas=2, idle_ttl=60, concurrency=100, scaledown_ttl=60, ), image=flyte.Image.from_debian_base().with_pip_packages("unionai-reuse>=0.1.10"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/reusable-containers/reuse_concurrency.py* Now, we define the `reuse_concurrency` task (the main driver task of the workflow) and the `noop` task that will be executed multiple times reusing the same containers: ``` @env.task async def noop(x: int) -> int: logger.debug(f"Task noop: {x}") return x @env.task async def main(n: int = 50) -> int: coros = [noop(i) for i in range(n)] results = await asyncio.gather(*coros) return sum(results) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/reusable-containers/reuse_concurrency.py* Finally, we deploy and run the workflow programmatically, so all you have to do is execute `python reuse_concurrency.py` to see it in action: ``` if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main, n=500) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/reusable-containers/reuse_concurrency.py* === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/pod-templates === Reach the underlying Kubernetes pod spec for anything Flyte does not expose directly. # Pod templates Flyte is built on Kubernetes and uses its powerful container orchestration capabilities. A Kubernetes [pod](https://kubernetes.io/docs/concepts/workloads/pods/) is a group of one or more containers that share storage and network resources. While Flyte automatically runs your task code in a container, pod templates let you customize the entire pod specification for advanced use cases. The `pod_template` parameter in `TaskEnvironment` allows you to: - **Add sidecar containers**: Run metrics exporters, service proxies, or specialized services alongside your task - **Mount volumes**: Attach persistent storage or cloud storage like GCS or S3 - **Configure metadata**: Set custom labels and annotations for monitoring, routing, or cluster policies - **Manage resources**: Configure resource requests, limits, and affinities - **Inject configuration**: Add secrets, environment variables, or config maps - **Access private registries**: Specify image pull secrets ## How it works When you define a pod template: 1. **Primary container**: Flyte automatically injects your task code into the container specified by `primary_container_name` (default: `"primary"`) 2. **Automatic monitoring**: Flyte watches the primary container and exits the entire pod when it completes 3. **Image handling**: The image for your task environment is built automatically by Flyte; images for sidecar containers must be provided by you 4. **Local execution**: When running locally, only the task code executes; additional containers are not started ## Requirements To use pod templates, install the Kubernetes Python client: ```bash pip install kubernetes ``` Or add it to your image dependencies: ```python image = flyte.Image.from_debian_base().with_pip_packages("kubernetes") ``` ## Basic usage Here's a complete example showing how to configure labels, annotations, environment variables, and image pull secrets: ``` # /// script # requires-python = "==3.12" # dependencies = [ # "flyte>=2.0.0b52", # "kubernetes" # ] # /// import flyte from kubernetes.client import ( V1Container, V1EnvVar, V1LocalObjectReference, V1PodSpec, ) # Create a custom pod template pod_template = flyte.PodTemplate( primary_container_name="primary", # Name of the main container labels={"lKeyA": "lValA"}, # Custom pod labels annotations={"aKeyA": "aValA"}, # Custom pod annotations pod_spec=V1PodSpec( # Kubernetes pod specification containers=[ V1Container( name="primary", env=[V1EnvVar(name="hello", value="world")] # Environment variables ) ], image_pull_secrets=[ # Access to private registries V1LocalObjectReference(name="regcred-test") ], ), ) # Use the pod template in a TaskEnvironment env = flyte.TaskEnvironment( name="hello_world", pod_template=pod_template, # Apply the custom pod template image=flyte.Image.from_uv_script(__file__, name="flyte", pre=True), ) @env.task async def say_hello(data: str) -> str: return f"Hello {data}" @env.task async def say_hello_nested(data: str = "default string") -> str: return await say_hello(data=data) if __name__ == "__main__": flyte.init_from_config() result = flyte.run(say_hello_nested, data="hello world") print(result.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/pod-templates/pod_template.py* ## PodTemplate parameters The `PodTemplate` class provides the following parameters: | Parameter | Type | Description | |-----------|------|-------------| | `primary_container_name` | `str` | Name of the container where task code runs (default: `"primary"`). Must match a container in `pod_spec`. | | `pod_spec` | `V1PodSpec` | Kubernetes pod specification for configuring containers, volumes, security contexts, and more. | | `labels` | `dict[str, str]` | Pod labels for organization and selection by Kubernetes selectors. | | `annotations` | `dict[str, str]` | Pod annotations for metadata and integrations (doesn't affect scheduling). | ## Volume mounts Pod templates are commonly used to mount volumes for persistent storage or cloud storage access: ```python from kubernetes.client import ( V1Container, V1PodSpec, V1Volume, V1VolumeMount, V1CSIVolumeSource, ) import flyte pod_template = flyte.PodTemplate( primary_container_name="primary", pod_spec=V1PodSpec( containers=[ V1Container( name="primary", volume_mounts=[ V1VolumeMount( name="data-volume", mount_path="/mnt/data", read_only=False, ) ], ) ], volumes=[ V1Volume( name="data-volume", csi=V1CSIVolumeSource( driver="your-csi-driver", volume_attributes={"key": "value"}, ), ) ], ), ) env = flyte.TaskEnvironment( name="volume-example", pod_template=pod_template, image=flyte.Image.from_debian_base(), ) @env.task async def process_data() -> str: # Access mounted volume with open("/mnt/data/input.txt", "r") as f: data = f.read() return f"Processed {len(data)} bytes" ``` ### GCS/S3 volume mounts Mount cloud storage directly into your pod for efficient data access: ```python from kubernetes.client import V1Container, V1PodSpec, V1Volume, V1VolumeMount, V1CSIVolumeSource import flyte # GCS example with CSI driver pod_template = flyte.PodTemplate( primary_container_name="primary", annotations={ "gke-gcsfuse/volumes": "true", "gke-gcsfuse/cpu-limit": "2", "gke-gcsfuse/memory-limit": "1Gi", }, pod_spec=V1PodSpec( containers=[ V1Container( name="primary", volume_mounts=[V1VolumeMount(name="gcs", mount_path="/mnt/gcs")], ) ], volumes=[ V1Volume( name="gcs", csi=V1CSIVolumeSource( driver="gcsfuse.csi.storage.gke.io", volume_attributes={"bucketName": "my-bucket"}, ), ) ], ), ) ``` ## Sidecar containers Add sidecar containers to run alongside your task. Common use cases include: - **Metrics exporters**: Prometheus, Datadog agents - **Service proxies**: Istio, Linkerd sidecars - **Data services**: Databases, caches, or specialized services like Nvidia NIMs ```python from kubernetes.client import V1Container, V1PodSpec import flyte pod_template = flyte.PodTemplate( primary_container_name="primary", pod_spec=V1PodSpec( containers=[ # Primary container (where your task code runs) V1Container(name="primary"), # Sidecar container V1Container( name="metrics-sidecar", image="prom/pushgateway:latest", ports=[{"containerPort": 9091}], ), ], ), ) env = flyte.TaskEnvironment( name="sidecar-example", pod_template=pod_template, image=flyte.Image.from_debian_base().with_pip_packages("requests"), ) @env.task async def task_with_metrics() -> str: import requests # Send metrics to sidecar requests.post("http://localhost:9091/metrics", data="my_metric 42") # Your task logic return "Task completed with metrics" ``` ## Image pull secrets Configure private registry access: ```python from kubernetes.client import V1Container, V1PodSpec, V1LocalObjectReference import flyte pod_template = flyte.PodTemplate( primary_container_name="primary", pod_spec=V1PodSpec( containers=[V1Container(name="primary")], image_pull_secrets=[V1LocalObjectReference(name="my-registry-secret")], ), ) ``` ## Cluster-specific configuration Pod templates are often used to configure Kubernetes-specific settings required by your cluster, even when not using multiple containers: ```python import flyte pod_template = flyte.PodTemplate( primary_container_name="primary", annotations={ "iam.amazonaws.com/role": "my-task-role", # AWS IAM role "cluster-autoscaler.kubernetes.io/safe-to-evict": "false", }, labels={ "cost-center": "ml-team", "project": "recommendations", }, ) ``` ## Important notes 1. **Local execution**: Pod templates only apply to on-cluster execution. When running locally, only your task code executes. 2. **Image building**: Flyte automatically builds and manages the image for your task environment. Images for sidecar containers must be pre-built and available in a registry. 3. **Primary container**: Your task code is automatically injected into the container matching `primary_container_name`. This container must be defined in the `pod_spec.containers` list. 4. **Lifecycle management**: Flyte monitors the primary container and terminates the entire pod when it exits, ensuring sidecar containers don't run indefinitely. ## Best practices 1. **Start simple**: Begin with basic labels and annotations before adding complex sidecars 2. **Test locally first**: Verify your task logic works locally before adding pod customizations 3. **Use environment-specific templates**: Different environments (dev, staging, prod) may need different pod configurations 4. **Set resource limits**: Always set resource requests and limits for sidecars to prevent cluster issues 5. **Security**: Use image pull secrets and least-privilege service accounts ## Learn more - [Kubernetes Pods Documentation](https://kubernetes.io/docs/concepts/workloads/pods/) - [Kubernetes Python Client](https://github.com/kubernetes-client/python) - [V1PodSpec Reference](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#podspec-v1-core) === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/multiple-environments === Give different tasks in one workload different images, resources, and configuration. # Multiple environments In many applications, different tasks within your workflow may require different configurations. Flyte enables you to manage this complexity by allowing multiple environments within a single workflow. Multiple environments are useful when: - Different tasks in your workflow need different dependencies. - Some tasks require specific CPU/GPU or memory configurations. - A task requires a secret that other tasks do not (and you want to limit exposure of the secret value). - You're integrating specialized tools that have conflicting requirements. ## Constraints on multiple environments To use multiple environments in your workflow you define multiple `TaskEnvironment` instances, each with its own configuration, and then assign tasks to their respective environments. There are, however, two additional constraints that you must take into account. If `task_1` in environment `env_1` calls a `task_2` in environment `env_2`, then: 1. `env_1` must declare a deployment-time dependency on `env_2` in the `depends_on` parameter of `TaskEnvironment` that defines `env_1`. 2. The image used in the `TaskEnvironment` of `env_1` must include the import-time dependencies of the module that defines `task_2` (unless **Tasks > Build tasks > Remote tasks**). ### Task `depends_on` constraints The `depends_on` parameter in `TaskEnvironment` is used to provide deployment-time dependencies by establishing a relationship between one `TaskEnvironment` and another. The system uses this information to determine which environments (and, specifically which images) need to be built in order to be able to run the code. On `flyte run` (or `flyte deploy`), the system walks the tree defined by the `depends_on` relationships, starting with the environment of the task being invoked (or the environment being deployed, in the case of `flyte deploy`), and prepares each required environment. Most importantly, it ensures that the container images need for all required environments are available (and if not, it builds them). This deploy-time determination of what to build is important because it means that for any given `run` or `deploy`, only those environments that are actually required are built. The alternative strategy of building all environments defined in the set of deployed code can lead to unnecessary and expensive builds, especially when iterating on code. ### Dependency inclusion constraints When a parent task invokes a child task in a different environment, the container image of the parent task environment must include the import-time dependencies of the module that defines the child task. This is narrower than every dependency the child task uses. It is what Python evaluates when the module is imported: - To invoke a child task by function name, the parent has to import the module that defines it. Importing that module runs the module's top-level statements: its module-level imports, its `Image` and `TaskEnvironment` definitions, and the `@env.task` decoration of each task in it. - Decorating a task builds its interface, which resolves the type annotations on the task's parameters and return value. Every name in those annotations has to be importable in the parent image. - The body of the child task function does not run in the parent. The child task still executes in its own environment, using its own image. So the parent image needs what the child's module imports at the top level, plus what the child task's signature refers to. It does not need a package that the child task imports inside its function body. You have two ways to keep a dependency out of the parent image: import it inside the task function, or invoke the child task remotely. #### Import the dependency inside the task function If a package is only used in the body of a child task, import it there rather than at module level. The child task, in `other/run.py`: ```python import flyte other_env = flyte.TaskEnvironment( name="other_env", image=flyte.Image.from_debian_base().with_pip_packages("polars"), ) @other_env.task async def row_count(path: str) -> int: import polars as pl return pl.read_parquet(path).height ``` The parent task, in `main.py`: ```python import flyte from other.run import other_env, row_count env = flyte.TaskEnvironment( name="main_env", depends_on=[other_env], image=flyte.Image.from_debian_base(), ) @env.task async def main(path: str) -> int: return await row_count(path) ``` The image for `main_env` does not include `polars`, because `other/run.py` imports it inside `row_count` rather than at module level. Importing `other/run.py` in the parent still works, and `row_count` still runs in `other_env`, where `polars` is installed. Keep at module level anything that has to resolve when the module is imported: - Names used in a task's parameter or return annotations. A name imported only in the function body raises `NameError` when the module is imported, including in a module that uses `from __future__ import annotations`. - Values passed to `TaskEnvironment`, `Image`, or the `@env.task` decorator, such as the package lists used to build an image. #### Invoke the child task remotely You can also avoid the requirement by **Tasks > Build tasks > Remote tasks**. The parent then refers to the child task by name instead of importing it, so the parent image needs nothing from the child's module. ## Example The following example is a (very) simple mock of an AlphaFold2 pipeline. It demonstrates a workflow with three tasks, each in its own environment. The example project looks like this: ```bash โ”œโ”€โ”€ msa/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ””โ”€โ”€ run.py โ”œโ”€โ”€ fold/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ””โ”€โ”€ run.py โ”œโ”€โ”€ __init__.py โ””โ”€โ”€ main.py ``` (The source code for this example can be found here:[AlphaFold2 mock example](https://github.com/unionai/unionai-examples/tree/main/v2/user-guide/task-configuration/multiple-environments/af2)) In file `msa/run.py` we define the task `run_msa`, which mocks the multiple sequence alignment step of the process: ```python import flyte from flyte.io import File MSA_PACKAGES = ["pytest"] msa_image = flyte.Image.from_debian_base().with_pip_packages(*MSA_PACKAGES) msa_env = flyte.TaskEnvironment(name="msa_env", image=msa_image) @msa_env.task def run_msa(x: str) -> File: f = File.new_remote() with f.open_sync("w") as fp: fp.write(x) return f ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/multiple-environments/af2/msa/run.py* * A dedicated image (`msa_image`) is built using the `MSA_PACKAGES` dependency list, on top of the standard base image. * A dedicated environment (`msa_env`) is defined for the task, using `msa_image`. * The task is defined within the context of the `msa_env` environment. In file `fold/run.py` we define the task `run_fold`, which mocks the fold step of the process: ```python import flyte from flyte.io import File FOLD_PACKAGES = ["ruff"] fold_image = flyte.Image.from_debian_base().with_pip_packages(*FOLD_PACKAGES) fold_env = flyte.TaskEnvironment(name="fold_env", image=fold_image) @fold_env.task def run_fold(sequence: str, msa: File) -> list[str]: with msa.open_sync("r") as f: msa_content = f.read() return [msa_content, sequence] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/multiple-environments/af2/fold/run.py* * A dedicated image (`fold_image`) is built using the `FOLD_PACKAGES` dependency list, on top of the standard base image. * A dedicated environment (`fold_env`) is defined for the task, using `fold_image`. * The task is defined within the context of the `fold_env` environment. Finally, in file `main.py` we define the task `main` that ties everything together into a workflow. We import the required modules and functions: ``` import logging import pathlib from fold.run import fold_env, fold_image, run_fold from msa.run import msa_env, MSA_PACKAGES, run_msa import flyte ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/multiple-environments/af2/main.py* Notice that we import * The task functions that we will be calling: `run_fold` and `run_msa`. * The environments of those tasks: `fold_env` and `msa_env`. * The dependency list of the `run_msa` task: `MSA_PACKAGES` * The image of the `run_fold` task: `fold_image` We then assemble the image and the environment: ``` main_image = fold_image.with_pip_packages(*MSA_PACKAGES) env = flyte.TaskEnvironment( name="multi_env", depends_on=[fold_env, msa_env], image=main_image, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/multiple-environments/af2/main.py* The image for the `main` task (`main_image`) is built by starting with `fold_image` (the image for the `run_fold` task) and adding `MSA_PACKAGES` (the dependency list for the `run_msa` task). This ensures that `main_image` can import `fold/run.py` and `msa/run.py`, whatever those modules import at the top level. > **๐Ÿ“ Note** > > In this small example neither `msa/run.py` nor `fold/run.py` actually imports its packages at the top level, so a smaller `main_image` would also run. > Composing the parent image from the child images is the pattern that keeps working once those modules do import their packages at module level, and it saves you working out which ones they are. The environment for the `main` task is defined with: * The image `main_image`. This ensures that the `main` task has all the dependencies it needs. * A depends_on list that includes both `fold_env` and `msa_env`. This establishes the deploy-time dependencies on those environments. Finally, we define the `main` task itself: ``` @env.task def main(sequence: str) -> list[str]: """Given a sequence, outputs files containing the protein structure This requires model weights + gpus + large database on aws fsx lustre """ print(f"Running AlphaFold2 for sequence: {sequence}") msa = run_msa(sequence) print(f"MSA result: {msa}, passing to fold task") results = run_fold(sequence, msa) print(f"Fold results: {results}") return results ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/multiple-environments/af2/main.py* Here we call, in turn, the `run_msa` and `run_fold` tasks. Since we call them directly rather than as **Tasks > Build tasks > Remote tasks**, `main_image` has to be able to import the modules that define them. The final piece of the puzzle is the `if __name__ == "__main__":` block that allows us to run the `main` task on the configured Flyte backend: ``` if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main, "AAGGTTCCAA") print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/multiple-environments/af2/main.py* Now you can run the workflow with: ```bash python main.py ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/clustered-task-environment === Run one task across a gang of pods at once, for distributed training and similar workloads. # Clustered task environment Most tasks run in a single container. A **clustered task environment** runs a *single task* across a gang of pods at once โ€” a group of workers that start together, discover each other, and run as one distributed job. This is what you need for multi-node, multi-GPU workloads such as distributed model training, where the work is too large for one machine and every worker must participate in the same computation. A `flyte.clustered.ClusteredTaskEnvironment` is a specialized `flyte.TaskEnvironment`: it takes all the usual environment settings (image, resources, secrets, and so on) and adds a few fields that describe the shape of the cluster. When you run a task defined on one, the backend launches a Kubernetes [JobSet](https://jobset.sigs.k8s.io/) of identical pods and bootstraps [`torchrun`](https://docs.pytorch.org/docs/stable/elastic/run.html) inside them, so your task body runs once per worker process with the standard PyTorch distributed environment variables already set. ## When to use it Reach for a clustered task environment when a single task needs many machines working together: - **Distributed data-parallel training** (DDP) โ€” replicate a model across workers and average gradients each step to train faster on more data. - **Sharded training** (FSDP, tensor/pipeline parallelism) โ€” shard a model that is too large to fit on one device across many devices. - **Any multi-node PyTorch job** that expects a `torchrun` rendezvous (`RANK`, `WORLD_SIZE`, `MASTER_ADDR`, โ€ฆ) to already be set up. If your workload is a large number of *independent* tasks rather than one tightly-coupled distributed job, you do not need this โ€” use ordinary tasks with **Tasks > Build tasks > Fanout** or, for warm-container throughput, **Tasks > Configure tasks > Reusable containers** instead. ## How it works When you decorate a function with a clustered environment's `@env.task` and run it, the backend: 1. Creates a **JobSet** of `replicas` identical pods (one pod per node). 2. Starts `torchrun` in each pod with `nproc_per_node` worker processes, so the total number of workers (the "world size") is `replicas ร— nproc_per_node`. 3. Establishes the `torchrun` rendezvous across pods, populating `RANK`, `LOCAL_RANK`, `WORLD_SIZE`, `MASTER_ADDR`, and `MASTER_PORT` in every worker. 4. Runs your task body **once in every worker process**. Your code calls `torch.distributed.init_process_group()` to join the group, and the collective operations (all-reduce, all-gather, โ€ฆ) work across the whole gang. 5. Applies the `failure_policy` to decide whether to restart the JobSet on failure or node eviction, and returns the result from rank 0. Because every worker runs the same task body, you branch on the rank when you need to (for example, only rank 0 saves checkpoints or returns outputs). ## Prerequisites Clustered tasks run on the Kubernetes [JobSet](https://jobset.sigs.k8s.io/) controller, which is not part of a default installation. If a clustered run fails with `required env var 'JOBSET_NAME' is not set`, the task ran as a plain pod instead of a JobSet: the controller is missing or the `clustered-task` plugin is not enabled. - **Union-hosted and Union-managed data planes:** clustered tasks are enabled per tenant. Contact Union support to turn them on; nothing needs to be installed on your side. - **Self-managed data planes:** install the JobSet controller and enable the plugin, as for the other **Self-managed deployment > Advanced configurations > Compute plugins**: 1. Install the controller (the `jobsets.jobset.x-k8s.io` CRD and the controller in `jobset-system`): ```bash helm install jobset oci://registry.k8s.io/jobset/charts/jobset \ --version 0.12.0 -n jobset-system --create-namespace ``` 2. Add `clustered-task` to `config.enabled_plugins.tasks.task-plugins.enabled-plugins` in your data plane Helm values. The list replaces the default rather than extending it, so keep your existing plugins when you add it. ## Basic usage The example below trains a tiny model with PyTorch `DistributedDataParallel` across the cluster. First, import `flyte` and the clustered environment types: ``` from __future__ import annotations import flyte from flyte.clustered import ClusteredTaskEnvironment, ClusterFailurePolicy, TorchRun ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/ddp_train.py* Define a `flyte.clustered.ClusteredTaskEnvironment`. The image is a normal pip-based image โ€” `flyte` itself provides the runtime entrypoint that sets up the `torchrun` rendezvous, so no extra runtime library is required. The `replicas` and `nproc_per_node` fields describe the cluster shape: ``` # The torch wheel from PyPI bundles CUDA + NCCL, so the same image runs on CPU # and GPU nodes. `flyte` itself provides the `clustered` runtime entrypoint that # bootstraps torchrun inside each pod โ€” no extra runtime library is needed. image = flyte.Image.from_debian_base().with_pip_packages("torch", "numpy") resources = ( flyte.Resources(cpu=(2, 4), memory=("4Gi", "8Gi"), gpu="L4:1") if USE_GPU else flyte.Resources(cpu=(1, 2), memory=("1Gi", "2Gi")) ) env = ClusteredTaskEnvironment( name="ddp_env", image=image, resources=resources, replicas=REPLICAS, # number of pods (nodes) in the JobSet nproc_per_node=NPROC_PER_NODE, # processes (one per GPU) per pod runtime=TorchRun(rdzv_backend="static", max_restarts=0), failure_policy=ClusterFailurePolicy(max_restarts=1), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/ddp_train.py* Write the task body as if it were a single `torchrun` worker: initialize the process group, run your distributed training loop, and clean up. It executes in every worker across every pod: CODE2 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/ddp_train.py* Finally, deploy and run the workflow programmatically: CODE3 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/ddp_train.py* > [!NOTE] > The example above defaults to CPU (the `gloo` backend) so you can smoke-test it without a GPU > cluster. For real training, set `USE_GPU = True` to use the `nccl` backend and request GPUs via > `flyte.Resources(gpu=...)`. ## Configuration parameters A `flyte.clustered.ClusteredTaskEnvironment` inherits every field of a `flyte.TaskEnvironment` (`name`, `image`, `resources`, `env_vars`, `secrets`, `pod_template`, `cache`, and so on) and adds the following cluster-specific fields. For full type signatures and defaults, see `flyte.clustered.ClusteredTaskEnvironment` (API reference). | Parameter | Description | |-----------|-------------| | **`replicas`** | Number of pods (nodes) in the JobSet. Required, must be `>= 1`. | | **`nproc_per_node`** | Worker processes per pod, passed to `torchrun --nproc-per-node`. Required, must be `>= 1`. When you request GPUs, it must be `<=` the GPU count per pod (typically one process per GPU). | | **`runtime`** | Launcher configuration. Currently a `flyte.clustered.TorchRun` instance (the default). | | **`interconnect`** | Network fabric between pods. Currently only `"tcp"` is supported. | | **`failure_policy`** | JobSet-level restart policy โ€” a `flyte.clustered.ClusterFailurePolicy` (see below). | | **`ttl_seconds_after_finished`** | Optional seconds to retain the JobSet after it completes, for inspecting pods. Defaults to the backend's behavior. | The world size โ€” the total number of distributed workers โ€” is `replicas ร— nproc_per_node`. ### `TorchRun` `flyte.clustered.TorchRun` configures the `torchrun` launcher: - **`rdzv_backend`** โ€” the rendezvous backend. `"static"` (default) relies on JobSet-level restarts; `"c10d"` enables in-job elastic recovery via a TCP store on rank 0. - **`max_restarts`** โ€” in-pod `torchrun` restarts before the pod itself is considered failed. This is distinct from the JobSet-level `max_restarts` on the failure policy. ### `ClusterFailurePolicy` `flyte.clustered.ClusterFailurePolicy` controls how the JobSet as a whole recovers from failure: - **`max_restarts`** โ€” how many times the entire JobSet may restart before Flyte surfaces a failure. - **`restart_on_host_maintenance`** โ€” when `True`, node evictions (for example, spot reclamation or host maintenance) trigger a free restart that does not consume the `max_restarts` budget. ## The distributed context Inside a clustered task, `flyte.ctx()` exposes the worker's place in the cluster, so you rarely need to read the raw environment variables yourself: | Attribute | Meaning | |-----------|---------| | `ctx.rank` | Global rank of this worker across the whole world. | | `ctx.world_size` | Total number of workers (`replicas ร— nproc_per_node`). | | `ctx.local_rank` | Rank of this worker within its pod โ€” use it to pin the local GPU. | | `ctx.node_rank` | Rank of this pod among all pods. | | `ctx.nnodes` | Number of pods (nodes). | | `ctx.master_addr` | Address of the rendezvous master (rank 0). | A common pattern is to bind each worker to its local GPU *before* initializing the process group so the backend binds to the right device: CODE4 ## Checkpointing Pod-local disk is wiped when a JobSet restarts, so long-running training must persist model state to durable storage rather than the local filesystem. Use the task's checkpoint store, available at `flyte.ctx().checkpoint`, and typically write from rank 0 only. The FSDP example below shows the full pattern: gather a full state dict onto rank 0 and save it (for models small enough to gather), or have every rank write its own shard (for models too large to gather). CODE5 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/fsdp_train.py* ## Using higher-level frameworks Frameworks with their own multi-process launchers โ€” such as PyTorch Lightning โ€” also ride the `torchrun` contract. Let the clustered runtime start one process per rank and configure the framework to **attach to the existing process group** rather than spawn its own. In Lightning, that means `strategy="ddp"` (not a `*_spawn` strategy) with `devices` and `num_nodes` taken from the clustered context: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.5.18", # "torch", # "torchvision", # "lightning", # ] # main = "train_lightning" # params = "max_steps=50" # /// """ PyTorch Lightning training on a ClusteredTaskEnvironment. Lightning has its own multi-process launching machinery, but it also rides the torchrun contract: we let the clustered runtime start one process per rank and configure Lightning's `Trainer` to attach to the EXISTING process group rather than spawning its own. The key is `strategy="ddp"` (not a `*_spawn` strategy) with `devices`/`num_nodes` taken from the clustered context โ€” Lightning then reads RANK / LOCAL_RANK / WORLD_SIZE / MASTER_ADDR from the environment. """ from __future__ import annotations import flyte from flyte.clustered import ClusteredTaskEnvironment, ClusterFailurePolicy, TorchRun USE_GPU = True REPLICAS = 2 # nodes NPROC_PER_NODE = 1 # processes (GPUs) per node image = flyte.Image.from_debian_base().with_pip_packages("torch", "torchvision", "lightning") resources = ( flyte.Resources(cpu=(2, 4), memory=("4Gi", "8Gi"), gpu="L4:1") if USE_GPU else flyte.Resources(cpu=(2, 4), memory=("2Gi", "4Gi")) ) env = ClusteredTaskEnvironment( name="lightning_env", image=image, resources=resources, replicas=REPLICAS, nproc_per_node=NPROC_PER_NODE, runtime=TorchRun(rdzv_backend="static", max_restarts=0), failure_policy=ClusterFailurePolicy(max_restarts=1), ) @env.task async def train_lightning(max_steps: int = 50) -> float: """Train a tiny MNIST autoencoder with Lightning DDP over the JobSet's ranks.""" import lightning as L import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, TensorDataset ctx = flyte.ctx() print( f"[rank {ctx.rank}/{ctx.world_size}] node_rank={ctx.node_rank} " f"nnodes={ctx.nnodes} local_rank={ctx.local_rank}", flush=True, ) class AutoEncoder(L.LightningModule): def __init__(self): super().__init__() self.encoder = nn.Sequential(nn.Linear(28 * 28, 64), nn.ReLU(), nn.Linear(64, 3)) self.decoder = nn.Sequential(nn.Linear(3, 64), nn.ReLU(), nn.Linear(64, 28 * 28)) def training_step(self, batch, _): x, _y = batch x = x.view(x.size(0), -1) z = self.encoder(x) loss = F.mse_loss(self.decoder(z), x) self.log("train_loss", loss, prog_bar=True) return loss def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=1e-3) # Synthetic MNIST-shaped data so the example needs no dataset download; swap # in torchvision MNIST for the real thing. Lightning's DistributedSampler # shards this across ranks automatically. torch.manual_seed(0) images = torch.rand(512, 1, 28, 28) labels = torch.zeros(512, dtype=torch.long) loader = DataLoader(TensorDataset(images, labels), batch_size=32, shuffle=True) # Attach to the torchrun-provided process group: ddp (not ddp_spawn), with # devices per node and num_nodes from the clustered context. trainer = L.Trainer( accelerator="gpu" if USE_GPU else "cpu", devices=NPROC_PER_NODE, num_nodes=ctx.nnodes or REPLICAS, strategy="ddp", max_steps=max_steps, enable_checkpointing=False, logger=False, ) model = AutoEncoder() trainer.fit(model, loader) final_loss = float(trainer.callback_metrics.get("train_loss", torch.tensor(0.0))) print(f"[rank {ctx.rank}] done โ€” final loss {final_loss:.5f}", flush=True) return final_loss if __name__ == "__main__": flyte.init_from_config() run = flyte.run(train_lightning, max_steps=50) print("Run URL:", run.url) run.wait() print("Final phase:", run.phase) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/lightning_mnist.py* ## Constraints - **No reusable containers.** A clustered environment cannot set `reusable` โ€” the gang is created fresh for each run. Setting it raises an error. - **`nproc_per_node` must not exceed the GPU count.** When `resources.gpu` is set, `nproc_per_node` must be `<=` the number of GPUs per pod. - **`torchrun` runtime only.** The `runtime` must currently be a `flyte.clustered.TorchRun`; other launchers are not yet supported. - **TCP interconnect only.** `interconnect` currently supports only `"tcp"`. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/retries-and-timeouts === The two controls for handling failure: retry strategies and three independent timeout bounds. # Retries and timeouts Retries and timeouts are the two primary controls for handling failure on a Flyte task. Long-running tasks fail and stall in many ways: a transient network blip, a flaky third-party API, a slow scheduler, a runaway loop, a hung container. Retries decide *whether to try again*; timeouts decide *how long to wait before giving up*. Used together they keep your workflows reliable in the face of transient failures while preventing a single stuck attempt from burning resources indefinitely. Both can be configured in the `@env.task` decorator or supplied per-call with `override`. Neither can be set on the `TaskEnvironment` definition itself. ## The action lifecycle Every attempt of a task moves through a sequence of phases. Knowing the phases makes the timeout controls obvious, because each timeout bounds a specific stretch of this timeline: | Phase | What's happening | | --- | --- | | **Queued** | The action has been accepted and is waiting to be scheduled onto the cluster. | | **Waiting for resources** | Scheduled, but waiting for compute (pods, GPUs, quota) to become available. | | **Initializing** | Resources are in hand; the pod is starting (image pull, init containers, sidecars). | | **Running** | Your code is actively executing. | | **Succeeded / Failed / Timed out / Aborted** | Terminal phases. | The diagram below shows one attempt, plus a second attempt after a retry, and which control governs each part of the timeline: ```mermaid gantt title Which control covers which part of the timeline dateFormat X axisFormat %Ss section Attempt 1 Queued :q1, 0, 2 Waiting for resources :w1, 2, 5 Initializing :i1, 5, 6 Running (your code) :r1, 6, 11 section Per-attempt bounds max_queued_time :crit, 0, 6 max_runtime :active, 6, 11 section Attempt 2 (after a retry + backoff) Queued -> Running :q2, 14, 25 section Across all attempts deadline :done, 0, 27 ``` In short: - **`max_queued_time`** bounds the time spent *waiting to run* (Queued + Waiting for resources + Initializing). It resets on every attempt. - **`max_runtime`** bounds the time spent *running your code*. It resets on every attempt. - **`deadline`** bounds the *total* wall-clock from the first time the action was queued until it reaches a terminal phase: across every attempt, user retries and platform retries alike. > [!NOTE] > `max_queued_time` is enforced only on Union deployments whose control plane records when each attempt was queued. > On a deployment with an older control plane, the bound isn't applied. ## Retries A retry is a fresh attempt at executing a failed action. Each retry runs in a brand-new pod, so nothing from the failed attempt (local files, in-memory state) carries over. The code for the retry examples below can be found on [GitHub](https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/retries.py). First we import the required modules and set up a task environment: ``` from datetime import timedelta import flyte import flyte.errors env = flyte.TaskEnvironment(name="retries", resources=flyte.Resources(cpu=1, memory="250Mi")) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/retries.py* ### Retry count The simplest form passes an integer. A "retry" is any attempt after the first, so `retries=3` means up to **4 attempts** in total (1 original + 3 retries): ``` @env.task(retries=3) async def call_service() -> str: # retries=3 -> up to 4 attempts (1 original + 3 retries). # Each retry runs in a fresh pod, so nothing from the failed attempt carries over. return await fetch_from_flaky_upstream() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/retries.py* This is the right default for genuinely transient failures (a dropped connection, a brief `503` from a dependency) where simply trying again is likely to succeed. ### Retries with exponential backoff Retrying immediately is exactly the wrong thing to do against a downstream that is *already struggling*: back-to-back retries pile load onto a service that needs room to recover. A `flyte.RetryStrategy` with a `flyte.Backoff` policy inserts a growing delay between attempts so a recovering dependency gets breathing room: ``` @env.task( retries=flyte.RetryStrategy( count=5, backoff=flyte.Backoff( base=timedelta(seconds=10), # first retry waits 10s factor=2.0, # then 20s, 40s, 80s, ... cap=timedelta(minutes=5), # never wait longer than 5m between retries ), ), ) async def call_flaky_api() -> str: # The delay before the n-th retry (0-indexed) is min(base * factor**n, cap). # Backoff gives a recovering downstream room to breathe instead of hammering it. return await fetch_from_flaky_upstream() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/retries.py* The delay before the n-th retry (0-indexed) is `min(base * factor**n, cap)`. With the values above the five delays are 10s, 20s, 40s, 80s and 160s. The `cap` is what keeps an aggressive `factor` from growing into hours; it is required whenever `factor > 1`. ### Skip retries for failures that can't be fixed Some failures will never succeed no matter how many times you try: an invalid input, a malformed config, a permission that was never granted. Retrying them just wastes the budget (and the wall-clock) before the inevitable failure. Raise `flyte.errors.NonRecoverableError` to signal that a failure is terminal: the action fails on the spot, on attempt #1, with no retries consumed even when `retries` is set: ``` @env.task(retries=3) async def validate_and_process(x: int) -> str: if x < 0: # A negative input will never succeed, so don't waste the retry budget on it. # NonRecoverableError fails the action on attempt #1 โ€” no retries are consumed. raise flyte.errors.NonRecoverableError( f"Input x={x} is negative โ€” retrying will not help." ) return f"processed({x})" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/retries.py* Finally, configure Flyte and run: ``` if __name__ == "__main__": flyte.init_from_config() run = flyte.run(validate_and_process, x=-5) print(run.name) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/retries.py* ### System retries `retries=N` covers failures of *your task*: exceptions, non-zero exits, timeouts you've configured. Failures caused by the underlying infrastructure (a node disappearing, ephemeral storage running out, a spot instance getting preempted, and so on) are handled separately. The platform retries these on its own and they do not consume your `retries=N` budget. They **do**, however, count against the `deadline` (see below), because the deadline is an absolute bound on total wall-clock regardless of who triggered the retry. > [!NOTE] > Retries run the task from the beginning, so your task logic should be idempotent. > Avoid relying on local state from a previous attempt, and make any external side effects safe to repeat. The platform does eventually give up, but only after many retries: a persistent infrastructure problem can churn for a while before the run is terminated. If you spot a task repeatedly failing on the same infrastructure error, abort it manually rather than waiting for the system to give up on its own. You don't configure the system retry budget from Python; it's a platform-level concern. For workloads on spot/preemptible compute, see also **Tasks > Configure tasks > Interruptible tasks > Behavior on preemption**, which describes how preempted interruptible tasks are rescheduled. ## Timeouts A timeout is a wall-clock bound that, when exceeded, terminates the action with phase **Timed out**. Without one, a stuck attempt has no natural end: a task waiting on a hung socket or starved for a GPU that never frees up can sit there for hours. The `timeout` parameter takes a `flyte.Timeout` value carrying any combination of three independent bounds, each optional: an unspecified bound is unlimited. The code for the timeout examples below can be found on [GitHub](https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py). First, the imports and environment: ``` import asyncio from datetime import timedelta import flyte from flyte import Timeout env = flyte.TaskEnvironment(name="timeouts", resources=flyte.Resources(cpu=1, memory="250Mi")) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py* ### `max_runtime`: bound a single attempt's execution `max_runtime` caps the time an attempt spends in the **Running** phase. It's the answer to "how long should one run of this code take?" Use it to reap a hung container so a retry can take over instead of letting a wedged process run forever. It is per-attempt and resets on each retry. ``` @env.task(timeout=Timeout(max_runtime=timedelta(minutes=30))) async def train_model() -> str: # max_runtime bounds the RUNNING phase of a single attempt. If the task is # still running after 30 minutes, this attempt is reaped as TIMED_OUT. # The budget is per-attempt: it resets fresh on every retry. ... return "model trained" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py* ### `max_queued_time`: fail fast when capacity isn't available `max_queued_time` caps the time an attempt spends *waiting to run* (the **Queued**, **Waiting for resources** and **Initializing** phases) before execution begins. It answers "how long am I willing to wait for this to even start?" When a task asks for a scarce resource (a specific GPU, a large node) that the cluster can't currently supply, this bound makes it fail fast instead of stalling indefinitely. It is per-attempt and resets on each retry. > [!NOTE] > On a Union deployment whose control plane is too old to record when an attempt was queued, this bound > isn't applied and `MaxQueuedTimeExceededError` is not raised. ``` @env.task(timeout=Timeout(max_queued_time=timedelta(minutes=15))) async def needs_scarce_gpu() -> str: # max_queued_time bounds the time spent waiting to run (QUEUED + # WAITING_FOR_RESOURCES). If the cluster can't find capacity within 15 # minutes, fail fast instead of stalling indefinitely. Per-attempt. ... return "done" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py* When the budget runs out, the parent task receives `flyte.errors.MaxQueuedTimeExceededError`. Catch it to try a different GPU type instead of failing the whole run; see **Tasks > Build tasks > Error handling > Falling back when GPU capacity isn't available**. ### `deadline`: bound the total wall-clock `deadline` is the strongest of the three: an absolute budget on total wall-clock, measured from the first time the action was queued to the moment it reaches a terminal phase: across **all** attempts, including platform-driven system retries. It answers "what is the total time budget for this work, no matter what?" Use it when a downstream consumer needs a definite outcome by a certain time: with `retries=5` and `max_runtime=1h` alone, an action could legally consume six hours plus queue time before giving up. A `deadline` puts a hard ceiling on that. ``` @env.task(timeout=Timeout(deadline=timedelta(hours=2))) async def must_finish_by() -> str: # deadline is an absolute wall-clock budget across ALL attempts, measured # from the first time the action was enqueued. Once 2 hours elapse, the # action is reaped no matter which phase it is in or how many retries remain. ... return "done" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py* When the `deadline` fires mid-attempt, the action terminates immediately as **Timed out**, regardless of remaining retry budget or per-attempt timer state. ### Combining the bounds The three bounds are orthogonal and can be set together. A common shape is a per-attempt runtime cap, a queue-wait cap, and an absolute ceiling on the whole thing: ``` @env.task( timeout=Timeout( max_runtime=timedelta(minutes=30), # per attempt, RUNNING only max_queued_time=timedelta(minutes=15), # per attempt, waiting to run deadline=timedelta(hours=2), # absolute, across all attempts ), ) async def fully_bounded() -> str: ... return "done" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py* For backward compatibility, a bare `int` (seconds) or `timedelta` passed to `timeout` is interpreted as `max_runtime`: ``` # A bare int (seconds) or timedelta is shorthand for Timeout(max_runtime=...). @env.task(timeout=timedelta(minutes=30)) async def runtime_only() -> str: ... return "done" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py* ## Combining retries and timeouts Retries and timeouts compose, and the per-attempt versus absolute distinction is what makes the combination expressive. Because `max_runtime` and `max_queued_time` are per-attempt, they retry normally: each timed-out attempt counts as a failure and the next attempt gets a fresh budget. Because `deadline` is absolute, it overrides retries entirely: once it fires, no further attempts run. | Timeout | With `retries` set | Without `retries` | | --- | --- | --- | | `max_runtime` | Each attempt is reaped at the budget and retried until retries are exhausted. | First timeout is final. | | `max_queued_time` | Each attempt is reaped pre-Running and retried until retries are exhausted. | First timeout is final. | | `deadline` | Retries continue until the budget is exhausted **or** the deadline fires, whichever comes first. | Action terminates at the deadline. | The most useful pattern combines backoff-paced retries with an absolute deadline: keep retrying a flaky dependency, but never spend more than a fixed total budget on it. ``` @env.task( retries=flyte.RetryStrategy( count=5, backoff=flyte.Backoff(base=timedelta(seconds=30), factor=2.0, cap=timedelta(minutes=5)), ), timeout=Timeout( max_runtime=timedelta(minutes=10), # cap any single attempt deadline=timedelta(hours=1), # but never spend more than 1h total ), ) async def resilient_work() -> str: # Retries continue until either the retry budget is exhausted OR the 1h # deadline fires โ€” whichever comes first. The deadline wins ties. ... return "done" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py* Finally, configure Flyte and run: ``` if __name__ == "__main__": flyte.init_from_config() run = flyte.run(fully_bounded) print(run.name) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/retries-and-timeouts/timeouts.py* Together, these controls let your workflows absorb transient failures gracefully while guaranteeing that broken or starved work is reaped on a schedule you choose rather than left to run unbounded. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/interruptible-tasks-and-queues === Run tasks on discounted spot instances that can be reclaimed at any time. # Interruptible tasks Cloud providers offer discounted compute instances (AWS Spot Instances, GCP Preemptible VMs) that can be reclaimed at any time. These instances are significantly cheaper than on-demand instances but come with the risk of preemption. Setting `interruptible=True` allows Flyte to schedule the task on these spot/preemptible instances for cost savings: ```python import flyte env = flyte.TaskEnvironment( name="my_env", interruptible=True, ) @env.task def train_model(data: list[float]) -> dict: return {"accuracy": 0.95} ``` ## Setting at different levels `interruptible` can be set at the `TaskEnvironment` level, the `@env.task` decorator level, and at the `task.override()` invocation level. The more specific level always takes precedence. This lets you set a default at the environment level and override per-task: ```python import flyte # All tasks in this environment are interruptible by default env = flyte.TaskEnvironment( name="my_env", interruptible=True, ) # This task uses the environment default (interruptible) @env.task def preprocess(data: list[int]) -> list[int]: return [x * 2 for x in data] # This task overrides to non-interruptible (critical, should not be preempted) @env.task(interruptible=False) def save_results(results: dict) -> str: return "saved" ``` You can also override at invocation time. From an `async` parent, call a sync task with `.aio()`: ```python @env.task async def main(data: list[int]) -> str: processed = await preprocess.aio(data=data) # Run this specific invocation as non-interruptible return await save_results.override(interruptible=False).aio(results={"data": processed}) ``` ## Behavior on preemption When a spot instance is reclaimed, the running task is terminated and automatically rescheduled. Preemptions are retried on a separate, platform-managed budget, so they do **not** consume the task's configured **Tasks > Configure tasks > Retries and timeouts** โ€” you don't need to set `retries` for an interruptible task to be resilient to preemption. `retries` instead governs re-attempts after your own task code fails (for example, an unhandled exception or a timeout), and behaves the same for interruptible and non-interruptible tasks: ```python @env.task(interruptible=True, retries=3) def train_model(data: list[float]) -> dict: return {"accuracy": 0.95} ``` > [!NOTE] > Retries due to spot preemption do not count against the user-configured retry budget. > System retries (for preemptions and other system-level failures) are tracked separately. ## Fall back to on-demand when spot capacity is unavailable Preemption and unavailability are different failures. A preempted task is rescheduled for you. A task whose spot pool has no capacity can sit in the **Queued** or **Waiting for resources** phase until capacity appears. Bound that wait with **Tasks > Configure tasks > Retries and timeouts > Timeouts > `max_queued_time`: fail fast when capacity isn't available**. When it fires, the parent receives `flyte.errors.MaxQueuedTimeExceededError`. Catch it and re-run the task on on-demand compute with `interruptible=False`: ```python from datetime import timedelta import flyte import flyte.errors env = flyte.TaskEnvironment( name="my_env", interruptible=True, ) @env.task(timeout=flyte.Timeout(max_queued_time=timedelta(minutes=10))) async def train_model(data: list[float]) -> dict: return {"accuracy": 0.95} # The parent runs on-demand, so it can start and catch the timeout even with no spot capacity @env.task(interruptible=False) async def main(data: list[float]) -> dict: try: # Spot, abandoned if nothing is scheduled within 10 minutes return await train_model(data=data) except flyte.errors.MaxQueuedTimeExceededError: # On-demand, with no queue bound return await train_model.override(interruptible=False, timeout=flyte.Timeout())(data=data) ``` - **Run the parent on-demand.** A parent in the interruptible environment needs spot capacity too. With none available, it never starts and never reaches the fallback. - **Clear the queue bound on the fallback.** `override()` keeps the task's `timeout` unless you pass a new one, so without `timeout=flyte.Timeout()` the on-demand attempt also fails after 10 minutes in the queue. `timeout=0` does not clear it. - **Account for retries.** `max_queued_time` applies to each attempt, so with `retries=3` the parent sees the error after about 40 minutes, not 10. See **Tasks > Configure tasks > Retries and timeouts > Combining retries and timeouts**. See **Tasks > Build tasks > Error handling > Falling back when GPU capacity isn't available** for the same pattern with scarce GPUs. > [!NOTE] > Looking for scheduling control: concurrency limits, depth, priority, or routing > work to a specific cluster? See **Tasks > Configure tasks > Queues**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/queues === Named scheduling lanes that route and rate-limit work instead of letting everything compete. # Queues A **queue** is a named scheduling lane for your work. Instead of every run and action competing for whatever capacity happens to be free, a queue gives the platform a place to apply policy: how many things run at once, how deep the backlog can get, how this work is prioritized relative to everyone else's, and which cluster it lands on. Targeting a queue is a single parameter: you don't change your task code, you just say *where* it should be scheduled. Anything you don't explicitly route goes to the **default queue**. ## Routing work to a queue The `queue` parameter can be set at three levels: on the `flyte.TaskEnvironment`, on the `@env.task` decorator, and at invocation time via `task.override()`. The more specific level always wins, exactly like the other task settings. ```python import flyte # Default every task in this environment to a queue... env = flyte.TaskEnvironment( name="my_env", queue="default-pool", ) # ...inherit the environment default... @env.task def preprocess(data: list) -> list: return [x * 2 for x in data] # ...or override per task. @env.task(queue="gpu-pool") def train_model(data: list) -> dict: return {"accuracy": 0.95} ``` A common pattern is to leave the entry-point task on the default routing and pin only the child steps that need capping to a queue, so the run as a whole goes through the default pool and only the targeted workload is constrained. ### Per-run and per-trigger routing You can also choose a queue when you launch a run, without touching the task definition: ```python flyte.with_runcontext(queue="my-queue").run(main, count=10) ``` And a [trigger](../../triggers/_index) can send its scheduled runs to a specific queue, useful when you want scheduled or automated work to run under different limits than ad-hoc runs: ```python import flyte trigger = flyte.Trigger( "nightly", flyte.Cron("0 2 * * *"), queue="batch", ) ``` ### Overriding a queue at runtime A running workflow can route a specific task invocation to a different queue, for example to push one heavy step onto a dedicated lane: ```python @env.task async def main(queue_name: str): # Route this invocation of train_model to a queue chosen at runtime. train_model.override(queue=queue_name)(data=[1, 2, 3]) ``` ## What a queue controls Queues are configured by your platform admin (see **Clusters and queues > Managing queues** for how they are created and managed), but it helps to understand the knobs so you can pick the right queue for a workload: - **Action concurrency**: the maximum number of tasks routed to the queue that run at the same time. A queue with a cap of 1 serializes its work; a cap of 3 lets at most three run concurrently and holds the rest until a slot frees up. - **Run concurrency**: the maximum number of *runs* on the queue that are active at once. Children of an active run aren't capped by this; only the runs themselves are. Use this for a job that parallelizes well internally but must not overlap with a previous invocation of itself. - **Depth**: the total number of in-flight plus waiting items the queue will hold. When a queue is full, new submissions are rejected immediately with a `RESOURCE_EXHAUSTED` error rather than queueing forever. That rejection is a back-pressure signal to your caller: catch it and slow down, rather than retrying in a tight loop. - **Priority**: when several queues share the same cluster capacity, higher priority work is scheduled ahead of lower priority work. Priority controls *ordering*, not preemption: a lower-priority task that has already started is not interrupted when higher-priority work arrives. - **Resource caps**: the most CPU, memory, and GPUs that the queue's scheduled tasks may request at once, counted across every cluster the queue routes to. GPUs can be capped per device type, and separately for tasks that ask for a GPU without naming a type. A task that would push the queue past a cap waits until enough running work finishes. - **Scheduling policy**: what the queue does when the next task in line does not fit. A `strict_fifo` queue waits for it, so nothing behind it starts first. A `greedy_capacity` queue skips it and starts the tasks behind it that do fit. Resource caps and scheduling policies are described in **Clusters and queues > Resource caps and scheduling**. ## When to use queues ### Concurrency control for scheduled and automated runs A run that updates a shared checkpoint or mutates global state must not overlap with itself. Route it to a queue with **run concurrency of 1**: even if a schedule fires again before the previous run finishes, the new run waits instead of running concurrently. Inside each run, children still fan out freely. ```python @env.task(queue="runs-1") # run-concurrency 1 async def nightly_job(fan_out: int = 50) -> list[str]: # Hundreds of children can run in parallel within this run... return list(flyte.map(child, range(fan_out))) # ...but two nightly_job runs never overlap. ``` This pairs naturally with [triggers](../../triggers/_index): give the trigger a serialized queue and you get self-non-overlapping scheduled jobs for free. ### Backfill control A backfill can produce thousands of actions in a burst and starve everything else sharing the cluster. Send the backfill to a queue with a bounded **action concurrency** (and optionally a **depth** limit) so it drains at a controlled rate while leaving headroom for production traffic. The depth limit turns a flood into explicit back-pressure: when the queue is full your submitter gets `RESOURCE_EXHAUSTED` and can pause instead of piling on. ### Multi-cluster routing and prioritizing certain workloads Because a queue can be bound to a specific cluster (or set of clusters) and given a priority, queues are how you say "GPU training goes to the GPU cluster" or "this customer-facing pipeline is high priority." Route latency-sensitive or business-critical work to a high-priority queue and bulk or best-effort work to a lower-priority one; when they contend for the same capacity, the important work is scheduled first. ### Sharing clusters across teams When several teams run on the same clusters, one team's large job can take all of the GPUs and leave everyone else waiting. Give each team a queue with **resource caps** and each team gets a ceiling on the CPU, memory, and GPUs its scheduled work can use at once. Work beyond the ceiling is still accepted and waits in the queue. Because the caps count resources, a team can run many small tasks or a few large ones under the same cap. Which queue you pick also decides how your work waits. On a `greedy_capacity` queue, small tasks and tasks for a **Tasks > Configure tasks > Reusable containers** that is already running keep starting while a large task waits for room. On a `strict_fifo` queue, tasks start strictly in the order they were submitted, which suits a job that needs many GPUs at the same moment and must not be overtaken by smaller work. ## Requests that can never run A task can ask for more than its queue allows, for example 64 CPUs on a queue capped at 32. Waiting would not help, so the action fails right away with the error code `INFEASIBLE` and is not retried. The error message names the request and the cap. Lower the task's `resources`, or route it to a queue with a higher cap. With resource-aware scheduling, the check also covers the clusters behind a queue: a task that asks for an accelerator none of the queue's clusters has, for a container larger than any of their nodes, or that is interruptible when none of them has a spot node pool it fits, fails the same way. See **Clusters and queues > Resource caps and scheduling > Infeasible requests fail fast**. ## Queues and timeouts How long a task is willing to *wait* in a queue before it gives up is a separate, per-task concern controlled by the timeout settings. If a queue is busy or capped, an action sits in the **Queued** phase until a slot opens: set **Tasks > Configure tasks > Retries and timeouts > Timeouts > `max_queued_time`: fail fast when capacity isn't available** to fail fast when capacity isn't available within your window, and **Tasks > Configure tasks > Retries and timeouts > Timeouts > `deadline`: bound the total wall-clock** to put an absolute ceiling on total wall-clock including queue wait. See **Tasks > Configure tasks > Retries and timeouts** for the full picture. When `max_queued_time` fires, the parent task receives `flyte.errors.MaxQueuedTimeExceededError`. Catching it and re-running the task with `override(queue=..., resources=...)` lets a workflow fall back to another queue that has a different GPU available; see **Tasks > Build tasks > Error handling > Routing each option to a different queue**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/task-plugins === Extend task execution beyond plain containers to specialized compute frameworks. # Task plugins Flyte tasks are pluggable by design, allowing you to extend task execution beyond simple containers to support specialized compute frameworks and integrations. ## Default execution: containers By default, Flyte tasks execute as single containers in Kubernetes. When you decorate a function with `@env.task`, Flyte packages your code into a container and runs it on the cluster. For more advanced scenarios requiring multiple containers in a single pod (such as sidecars for logging or data mounting), you can use **Tasks > Configure tasks > Pod templates**, which allow you to customize the entire Kubernetes pod specification. ## Compute plugins Beyond native container execution, Flyte provides **compute plugins** that enable you to run distributed computing frameworks directly on Kubernetes. These plugins create ephemeral clusters specifically for your task execution, spinning them up on-demand and tearing them down when complete. ### Available compute plugins Flyte supports several popular distributed computing frameworks through compute plugins: - **Spark**: Run Apache Spark jobs using the Spark operator - **Ray**: Execute Ray workloads for distributed Python applications and ML training - **Dask**: Scale Python workflows with Dask distributed - **PyTorch**: Run distributed training jobs using PyTorch and Kubeflow's training operator ### How compute plugins work Compute plugins create temporary, isolated clusters within the same Kubernetes environment as Flyte: 1. **Ephemeral clusters**: Each task execution gets its own cluster, spun up on-demand 2. **Kubernetes operators**: Flyte uses specialized Kubernetes operators (Spark operator, Ray operator, etc.) to manage cluster lifecycle 3. **Native containerization**: The same container image system used for regular tasks works with compute plugins 4. **Per-environment configuration**: You can define the cluster shape (number of workers, resources, etc.) using `plugin_config` in your `TaskEnvironment` ### Using compute plugins To use a compute plugin, you need to: 1. **Install the plugin package**: Each plugin has a corresponding Python package (e.g., `flyteplugins-ray` for Ray) 2. **Configure the TaskEnvironment**: Set the `plugin_config` parameter with the plugin-specific configuration 3. **Write your task**: Use the framework's native APIs within your task function #### Example: Ray plugin Here's how to run a distributed Ray task: ```python import ray from flyteplugins.ray.task import HeadNodeConfig, RayJobConfig, WorkerNodeConfig import flyte # Define your Ray computation @ray.remote def compute_square(x): return x * x # Configure the Ray cluster ray_config = RayJobConfig( head_node_config=HeadNodeConfig(ray_start_params={"log-color": "True"}), worker_node_config=[WorkerNodeConfig(group_name="ray-workers", replicas=2)], runtime_env={"pip": ["numpy", "pandas"]}, enable_autoscaling=False, shutdown_after_job_finishes=True, ttl_seconds_after_finished=300, ) # Create a task environment with Ray plugin configuration image = ( flyte.Image.from_debian_base(name="ray") .with_pip_packages("ray[default]==2.46.0", "flyteplugins-ray") ) ray_env = flyte.TaskEnvironment( name="ray_env", plugin_config=ray_config, image=image, resources=flyte.Resources(cpu=(3, 4), memory=("3000Mi", "5000Mi")), ) # Use the Ray cluster in your task @ray_env.task async def distributed_compute(n: int = 10) -> list[int]: futures = [compute_square.remote(i) for i in range(n)] return ray.get(futures) ``` When this task runs, Flyte will: 1. Spin up a Ray cluster with 1 head node and 2 worker nodes 2. Execute your task code in the Ray cluster 3. Tear down the cluster after completion ### Using plugins on Union Most compute plugins are enabled by default on Union or can be enabled upon request. Contact your Account Manager to confirm plugin availability or request specific plugins for your deployment. ## Backend integrations Beyond compute plugins, Flyte also supports **integrations** with external SaaS services and internal systems through **connectors**. These allow you to interact with: - **Data warehouses**: Snowflake, BigQuery, Redshift - **Data platforms**: Databricks - **Custom services**: Your internal APIs and services Connectors enable Flyte to delegate task execution to these external systems while maintaining Flyte's orchestration, observability, and data lineage capabilities. See the [connectors documentation](../../../integrations/_index) for more details on available integrations. ## Next steps For detailed guides on each compute plugin, including configuration options, best practices, and advanced examples, see the [Plugins section](../../../integrations/_index) of the documentation. Each plugin guide covers: - Installation and setup - Configuration options - Resource management - Advanced use cases - Troubleshooting tips === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/additional-task-settings === Naming, metadata, default inputs, and environment variables, and the settings without their own page. # Additional task settings This page covers task configuration parameters that do not have their own dedicated page: naming and metadata, default inputs, environment variables, and inline I/O thresholds. For the full list of all task configuration parameters, see [Configure tasks](./_index). ## Naming and metadata ### `name` The `name` parameter on `TaskEnvironment` is required. It is combined with each task function name to form the fully-qualified task name. For example, if you define a `TaskEnvironment` with `name="my_env"` and a task function `my_task`, the fully-qualified task name is `my_env.my_task`. The `name` must use `snake_case` or `kebab-case` and is immutable once set. ### `short_name` The `short_name` parameter on `@env.task` (and `override()`) overrides the display name of a task in the UI graph view. By default, the display name is the Python function name. Overriding `short_name` does not change the fully-qualified task name. ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task(short_name="Train Model") def train(data: list) -> dict: return {"accuracy": 0.95} ``` ### `prefix` The `prefix` parameter on `@env.task` prefixes the function name, so the fully-qualified task name becomes `.-`. The display name becomes `-`, which is `-` when `short_name` isn't set. Use it when functions with the same name in different modules share one `TaskEnvironment`. Requires `flyte` 2.12.2 or later. A prefix is letters, digits and underscores, separated by `-` (for example `myproject-train`); it cannot contain `.`. Use a fixed string rather than `__name__`, which differs between `flyte run` and the task container. ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task(prefix="train") def validate_inputs(data: list) -> list: # my_env.train-validate_inputs return data ``` > [!NOTE] > Adding or changing the prefix renames the task: existing cache entries no longer apply, and earlier runs stay under the old name. ### `description` The `description` parameter on `TaskEnvironment` provides a description of the task environment (max 255 characters). It is used for organizational purposes and can be viewed in the UI. ### `docs` A task's description, shown in the UI, comes from the task function's docstring: ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task def train(data: list) -> dict: """Trains a model on the given dataset.""" return {"accuracy": 0.95} ``` > [!NOTE] > `@env.task` also accepts a `docs` parameter. In the current SDK it sets only the help text that > `flyte run` shows for the task; it does not change the description shown in the UI. Use the docstring. ### `report` The `report` parameter on `@env.task` controls whether an HTML report is generated for the task. See **Tasks > Build tasks > Reports** for details. ### Source-code link (automatic) In addition to the description and docs above, Flyte automatically attaches a link from each deployed task back to its source code on GitHub or GitLab, when you deploy from inside a checked-out git repository. The link is rendered next to the task description in the UI. There is no parameter to set. See **Tasks > Run and deploy tasks > How task deployment works > 6. Source-code link discovery** for the conditions and caveats. ### `links` The `links` parameter on `@env.task` (and `override()`) attaches clickable URLs to tasks in the UI. Use links to connect tasks to external tools like experiment trackers, monitoring dashboards, or logging systems. Links are defined by implementing the **Flyte SDK > flyte > Link** protocol. See **Tasks > Build tasks > Links** for full details on creating and using links. ## Default inputs Task functions support Python default parameter values. When a task parameter has a default, callers can omit it and the default is used. ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task async def process(data: list[int], batch_size: int = 32, verbose: bool = False) -> dict: # batch_size defaults to 32, verbose defaults to False ... ``` When running via `flyte run`, parameters with defaults are optional: ```bash # Uses defaults for batch_size and verbose flyte run my_file.py process --data '[1, 2, 3]' # Override a default flyte run my_file.py process --data '[1, 2, 3]' --batch_size 64 ``` When invoking programmatically, Python's normal default argument rules apply: ```python result = flyte.run(process, data=[1, 2, 3]) # batch_size=32, verbose=False result = flyte.run(process, data=[1, 2, 3], batch_size=64) # override ``` Defaults are part of the task's input schema and are visible in the UI when viewing the task. ## Environment variables The `env_vars` parameter on `TaskEnvironment` injects plain-text environment variables into the task container. It accepts a `Dict[str, str]`. ```python import flyte env = flyte.TaskEnvironment( name="my_env", env_vars={ "LOG_LEVEL": "DEBUG", "API_ENDPOINT": "https://api.example.com", }, ) @env.task def my_task() -> str: import os return os.environ["API_ENDPOINT"] ``` Environment variables can be overridden at the `task.override()` invocation level (unless `reusable` is in effect). Use `env_vars` for non-sensitive configuration values. For sensitive values like API keys and credentials, use **Tasks > Configure tasks > Secrets** instead. ## Inline I/O threshold The `max_inline_io_bytes` parameter on `@env.task` (and `override()`) controls the maximum size for data passed directly in the task request and response (e.g., primitives, strings, dictionaries). When one task calls another in a remote run, data exceeding this threshold raises an `InlineIOMaxBytesBreached` error (see **Tasks > Configure tasks > Additional task settings > Where the limit is checked**). The default value is 10 MiB (`10 * 1024 * 1024` bytes). `TaskEnvironment` does not accept `max_inline_io_bytes`; set it on `@env.task` or `override()`. This setting does **not** affect **Tasks > Build tasks > Files and directories**, or **Tasks > Build tasks > DataFrames**, which are always offloaded to object storage regardless of size. ```python import flyte env = flyte.TaskEnvironment(name="my_env") # Allow up to 50 MiB of inline data @env.task(max_inline_io_bytes=50 * 1024 * 1024) def process_large_dict(data: dict) -> dict: return {k: v * 2 for k, v in data.items()} ``` To change the limit for a single call, use `override()`: ```python result = process_large_dict.override(max_inline_io_bytes=100 * 1024 * 1024)(data) ``` ### Where the limit is checked The limit applies to calls between tasks, and the calling task checks it against the limit of the task it calls: - **Inputs** are checked before the call is submitted. With the default limit, the error reads `Inputs exceed max_bytes limit of 10.0 MB, actual size: MB`. - **Outputs** are checked when the calling task reads them back. The called task runs to completion and writes its output first, so the called action succeeds and the calling task fails. With the default limit, the error reads `Output file at exceeds max_bytes limit of 10485760`. The SDK does not check a top-level run's own inputs and outputs. Local runs do not enforce the limit. A value that passes in a local run can still raise `InlineIOMaxBytesBreached` when the same tasks run remotely. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/logging === The two loggers Flyte uses, and how to set each level independently. # Logging Flyte uses two separate loggers, each with its own level: - The **framework logger** (`flyte`): Flyte's own internal messages. Lines are prefixed with `[flyte]`. Defaults to `WARNING`. - The **user logger** (`flyte.user`): the logger you get from `flyte.logger`, for your own application messages. Defaults to `INFO`. Splitting the two lets you turn up Flyte's internal logging for debugging without flooding your output with framework noise during normal use, and vice versa. ## Set the logging level with environment variables The quickest way to set the level is via environment variables. They apply to both local and remote runs. | Variable | Controls | Default | |----------|----------|---------| | `LOG_LEVEL` | The framework logger (`flyte`) | `WARNING` | | `USER_LOG_LEVEL` | The user logger (`flyte.user`) | `INFO` | | `LOG_FORMAT` | Output format: `console` or `json` | `console` | | `DISABLE_RICH_LOGGING` | If set (to any value), disables the Rich-formatted console handler | *unset* | | `FLYTE_RESET_ROOT_LOGGER` | If set to `1`, resets the root logger so third-party library logs are captured as JSON too (see **Tasks > Configure tasks > Logging > JSON logging and third-party libraries**) | *unset* | For example, to see Flyte's internal debug messages: ```bash LOG_LEVEL=debug flyte run --local my_workflow.py main ``` `LOG_LEVEL` accepts either a **named level** (`critical`, `error`, `warning` or `warn`, `info`, `debug`, case-insensitive) or a **numeric** Python logging level, such as `10` (`DEBUG`) or `20` (`INFO`): ```bash LOG_LEVEL=10 USER_LOG_LEVEL=debug flyte run --local my_workflow.py main ``` An unrecognized `LOG_LEVEL` falls back to `WARNING`. With the `flyte` CLI, `USER_LOG_LEVEL` is read as the value of the `--user-log-level` option, so it accepts only `debug`, `info`, `warning`, `error` or `critical` (case-insensitive). Any other value, including `warn` or a number, makes the command exit with an `Invalid value for '--user-log-level'` error. Without the CLI, such as when you call `flyte.init()` from your own script, `USER_LOG_LEVEL` accepts the same values as `LOG_LEVEL`, and an unrecognized value falls back to `INFO`. ## Set the framework verbosity from the CLI The `flyte` CLI's `-v` flag is a shorthand for the **framework** log level (the `flyte` logger). It's a global option, so it goes *before* the subcommand, and repeating it raises the verbosity: | Flag | Framework level | |------|-----------------| | *(none)* | `LOG_LEVEL` env var, else `WARNING` | | `-v` | `WARNING` | | `-vv` | `INFO` | | `-vvv` | `DEBUG` | ```bash flyte -vvv run --local my_workflow.py main ``` `-v` controls only the framework logger; it does **not** change your task (user) log level. Set that separately with `--user-log-level` (also a global option, so likewise before the subcommand), or the `USER_LOG_LEVEL` environment variable: ```bash flyte --user-log-level debug run --local my_workflow.py main ``` ## Set the logging level with `flyte.init()` You can also set logging when you initialize the SDK. The `log_level` and `user_log_level` parameters take numeric Python logging levels: ```python import logging import flyte flyte.init( log_level=logging.DEBUG, # framework logger user_log_level=logging.INFO, # user logger log_format="console", # or "json" ) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `log_level` | `int` | `LOG_LEVEL` env var, else `WARNING` | Level for the framework logger (`flyte`). | | `user_log_level` | `int` | `USER_LOG_LEVEL` env var, else `INFO` | Level for the user logger (`flyte.user`). | | `log_format` | `"console"` \| `"json"` | `LOG_FORMAT` env var, else `"console"` | Output format. | | `reset_root_logger` | `bool` | `False` | When `True`, Flyte clears the root logger's existing handlers and installs its own, set to the framework `log_level`: third-party log lines below that level aren't shown. With `flyte` 2.12.5 or later, Python warnings are also routed through Flyte's root handler and filtered the same way, so with `log_level` above `WARNING` they aren't shown. When `False` (the default), Flyte leaves your existing root handlers in place and wraps their formatters so third-party log lines also carry the run/action context. | > [!NOTE] > Explicit `flyte.init()` arguments take precedence over the environment variables, except `reset_root_logger`: if `FLYTE_RESET_ROOT_LOGGER` is `1`, the root logger is reset even when you pass `reset_root_logger=False`. An argument left unset falls back to the corresponding environment variable, then to the built-in default. ## Write to the user logger Use `flyte.logger` for your own application messages so they render with the same run/action context as Flyte's output: ```python import flyte flyte.logger.info("Processing %d records", len(records)) flyte.logger.debug("Intermediate value: %r", value) ``` ## JSON logging and third-party libraries Setting `LOG_FORMAT=json` (or `log_format="json"`) switches Flyte's output to JSON โ€” but only for the two Flyte loggers, `flyte` and `flyte.user`. Both have propagation disabled, so neither reaches the Python **root logger**. Third-party libraries (`urllib3`, `boto3`, your own dependencies) typically emit through the root logger, so their lines are not converted to JSON: your Flyte output is JSON, but library log lines stay plain text. This matters when you ship logs to a cloud logging backend โ€” Google Cloud Logging (Stackdriver), AWS CloudWatch, Datadog โ€” that expects one consistent JSON format across every line. To make third-party lines JSON as well, also set `reset_root_logger=True`. Flyte then clears the root logger's existing handlers and attaches a JSON handler at the root, so every library that propagates to the root logger is captured as JSON. With `flyte` 2.12.5 or later, Flyte also routes Python warnings (`warnings.warn()`) through that handler, as `WARNING` records from the `py.warnings` logger, instead of leaving them as plain text on stderr: ```python import flyte flyte.with_runcontext( log_format="json", reset_root_logger=True, ).run(main) ``` By default (`reset_root_logger=False`), Flyte does **not** clear the root logger; it only wraps your existing root handlers so their lines carry the run/action context. The root reset is what makes third-party output uniform JSON. `flyte.with_runcontext()` applies the reset only in the remote task. To reset the root logger in your local process as well, pass `reset_root_logger=True` to `flyte.init()`, or use the `flyte` CLI's global `--reset-root-logger` flag. ### Set it at registration with `FLYTE_RESET_ROOT_LOGGER` Passing `reset_root_logger=True` to `flyte.with_runcontext()` automatically injects `FLYTE_RESET_ROOT_LOGGER=1` into the task container, so the reset happens in the remote task. To configure it on the task environment instead โ€” resetting the root logger for every run, at registration time rather than per-run โ€” set the environment variable directly. The value must be the string `1`: ```python import flyte env = flyte.TaskEnvironment( name="my_env", env_vars={ "LOG_FORMAT": "json", "FLYTE_RESET_ROOT_LOGGER": "1", }, ) ``` ## Related The same logging parameters can be set per-run via `flyte.with_runcontext()`. See the **Tasks > Run and deploy tasks > Run context > Configuring a run with `flyte.with_runcontext()` > Logging** in the run context reference. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-configuration/overrides === Change a task's configuration at invocation time rather than where it is defined. # Overrides Most task configuration is set when you define a task: on the `TaskEnvironment` or in the `@env.task` decorator. But you often need to change some of that configuration for a **single invocation** of a task: give one call more memory, point it at a different secret, or bump its retries. The `task.override()` method does exactly this. It returns a **new task** with the specified parameters changed, leaving the original task definition untouched, so you can invoke the overridden task in place of the original: ```python import flyte env = flyte.TaskEnvironment( name="training", resources=flyte.Resources(cpu=1, memory="512Mi"), ) @env.task async def train(data: str) -> str: return f"trained on {data}" @env.task async def main() -> str: # Invoke train with its environment-level resources. baseline = await train("small.csv") # Invoke train with overridden resources for this call only. heavy = await train.override( resources=flyte.Resources(cpu="4", memory="24Gi"), )("large.csv") return heavy ``` The key idiom is `task.override(...)(args)`: `override()` returns a callable task, which you then invoke with the task's arguments. Note the two sets of parentheses. ## What you can override `override()` accepts the parameters that are settable at the task-invocation level: | Parameter | Details | |-----------|---------| | **short_name** | **Tasks > Configure tasks > Additional task settings** | | **resources** | **Tasks > Configure tasks > Resources** • **Flyte SDK > flyte > Resources** | | **cache** | **Tasks > Configure tasks > Caching** • **Flyte SDK > flyte > Cache** | | **retries** | **Tasks > Configure tasks > Retries and timeouts** • **Flyte SDK > flyte > RetryStrategy** | | **timeout** | **Tasks > Configure tasks > Retries and timeouts** • **Flyte SDK > flyte > Timeout** | | **reusable** | **Tasks > Configure tasks > Reusable containers** • **Flyte SDK > flyte > ReusePolicy** | | **env_vars** | **Tasks > Configure tasks > Additional task settings > Environment variables** | | **secrets** | **Tasks > Configure tasks > Overrides > Overriding secrets** • **Tasks > Configure tasks > Secrets** • **Flyte SDK > flyte > Secret** | | **max_inline_io_bytes** | **Tasks > Configure tasks > Additional task settings > Inline I/O threshold** | | **pod_template** | **Tasks > Configure tasks > Pod templates** • **Flyte SDK > flyte > PodTemplate** | | **queue** | **Tasks > Configure tasks > Queues** | | **interruptible** | **Tasks > Configure tasks > Interruptible tasks** | | **links** | **Tasks > Configure tasks > Additional task settings > Naming and metadata > `links`** | For the full parameter interaction matrix showing which parameters can be set at which level, see [Task configuration levels](./_index#task-configuration-levels). > [!NOTE] Overrides replace, they don't merge > When you override a collection-valued parameter such as `resources`, `env_vars`, or `secrets`, the value you pass **replaces** the environment's value for that invocation. It is not merged with it. > To keep some of the original entries, include them in the override. ## What you cannot override `name`, `image`, `docs`, and the task's interface (its input and output types) **cannot** be overridden. Attempting to override them raises an error. To run a task with a different image, define it in a separate `TaskEnvironment` (see **Tasks > Configure tasks > Container images** and **Tasks > Configure tasks > Multiple environments**). ## Overriding when a task is reusable When a task uses a **Tasks > Configure tasks > Reusable containers** (`reusable` is set), its `resources`, `env_vars`, and `secrets` come from the parent environment and **cannot** be overridden while reuse is active. The container is already running. To override any of these on a reusable task, turn reuse off in the same `override()` call by passing `reusable="off"`: ```python result = await my_task.override( reusable="off", resources=flyte.Resources(cpu="4", memory="8Gi"), )(data) ``` ## Overriding secrets Just as you can override resources per invocation, you can override the **Tasks > Configure tasks > Secrets** injected into a task for a single call. This is useful when the same task needs different credentials depending on how it's invoked: for example, calling an external API with a different key per tenant, or supplying a secret that the task's environment doesn't declare. Pass `secrets` to `override()` exactly as you would to the `TaskEnvironment`: a secret key, a `Secret` object, or a list of either. ```python import flyte from flyte import Secret env = flyte.TaskEnvironment( name="model_calls", secrets=Secret("openai-key", as_env_var="LLM_API_KEY"), ) @env.task async def call_model(prompt: str) -> str: import os api_key = os.environ["LLM_API_KEY"] ... # call the model using api_key return "response" @env.task async def main() -> str: # Use the environment's default secret. default = await call_model("hello") # Override the secret for this invocation, mounting a different # store key into the same LLM_API_KEY environment variable. alternate = await call_model.override( secrets=Secret("anthropic-key", as_env_var="LLM_API_KEY"), )("hello") return alternate ``` > [!NOTE] > If the task's environment uses **reusable containers** (`reusable` is set), overriding `secrets`, like `resources` and `env_vars`, requires passing `reusable="off"` in the **same** `override()` call. Otherwise the override is rejected. As with the environment-level `secrets` parameter, the secret is injected at runtime and accessed inside the task: typically as an environment variable via `os.environ` (or mounted as a file). See **Tasks > Configure tasks > Secrets** for how to create secrets and how they are injected, and remember that the overriding `secrets` value **replaces** the environment's secrets for that invocation rather than adding to them. > [!NOTE] > A task can only access a secret if the secret's scope includes the project and domain where the task's `TaskEnvironment` is deployed. Overriding the secret at invocation time does not change this. > [!WARNING] > Do not return secret values from tasks. Returned values are stored in plaintext in your data plane's object store and shown in the UI and to downstream tasks, defeating the secret store's protections. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming === Compose tasks with fanout, parallelism, error handling, traces, files, and DataFrames. # Build tasks This section covers the essential programming patterns and techniques for developing robust Flyte workflows. Once you understand the basics of task configuration, these guides will help you build sophisticated, production-ready data pipelines and machine learning workflows. ## What you'll learn The task programming section covers key patterns for building effective Flyte workflows: **Data handling and types** - **Tasks > Build tasks > Files and directories**: Work with large datasets using Flyte's efficient file and directory types that automatically handle data upload, storage, and transfer between tasks. - [**Volumes**](./volumes/_index): Mount a persistent file system and use it from within your task like an ordinary local directory. - **Tasks > Build tasks > DataFrames**: Pass DataFrames between tasks without downloading data into memory, with support for Pandas, Polars, PyArrow, and other DataFrame backends. - **Tasks > Build tasks > Data classes and structures**: Use Python data classes and Pydantic models as task inputs and outputs to create well-structured, type-safe workflows. - **Tasks > Build tasks > Custom context**: Use custom context to pass metadata through your task execution hierarchy without adding parameters to every task. **Execution patterns** - **Tasks > Build tasks > Fanout**: Scale your workflows by running many tasks in parallel, perfect for processing large datasets or running hyperparameter sweeps. - **Tasks > Build tasks > Mapping over inputs**: Apply the same task to every item of a list with `flyte.map`: in-order results, error handling, concurrency limits, and partials. - **Tasks > Build tasks > Consuming a message queue**: Pull messages from an external queue such as AWS SQS and fan out processing across a pool of reusable containers. - **Tasks > Build tasks > Controlling parallel execution**: Limit concurrent task executions using semaphores or `flyte.map` concurrency for rate-limited APIs, GPU quotas, and resource-constrained workflows. - **Tasks > Build tasks > Streaming map-reduce**: Process fanout results as they complete with `asyncio.as_completed`, reducing in batches incrementally instead of waiting for every task to finish. - **Tasks > Build tasks > Task dependencies and ordering**: Replicate DAG-like behavior (sequencing, fan-out, fan-in, and fine-grained dependency-driven scheduling) using `asyncio` in Flyte 2's implicit dependency model. - **Tasks > Build tasks > Structured concurrency with anyio**: Use `anyio` task groups as a top-level structured-concurrency alternative to raw `asyncio`, with automatic sibling cancellation when one task fails. - **Tasks > Build tasks > Orchestrator tasks**: Run driver tasks that only call other tasks without a pod of their own, so they start in milliseconds and hold no compute while they wait. - **Tasks > Build tasks > External conditions**: Pause a task until an external signal arrives: a human approval, a callback from an external service, or a value supplied at runtime. - **Tasks > Build tasks > Grouping actions**: Organize related task executions into logical groups for better visualization and management in the UI. - **Tasks > Build tasks > Run a bioinformatics tool**: Run arbitrary containers in any language without the Flyte SDK installed, using Flyte's copilot sidecar for data flow. - **Tasks > Build tasks > Remote tasks**: Use previously deployed tasks without importing their code or dependencies, enabling team collaboration and task reuse. - **Tasks > Configure tasks > Pod templates**: Extend tasks with Kubernetes pod templates to add sidecars, volume mounts, and advanced Kubernetes configurations. - **Tasks > Build tasks > Abort and cancel actions**: Stop in-progress actions automatically, programmatically, or manually via the CLI and UI. - **Tasks > Build tasks > Regular async function (not a task)**: Advanced patterns like task forwarding and other specialized task execution techniques. - **Tasks > Build tasks > Higher-order functions**: Write reusable functions that take tasks as arguments โ€” fallback, memory-scaling retry, circuit breaker, and batch map-reduce wrappers built on Flyte's dynamic execution. **Development and debugging** - **Tasks > Build tasks > Notebooks**: Write and iterate on workflows directly in Jupyter notebooks for interactive development and experimentation. - **Tasks > Build tasks > Test business logic directly**: Test your Flyte tasks using direct invocation for business logic or `flyte.run()` for Flyte-specific features. - **Tasks > Build tasks > Links**: Add clickable URLs to tasks in the Flyte UI, connecting them to external tools like experiment trackers and monitoring dashboards. - **Tasks > Build tasks > Reports**: Generate custom HTML reports during task execution to display progress, results, and visualizations in the UI. - **Tasks > Build tasks > Traces**: Add fine-grained observability to helper functions within your tasks for better debugging and resumption capabilities. - **Tasks > Build tasks > Intra-task checkpoints**: Save in-progress state within a task (such as a training loop) so retries resume from the last checkpoint instead of starting over. - **Tasks > Build tasks > Error handling**: Implement robust error recovery strategies, including automatic resource scaling and graceful failure handling. ## When to use these patterns These programming patterns become essential as your workflows grow in complexity: - Use **fanout** when you need to process multiple items concurrently or run parameter sweeps. - Use **mapping over inputs** to apply the same task to every item of a list, and **controlling parallel execution** when you need to limit how many run at the same time. - Apply **streaming map-reduce** when map tasks have uneven durations or you want to reduce results in batches as they complete, rather than waiting for the entire fanout to finish. - Implement **error handling** for production workflows that need to recover from infrastructure failures. - Apply **grouping** to organize complex workflows with many task executions. - Use **files and directories** when working with large datasets that don't fit in memory. - Use **DataFrames** to efficiently pass tabular data between tasks across different processing engines. - Choose **container tasks** when you need to run code in non-Python languages, use legacy containers, or execute AI-generated code in sandboxes. - Use **remote tasks** to reuse tasks deployed by other teams without managing their dependencies. - Apply **pod templates** when you need advanced Kubernetes features like sidecars or specialized storage configurations. - Use **traces** to debug non-deterministic operations like API calls or ML inference. - Use **intra-task checkpoints** to make long-running training loops resumable across retries, preemptions, and interruptions. - Use **links** to connect tasks to external tools like Weights & Biases, Grafana, or custom dashboards directly from the Flyte UI. - Create **reports** to monitor long-running workflows and share results with stakeholders. - Use **custom context** when you need lightweight, cross-cutting metadata to flow through your task hierarchy without becoming part of the task's logical inputs. - Write **unit tests** to validate your task logic and ensure type transformations work correctly before deployment. - Use **abort and cancel** to stop unnecessary actions when conditions change, such as early convergence in HPO or manual intervention. - Use **external conditions** to insert approval gates or data collection checkpoints into automated workflows. - Apply **higher-order functions** to factor recurring orchestration logic โ€” retry-on-OOM, fallback, circuit breaking, batching โ€” into reusable wrappers that work with any task. Each guide includes practical examples and best practices to help you implement these patterns effectively in your own workflows. {{< subpage-cards >}} ## Subpages - **Tasks > Build tasks > Files and directories** - Pass files and directories between tasks with flyte.io.File and flyte.io.Dir. - **Tasks > Build tasks > Volumes** - A durable, versioned file system that tasks mount and read and write like a local directory, with cheap copy-on-write forks. - **Tasks > Build tasks > Data classes and structures** - Pass dataclasses and Pydantic models between tasks as materialized values. - **Tasks > Build tasks > DataFrames** - Pass DataFrames between tasks by reference instead of materializing them. - **Tasks > Build tasks > Custom types** - Teach Flyte to serialize a type its type system does not already handle. - **Tasks > Build tasks > Custom context** - Pass configuration through a task hierarchy without threading it through every signature. - **Tasks > Build tasks > Abort and cancel actions** - Stop actions that are no longer needed while a run is still going. - **Tasks > Build tasks > Run a bioinformatics tool** - Run any container image as a task, with no Flyte SDK installed inside it. - **Tasks > Build tasks > Links** - Attach clickable URLs to a task so the UI can reach external tools. - **Tasks > Build tasks > Reports** - Display and update custom output in the UI while a task runs. - **Tasks > Build tasks > Notebooks** - Write and run Flyte workloads from inside a Jupyter notebook. - **Tasks > Build tasks > Orchestrator tasks** - Run driver tasks that only call other tasks without a pod of their own, so they start in milliseconds and hold no compute while they wait. - **Tasks > Build tasks > Remote tasks** - Call an already-deployed task without importing its code or dependencies. - **Tasks > Build tasks > Error handling** - Catch and recover from task failures, including out-of-memory errors, timeouts, missing GPU capacity, and GPU hardware faults. - **Tasks > Build tasks > Traces** - Make a called function observable and resumable with the flyte.trace decorator. - **Tasks > Build tasks > Intra-task checkpoints** - Save progress inside a long-running task so a retry does not start over. - **Tasks > Build tasks > Grouping actions** - Cluster related actions together so a large run stays readable in the UI. - **Tasks > Build tasks > Fanout** - Run many tasks in parallel, and what changes at large scale. - **Tasks > Build tasks > Mapping over inputs** - Apply one task across every item of an iterable, in parallel. - **Tasks > Build tasks > Consuming a message queue** - Build a long-running task that pulls messages from an external queue such as SQS. - **Tasks > Build tasks > Controlling parallel execution** - Cap how many fanned-out tasks run at once, for rate limits and quotas. - **Tasks > Build tasks > Streaming map-reduce** - Process fanned-out results as they finish instead of waiting for all of them. - **Tasks > Build tasks > Structured concurrency with anyio** - Use anyio or trio instead of asyncio, since the graph is built from what you await. - **Tasks > Build tasks > Task dependencies and ordering** - How ordering comes from ordinary Python data flow rather than an explicit DAG. - **Tasks > Build tasks > External conditions** - Pause a task until an external signal arrives, such as a human approval or a callback. - **Tasks > Build tasks > Test business logic directly** - Test task logic locally, with and without a running backend. - **Tasks > Build tasks > Higher-order functions** - Pass tasks to other tasks and return them, since tasks are ordinary Python. - **Tasks > Build tasks > Regular async function (not a task)** - Advanced patterns that do not fit the other pages in this section. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/files-and-directories === Pass files and directories between tasks with flyte.io.File and flyte.io.Dir. # Files and directories Flyte provides the `flyte.io.File` and `flyte.io.Dir` types to represent files and directories, respectively. Together with **Tasks > Build tasks > DataFrames** they constitute the *offloaded data types* - unlike **Tasks > Build tasks > Data classes and structures** like data classes, these pass references rather than full data content. A variable of an offloaded type does not contain its actual data, but rather a reference to the data. The actual data is stored in the internal blob store of your Union/Flyte instance. When a variable of an offloaded type is first created, its data is uploaded to the blob store. It can then be passed from task to task as a reference. The actual data is only downloaded from the blob stored when the task needs to access it, for example, when the task calls `open()` on a `File` or `Dir` object. This allows Flyte to efficiently handle large files and directories without needing to transfer the data unnecessarily. Even very large data objects like video files and DNA datasets can be passed efficiently between tasks. For the full picture of what gets stored in the bucket versus what stays in the control plane database, see **Get started > Core concepts > Where your data lives**. The `File` and `Dir` classes provide both synchronous and asynchronous methods to interact with the data, so you can use them from either kind of task. See **Tasks > Build tasks > Files and directories > Synchronous and asynchronous APIs** for the full method pairing. > [!NOTE] > Because `File` and `Dir` are passed by reference, a downstream cached task does not get a cache hit on identical content stored at a new path. To cache on content, attach a hash at production time - see **Tasks > Configure tasks > Caching > Content-based caching for DataFrames, files, and directories**. ## Example usage The examples below show the basic use-cases of uploading files and directories created locally, and using them as inputs to a task. ``` import asyncio import tempfile from pathlib import Path import flyte from flyte.io import Dir, File env = flyte.TaskEnvironment(name="files-and-folders") @env.task async def write_file(name: str) -> File: # Create a file and write some content to it with open("test.txt", "w") as f: f.write(f"hello world {name}") # Upload the file using flyte uploaded_file_obj = await File.from_local("test.txt") return uploaded_file_obj ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/files-and-directories/file_and_dir.py* The upload happens when the **Flyte SDK > flyte.io > File > Methods > from_local()** command is called. Because the upload would otherwise block execution, `File.from_local` is implemented as an `async` function. The Flyte SDK frequently uses this class constructor pattern, so you will see it with other types as well. This is a slightly more complicated task that calls the task above to produce `File` objects. These are assembled into a directory and the `Dir` object is returned, also via invoking `from_local`. ``` @env.task async def write_and_check_files() -> Dir: coros = [] for name in ["Alice", "Bob", "Eve"]: coros.append(write_file(name=name)) vals = await asyncio.gather(*coros) temp_dir = tempfile.mkdtemp() for file in vals: async with file.open("rb") as fh: contents = await fh.read() # Convert bytes to string contents_str = contents.decode('utf-8') if isinstance(contents, bytes) else str(contents) print(f"File {file.path} contents: {contents_str}") new_file = Path(temp_dir) / file.name with open(new_file, "w") as out: # noqa: ASYNC230 out.write(contents_str) print(f"Files written to {temp_dir}") # walk the directory and ls for path in Path(temp_dir).iterdir(): print(f"File: {path.name}") my_dir = await Dir.from_local(temp_dir) return my_dir ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/files-and-directories/file_and_dir.py* Finally, these tasks show how to use an offloaded type as an input. Helper functions like `walk` and `open` have been added to the objects and do what you might expect. ``` @env.task async def check_dir(my_dir: Dir): print(f"Dir {my_dir.path} contents:") async for file in my_dir.walk(): print(f"File: {file.name}") async with file.open("rb") as fh: contents = await fh.read() # Convert bytes to string contents_str = contents.decode('utf-8') if isinstance(contents, bytes) else str(contents) print(f"Contents: {contents_str}") @env.task async def create_and_check_dir(): my_dir = await write_and_check_files() await check_dir(my_dir=my_dir) if __name__ == "__main__": flyte.init_from_config() r = flyte.run(create_and_check_dir) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/files-and-directories/file_and_dir.py* ## Synchronous and asynchronous APIs Every I/O operation on `File` and `Dir` comes in two forms, so you can use the offloaded types from both asynchronous and synchronous tasks: - In an **asynchronous task** (`async def`), use the coroutine methods: `await` the upload, download, and existence calls, use `async with file.open(...)` to stream, and `async for` to walk a `Dir`. This is the pattern shown in **Tasks > Build tasks > Files and directories > Example usage** above. - In a **synchronous task** (plain `def`), use the `_sync` variants: `File.from_local_sync()`, `file.open_sync()`, `dir.walk_sync()`, and so on. These block until the operation completes. The two forms are otherwise equivalent โ€” pick the one that matches how your task is defined. A few constructors do no I/O and so have a single form that is used unchanged from either kind of task: `File.new_remote()`, `File.from_existing_remote()`, `Dir.new_remote()`, and `Dir.from_existing_remote()`. ### File methods | Asynchronous (in `async def` tasks) | Synchronous (in `def` tasks) | Purpose | |---|---|---| | `await File.from_local(path)` | `File.from_local_sync(path)` | Upload a local file to the blob store | | `File.new_remote()` | `File.new_remote()` | Allocate a new remote file to stream into | | `File.from_existing_remote(uri)` | `File.from_existing_remote(uri)` | Reference a file that already exists remotely | | `async with file.open(mode) as fh` | `with file.open_sync(mode) as fh` | Open the file as a stream for reading or writing | | `await file.download()` | `file.download_sync()` | Download the file to the local filesystem (a local file returns its own path; see below) | | `await file.exists()` | `file.exists_sync()` | Check whether the file exists | > [!WARNING] > If a `File` already points at the local filesystem, for example a file on a mounted volume, `download()` and `download_sync()` return the file's own path without copying it (`flyte` 2.11.2 or later). This happens when you pass no `local_path` or pass the file's own path. Modifying or deleting the returned file changes the source. > > To get a separate copy, pass a different `local_path`. For large files, use `download_sync()` for this: the async `download()` reads the whole file into memory when it copies. ### Dir methods | Asynchronous (in `async def` tasks) | Synchronous (in `def` tasks) | Purpose | |---|---|---| | `await Dir.from_local(path)` | `Dir.from_local_sync(path)` | Upload a local directory to the blob store | | `Dir.new_remote()` | `Dir.new_remote()` | Allocate a new remote directory to stream into | | `Dir.from_existing_remote(uri)` | `Dir.from_existing_remote(uri)` | Reference a directory that already exists remotely | | `async for f in dir.walk()` | `for f in dir.walk_sync()` | Iterate over the files in the directory | | `await dir.list_files()` | `dir.list_files_sync()` | List the files in the directory (see the note below for how deep each one goes) | | `await dir.get_file(name)` | `dir.get_file_sync(name)` | Get a single file from the directory by name | | `await dir.download()` | `dir.download_sync()` | Download the whole directory to the local filesystem | | `await dir.exists()` | `dir.exists_sync()` | Check whether the directory exists | If a `Dir` already points at the local filesystem, `dir.download()` and `dir.download_sync()` with no `local_path` return the directory's own path without copying it. Modifying or deleting files under it changes the source. > [!NOTE] > `walk()` accepts `recursive` and `max_depth`. With `recursive=False`, it yields the top-level files and the files one subdirectory down. `list_files()` returns the same set. > > `walk_sync()` accepts `recursive` and `file_pattern` but ignores both. Unless you pass `max_depth`, it yields every file at every depth. `list_files_sync()` also returns every file at every depth. > > To return only the top-level files from either form, pass `max_depth=1` and leave `recursive` at its default. In `walk()`, `recursive=False` replaces any `max_depth` you pass with 2. ### Synchronous example The **Tasks > Build tasks > Files and directories > Example usage** uses `await`, `async with`, and `async for`. The same kind of workflow written with the synchronous API uses plain `def` tasks and the `_sync` method names: ```python import flyte from flyte.io import File env = flyte.TaskEnvironment(name="sync-file") @env.task def write_file(content: str) -> File: # Allocate a new remote file and stream content into it f = File.new_remote() with f.open_sync("wb") as fh: fh.write(content.encode("utf-8")) return f @env.task def read_file(f: File) -> str: # Open the file for reading without downloading the whole object with f.open_sync("rb") as fh: return fh.read().decode("utf-8") @env.task def main() -> str: f = write_file(content="hello world") return read_file(f) ``` Directories work the same way โ€” use `Dir.from_local_sync()` to upload and `walk_sync()` to iterate: ```python import os import tempfile import flyte from flyte.io import Dir env = flyte.TaskEnvironment(name="sync-dir") @env.task def upload_dir() -> Dir: with tempfile.TemporaryDirectory() as tmp: for i in range(3): with open(os.path.join(tmp, f"file{i}.txt"), "w") as fh: fh.write(f"content {i}") # Upload the directory to the blob store return Dir.from_local_sync(tmp) @env.task def read_dir(d: Dir) -> int: count = 0 # Walk and read every file, all synchronously for file in d.walk_sync(recursive=True): with file.open_sync("rb") as fh: print(f"{file.name}: {fh.read().decode('utf-8')}") count += 1 return count @env.task def main() -> int: d = upload_dir() return read_dir(d) ``` ## JSONL files Flyte provides typed JSON Lines (JSONL) I/O through the `flyteplugins-jsonl` plugin, which extends `File` and `Dir` with the `JsonlFile` and `JsonlDir` types, adding streaming record-level read/write, optional zstd compression, and automatic shard rotation for large datasets. See the [JSONL integration](../../../integrations/jsonl/_index) guide for installation and usage. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/volumes === A durable, versioned file system that tasks mount and read and write like a local directory, with cheap copy-on-write forks. # Volumes A **Volume** is a durable file system that your task mounts and uses like an ordinary local directory, backed by object storage, but with real file-system semantics: open, read, write, list, and seek over many files in place. Unlike **Tasks > Build tasks > Files and directories**, which pass a *snapshot* of data as a value between tasks, a Volume is **long-lived and versioned**. You write to it during one run and commit it as an immutable version; any later task or run can mount that version and pick up exactly where you left off. Each commit is a new immutable version, and versions share unchanged data, so keeping history is cheap. ## Volumes vs. files and directories `File`/`Dir` and Volumes solve different problems. Use the one that matches how your data is shaped and used. | | `flyte.io.File` / `flyte.io.Dir` | Volume | |---|---|---| | **What it is** | A single file or folder passed as a value | A whole file system you mount | | **Access** | Uploaded/downloaded as a unit | Mounted; read and written in place, like a local disk | | **Lifetime** | Tied to the run that produced it | Long-lived; remount across tasks and runs | | **Changing it** | Produce a new `File`/`Dir` | Fork, write, and commit a new version (copy-on-write) | | **Best for** | Handing a finished artifact to the next task | Evolving, file-system-heavy state | If you just need to hand a finished file or folder from one task to the next, reach for **Tasks > Build tasks > Files and directories**. They're simpler and need no setup. Choose a Volume when you need a *mountable, durable file system* that evolves over time. > [!NOTE] > A Volume is a durable, network-backed file system, not an in-memory cache. > Use it when you want file-system semantics over durable, shared data > (mounting, partial and random reads, tools that expect files on disk). It is > **not** a way to speed up model loading: pulling weights into memory through a > Volume is slower than streaming them directly from object storage with a > purpose-built loader. ## When to use a Volume Volumes fit AI and agentic workloads, where work is long-running, stateful, and file-heavy: - **Agent memory and state.** Give an agent a durable workspace it builds up across turns, tasks, and sessions (notes, intermediate artifacts, a growing working set of files) and resume exactly where it left off, instead of starting cold each run. - **Sandboxes and code execution.** Back a [sandbox](../../../agents/sandboxing/_index) or code-execution environment with a Volume so agent- or model-generated code has a real, writable file system to work in. Fork a clean base per session so concurrent runs stay isolated from each other. - **Shared, durable datasets.** Keep a dataset, index, or other large working set on a Volume and mount it from many tasks to read (or fork and update) it as files, without re-fetching or re-uploading the whole thing each run. - **Branching experiments.** Fork a base Volume per experiment or per run; copy-on-write makes each branch independent and cheap, with version history to compare against or roll back to. More broadly, reach for a Volume whenever you need **long-lived, versioned state** that carries forward across tasks or runs: anything you'd otherwise rebuild from scratch every time. > [!TIP] Many small files, one writer? > Build caches, package caches, virtualenvs and source trees spend most of > their time on per-file metadata. A **Tasks > Build tasks > Volumes > Block volumes** stores the > volume as one ext4 image the kernel mounts directly, which brings these > workloads close to local-disk speed. ## Read-write and read-only volumes A Volume is always one of two types, and the type tells you what you can do with it: - **`RWVolume`**: a writable handle. `Volume.new()` returns one. Mount it, write to it, and `commit()` to record an immutable version. While it is mounted it is the **single writer**. - **`ROVolume`**: an immutable, committed version. Mount it read-only to read its contents. To change it, `fork()` it into a new `RWVolume`. Because the type is part of a task's signature, the read/write contract is enforced at the task boundary: a task that declares `vol: ROVolume` can read shared data but cannot mutate it. Returning a writable `RWVolume` from a task commits it and hands the next task an `ROVolume`. ## Setup Volumes are mounted inside the task or app pod, so the environment needs two things: an **image** with the volume client (`flyteplugins-union`), and a **pod template** that lets the pod reach the mount. ```python import flyte from flyteplugins.union.io import Volume, ROVolume, allow_volumes image = ( flyte.Image.from_debian_base() .with_pip_packages("flyteplugins-union") # volume client (bundles the mount binary) ) env = flyte.TaskEnvironment( name="volumes-demo", image=image, # let the pod mount Volumes (no privileges required) pod_template=allow_volumes(), resources=flyte.Resources(cpu="1", memory="2Gi"), ) ``` > [!NOTE] > **`allow_volumes()`** (from `flyteplugins.union.io`) is the only pod-level > setup a Volume needs, and the mount runs fully **unprivileged**: no > `CAP_SYS_ADMIN`, no `/dev/fuse`, no `fuse3` package. > > It relies on a mount broker running on the cluster. The Union data plane ships > one; on a self-managed cluster an administrator > **Self-managed deployment > Advanced configurations > Volumes**. ### Volumes in apps An [app](../../../apps/_index) mounts Volumes with the same pod template as a task. Requires `flyte` 2.12.2 or later. ```python from flyte.app.extras import FastAPIAppEnvironment app_env = FastAPIAppEnvironment( name="volume-app", app=app, image=image, pod_template=allow_volumes(), ) ``` The apps backend requires the app's primary container to be named `app`. When the app is deployed, the SDK renames the pod template's primary container to `app`, so you don't need to set `primary_container_name`. A pod template with a sidecar container already named `app` is rejected. To hand an app a committed version, pass its locator as a string **Apps > Configure apps > Passing parameters into app environments** and load it with `Volume.from_locator()`. The app mounts that version read-only. See **Tasks > Build tasks > Volumes > Versions, artifacts and lineage > Reference a volume across runs**. This page covers only that read-only pattern, not mounting a writable volume in an app. The app's Knative Serving must allow inline CSI volumes and mount propagation (the `kubernetes.podspec-volumes-csi` and `kubernetes.podspec-volumes-mount-propagation` features). On a self-managed data plane, an administrator must confirm that both features are enabled in the Knative Serving configuration. A data plane that still serves apps through the `knative-operator` chart (Knative Serving 1.16) supports neither, so complete **Self-managed deployment > Upgrade the data plane > One-time migrations** first. ## Where to go next The rest of this topic is split by what you are trying to do. The quickest way to get your hands on a volume is the first one: it needs no cluster. {{< subpage-cards >}} ## Reference - API: `Volume`, `RWVolume`, `ROVolume`, and `flyteplugins.union.io.allow_volumes`. - Artifact publication: `Volume.new(artifact=...)`, `fork(artifact=...)`, and `publish_artifact=` / `artifact_version=` on `commit()` and `finalize()` - see **Tasks > Build tasks > Volumes > Versions, artifacts and lineage > Tracking versions as artifacts**. - Reporting: `vol.report = True` or `$UNION_VOLUME_REPORT` - see **Tasks > Build tasks > Volumes > Performance, caching and tuning > Debugging a mount**. - Caching: `allow_volumes(cache_size=...)` and `mount(cache_dir=..., cache_size_mb=...)` - see **Tasks > Build tasks > Volumes > Performance, caching and tuning > The chunk cache**; `allow_volumes(shared_node_cache=True)` and `mount(shared_node_cache=...)` - see **Tasks > Build tasks > Volumes > Performance, caching and tuning > Shared node cache**. - Client memory: `$UNION_VOLUME_CLIENT_MEMORY_LIMIT`. See **Tasks > Build tasks > Volumes > Performance, caching and tuning > Tuning the mount**. - CLI: `flyte create volume`, `flyte mount volume`, `flyte warmup volume`, `flyte status volume`, `flyte unmount volume`, `flyte forget volume` - see **Tasks > Build tasks > Volumes > Work with a volume on your machine**; `flyte explore volume` - see **Tasks > Build tasks > Volumes > Work with a volume on your machine > Inspecting a volume**. - Related: **Tasks > Build tasks > Volumes > Block volumes** for small-file, single-writer workloads; **Tasks > Build tasks > Files and directories** for passing snapshot data between tasks. ## Subpages - **Tasks > Build tasks > Volumes > Work with a volume on your machine** - Mount a Volume on a laptop, a dev box or a CI runner with the flyte CLI - a durable working copy you can resume, and warm for working offline. - **Tasks > Build tasks > Volumes > Use a volume in a task** - The create, mount, write and return lifecycle of a Volume inside a task - forking to update a version, writing in parallel, and checkpointing mid-task. - **Tasks > Build tasks > Volumes > Versions, artifacts and lineage** - Publish each sealed Volume version to the artifact registry with a stable name and parent edges, and pin a specific version from an unrelated run by locator. - **Tasks > Build tasks > Volumes > Performance, caching and tuning** - The chunk cache, the shared node cache, mount options, measured trade-offs against local disk, and how to tell a slow mount from a wedged one. - **Tasks > Build tasks > Volumes > Block volumes** - A Volume whose content is one ext4 disk image, for small-file, single-writer workloads like build and package caches that need near-local-disk speed. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/volumes/local === Mount a Volume on a laptop, a dev box or a CI runner with the flyte CLI - a durable working copy you can resume, and warm for working offline. # Work with a volume on your machine **Tasks > Build tasks > Volumes > Use a volume in a task** runs everything inside the cluster. You can also mount a volume **on your own machine** - a laptop, a dev box, a CI runner - and read and write it like any other directory. No FUSE tooling to install: on macOS the volume is served over a loopback NFS mount instead, so `mount volume` works there without macFUSE. `--transport` picks between them (`auto` means NFS on macOS and FUSE elsewhere), and a few commands behave differently over NFS - each is called out where it comes up. This is the workflow for building a dataset by hand, inspecting one in place with ordinary tools, or carrying one onto a plane. ## Create a volume ```bash flyte create volume my-dataset --artifact my-dataset \ --project my-project --domain development ``` `--artifact` registers the new volume in the artifact registry under that name. It is optional, but without it nothing in the registry knows the volume, and the only handle you have afterwards is the locator `create` printed - so every later mount has to name that locator. Registering it once gives you a name you can mount by instead. You do not have to say where it lives. The CLI asks the control plane for the storage this project and domain already use - the same raw-data path a task would be given - so a volume you create from a laptop lands exactly where a volume created inside a task lands. It prints the bucket it chose and the locator of the new (empty) version. Pass `--bucket s3://my-bucket/volumes` to choose explicitly; with an explicit bucket the command contacts no control plane at all. `--size 64G` makes a **Tasks > Build tasks > Volumes > Block volumes** instead, which is much faster for workloads with many small files - but only on Linux: macOS has neither an ext4 driver nor a loop device to attach the image to, so `--size` is refused there. > [!NOTE] > The discovered bucket is the one your **tasks** use, and your laptop is a > different access domain. If `create` fails with *"Access denied reading the > bucket"*, your local credentials cannot reach that bucket even though they > are valid - use a profile or role that can (`AWS_PROFILE=...`), or pass > `--bucket` to use one you already have access to. ## Mount it Name the volume with exactly one of `--artifact`, `--run` (with `--action`), or `--locator`. The mount point is the only positional argument: ```bash # By artifact, which is the name you would normally use flyte mount volume ~/data --artifact my-dataset # A specific version, by the locator create or commit printed. Needs no # control plane at all - only object-store credentials. flyte mount volume ~/data --locator s3://my-bucket/volumes/versions/volumes/.metadata.json ``` The volume is **forked first** and the fork is what gets mounted, so writing through the mount cannot touch the version you named. A fork copies no data. The command then holds the terminal. Press **Ctrl-C** to drain, unmount, and publish your writes as a new version, whose locator it prints - as do `kill` and closing the terminal, so a mount does not get orphaned by a closed window. `--no-commit` throws the writes away instead, and `--read-only` mounts without forking at all - use it when you only have read access, or only want to look. ## A local mount is a durable working copy A local mount is not a scratch directory. The fork is recorded on disk, so a second `mount volume` of the same volume comes back to it rather than making another one - and **if the first mount ended without publishing, the work is still there and the mount picks it up.** Losing your connection, your credentials expiring, or the machine restarting all leave the work recoverable. **Resuming needs no network.** The fork's own record is kept with the working copy, so rebuilding it does not re-read anything from the bucket. That is the difference between resuming on a plane and resuming after you land. A mount also outlives the credentials it started with. By default (`--credentials auto`) the client reads them from a refreshing loopback endpoint rather than holding a copy, and scopes them to this volume where the store allows it, so a long mount does not die when a token expires. `--credentials ambient` takes the environment as-is and **cannot refresh** - use it only for a short mount, or where the ambient credentials do not expire. Three commands manage that local state: ```bash flyte status volume # what is held locally, and how much of it is unpublished flyte status volume my-dataset # just this one flyte unmount volume my-dataset # stop a mount running in another terminal, publishing as it goes flyte forget volume my-dataset # remove the local copy ``` `forget` refuses to take unpublished work with it unless you pass `--discard`. If the published version has moved on while your local work sat there, the next mount says so and asks which you want. Keeping your work is the default, including when there is no terminal to ask - a prompt nobody can answer is not consent to delete. `--discard-local` chooses the other way explicitly. > [!NOTE] > The mount is served by a client process that outlives the CLI. If you kill > the CLI with `SIGKILL` (rather than Ctrl-C), that client keeps running and > keeps the local index open, and the next mount will tell you so and name the > process. Your work is safe - it is in the local index, not in that process. > Stop it and mount again, and the resume picks the work up. ## Take it offline Reads are served on demand, so a mount needs the network for anything it has not already cached - and an uncached read with no network is an **I/O error**, not a slow read. Warm the cache before you disconnect: ```bash # A subtree you know you need flyte mount volume ~/data --artifact my-dataset --warmup models/ # Everything flyte mount volume ~/data --artifact my-dataset --warmup . ``` `--warmup` names a path **inside** the volume, relative to the mount point, and can be repeated. You can also warm a mount that is already up, from another terminal: ```bash flyte warmup volume ~/data # the whole volume flyte warmup volume ~/data models/ # just this subtree flyte warmup volume ~/data --check # report what is already cached ``` On macOS the client's own parallel prefetch is unavailable: it drives the mount through a control file the NFS server does not serve. Warming falls back to reading the files, which is slower and ends in the same place, so `flyte warmup volume ~/data` works there. **`--check` has no such fallback** - there is nothing to ask but the control file - so it is refused on macOS, and on any mount you started with `--transport nfs`. > [!NOTE] > `flyte create volume --mount` is **not** resumable, and says so when you use > it. A volume you have just declared has no published version yet, so there is > nothing to fork and come back to. Create it, then `flyte mount volume` the > locator it printed - that path resumes. ## Inspecting a volume To browse a volume without mounting it, use the CLI. `flyte explore volume` opens an interactive view of a volume's file tree and its version history, reading only the small metadata index (no FUSE mount and no file downloads): ```bash # Explore the volume produced by a run (auto-discovers the volume output) flyte explore volume # Pin a specific action and the exact output to inspect flyte explore volume --op-name my_volume ``` It follows the version lineage, so you can step back through earlier commits and jump to the action that produced any version. To open an index you already have on disk, pass `--from-file `. ## Next - **Tasks > Build tasks > Volumes > Use a volume in a task** - the same volume, from inside the cluster. - **Tasks > Build tasks > Volumes > Performance, caching and tuning** - what the local cache is doing, and the knobs that apply to any mount. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/volumes/in-tasks === The create, mount, write and return lifecycle of a Volume inside a task - forking to update a version, writing in parallel, and checkpointing mid-task. # Use a volume in a task A task mounts a Volume and uses it like a local directory. Most of this page follows from one property: a Volume has exactly **one writer** while it is mounted. That is why you change a version by forking it, why parallel writers each get their own fork, and why a long task checkpoints rather than sharing. It assumes the image and pod template from [Setup](./_index#setup). ## Get started The lifecycle is: **create โ†’ mount โ†’ write โ†’ return**. Returning a writable volume from a task commits it into an immutable `ROVolume`; downstream tasks receive that and mount it read-only. ```python import flyte from flyteplugins.union.io import Volume, RWVolume, ROVolume @env.task async def create_dataset() -> RWVolume: vol = Volume.new(name="my-dataset") # a fresh writable RWVolume data = await vol.mount() # mount (default: ~/flyte-volume/my-dataset); returns the path (data / "greeting.txt").write_text("hello from a volume\n") return vol # auto-committed; the next task receives an ROVolume @env.task async def read_dataset(vol: ROVolume) -> str: data = await vol.mount() # ROVolume always mounts read-only return (data / "greeting.txt").read_text() @env.task async def main() -> str: dataset = await create_dataset() return await read_dataset(dataset) ``` `Volume.new()` hands you a writable `RWVolume`. When you return it from a task, your writes are flushed and the volume is committed into an immutable `ROVolume`: a durable version safe to pass between tasks. The next task receives that `ROVolume` and mounts the exact same data. > [!NOTE] > Returning a mounted `RWVolume` commits and unmounts it for you. To attach a > message to that final version, return `finalize()` explicitly: > `return await vol.finalize(message="initial dataset")`. To record a version > *partway* through a task without unmounting, use `commit()`. See > **Tasks > Build tasks > Volumes > Use a volume in a task > Checkpoint while you work**. ## Updating a volume by forking An `ROVolume` is immutable, so you never edit one in place. Instead you **fork** it (creating an independent, writable `RWVolume` branch), then write and commit a new version: ```python @env.task async def add_file(vol: ROVolume) -> ROVolume: rw = await vol.fork(name="my-dataset-v2") # copy-on-write writable branch data = await rw.mount() (data / "extra.txt").write_text("added in a later run\n") return await rw.finalize(message="add extra.txt") ``` Forking is **copy-on-write**: the branch shares all unchanged data with its parent and only stores what you actually change, so it stays cheap even for very large Volumes. The parent version is never touched, so you keep a clean lineage of versions to compare against or roll back to. Forks are also isolated: two branches (or two parallel runs) can write at the same time without clobbering each other. ## Writing in parallel A Volume has a **single writer** while it is mounted. One task mounts an `RWVolume`, writes, and commits; mounting the *same* volume read-write from two tasks at once is not supported, and there is no distributed file locking. To write in parallel, don't share one mount: **fork**. Each fork is an independent `RWVolume` on a disjoint key space, so branches never collide, even when they run at the same time: ```python import asyncio @env.task async def process_shard(base: ROVolume, i: int) -> ROVolume: branch = await base.fork(name=f"shard-{i}") # isolated writable branch data = await branch.mount() (data / f"shard-{i}.bin").write_bytes(compute_shard(i)) return await branch.finalize(message=f"shard {i}") @env.task async def fan_out(base: ROVolume) -> list[ROVolume]: # each shard runs as its own action, writing its own fork concurrently return await asyncio.gather(*(process_shard(base, i) for i in range(8))) ``` Each branch commits its own immutable version; downstream you can read them independently or fork a new branch from any of them. Reading is never restricted: any number of tasks can mount the same `ROVolume` read-only at once. ## Checkpoint while you work Use `commit()` to record a version **without unmounting**: useful in long-running loops where you want a durable point you can resume from if the run is interrupted: ```python @env.task async def train(base: ROVolume) -> ROVolume: rw = await base.fork(name="training-run") data = await rw.mount() for epoch in range(100): train_one_epoch(data) # writes under the mounted volume if epoch % 10 == 0: await rw.commit(message=f"epoch {epoch}") # durable checkpoint return await rw.finalize(message="training complete") ``` Each `commit()` records a durable, immutable version you can resume from. Those versions are **retained**, so commit on a cadence that matches how often you'd actually want to roll back: checkpoint periodically rather than every step, and prune versions you no longer need. ## Custom images The setup above works on top of any image built from `flyte.Image.from_debian_base()`. If you bring a **fully custom image** (your own Dockerfile / base), it needs one thing: **the volume client**, `pip install flyteplugins-union`. The wheel bundles the mount binary, so there's nothing else to fetch. In a Dockerfile that's: ```dockerfile RUN pip install flyteplugins-union ``` That is the whole image contract: no FUSE userspace tools are needed. > [!NOTE] > The container also needs to run as a user that can write the volume's > `mount_path`, `meta_dir`, and `cache_dir`. The defaults live under the task > user's `$HOME`, which the default image owns; if your image runs as a > different user or root, either keep those dirs writable or pass explicit > writable paths to `mount()`. ## Next - **Tasks > Build tasks > Volumes > Versions, artifacts and lineage** - publish each sealed version, and reach a specific version from an unrelated run. - **Tasks > Build tasks > Volumes > Performance, caching and tuning** - the chunk cache, mount options, and the measured trade-offs. - **Tasks > Build tasks > Volumes > Work with a volume on your machine** - the same volume from a laptop. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/volumes/versions === Publish each sealed Volume version to the artifact registry with a stable name and parent edges, and pin a specific version from an unrelated run by locator. # Versions, artifacts and lineage A volume's version history is durable on its own. This page is about reaching it from outside: publishing versions to the artifact registry so they have stable names and visible parent edges, and addressing one exact version from somewhere that has no task input to receive it. ## Tracking versions as artifacts Every commit gives you an immutable version, but that history lives inside the volume. Declaring the volume as an **artifact** also publishes each sealed version to the artifact registry, where it has a stable name, is searchable across runs, and carries an explicit parent edge to the version it came from. Declare the identity once, when the volume is created: ```python @env.task async def build_index() -> RWVolume: vol = Volume.new(name="search-index", artifact=True) data = await vol.mount() build_into(data) return vol # the committed version is published as artifact "search-index" ``` `artifact=True` publishes under the volume's own name. Pass a string to publish under a different name, or a `flyte.artifacts.Metadata` when you want a description and your own attributes: ```python from flyte.artifacts import Metadata vol = Volume.new( name="search-index", artifact=Metadata( name="product-search-index", description="FAISS index over the product catalog", attrs={"team": "search"}, ), ) ``` Artifact identity belongs to the *lineage*, not to any one version, so you set it when the volume is created or when you **Tasks > Build tasks > Volumes > Versions, artifacts and lineage > Tracking versions as artifacts > Branching under a different artifact** - never per commit. That is why `commit()` and `finalize()` take no artifact name: renaming mid-stream would split one version graph into two. > [!NOTE] > `Metadata(version=...)` and `Metadata(card=...)` are rejected on a volume. > Versions are per-seal, and the card is rendered from each seal. ### Publishing a version Returning the volume from a task publishes that seal as part of writing the task's outputs: no extra call in your code, and no registry round trip inside the task. To publish a checkpoint partway through a task, ask for it on the commit: ```python for epoch in range(100): train_one_epoch(data) if epoch % 10 == 0: await rw.commit(message=f"epoch {epoch}", publish_artifact=True) return await rw.finalize(message="training complete") # published too, if the volume declares an artifact ``` `publish_artifact=True` works even on a volume that declared no identity; the artifact name then defaults to the volume's name. Commits you don't publish are still durable versions - they are simply not in the registry, much as a local commit is real but has not been pushed. The registry holds the versions you chose to publish. ### Versions and parents A published version defaults to the seal's **identity hash**, which covers the committed index and where its chunks live. Every seal writes a new index, so every seal is its own version; publishing the *same* seal twice is idempotent rather than duplicating it. Pass `artifact_version="v3"` to `commit()` or `finalize()` to choose the version string yourself. Each version records a parent edge pointing at the previous *published* version of the same artifact, so the registry mirrors the branching shape of the volume's own lineage. Alongside any attributes you set, every published version carries: | Attribute | What it holds | |---|---| | `volume/name` | The volume's name | | `volume/locator` | The locator for this exact version, for `Volume.from_locator()` | | `volume/used_bytes` | Bytes used at the seal | | `volume/inode_count` | Files, directories and symlinks at the seal | | `volume/metadata_store` | The metadata store backing the volume | ### Branching under a different artifact `fork()` inherits its parent's artifact identity, so a branch keeps publishing under the same name and the registry shows it as a continuation. Give a branch its own artifact when it is genuinely a different thing. The first version published under the new name still records the old one as its parent, so the lineage stays connected across the rename: ```python candidate = await base.fork( name="index-candidate", artifact="product-search-index-candidate", ) ``` Pass `artifact=None` to detach a branch from the registry entirely: it still commits durable versions, it just publishes none of them. > [!NOTE] > Publishing is best-effort by design. If the registry is unreachable the seal > still succeeds, your data is still durable and still addressable by locator, > and a warning records that the registry entry is missing. Local executions > skip publishing altogether. ## Reference a volume across runs The usual way to receive a volume is as a typed task input or from `run.outputs`. When you instead want to pin a **specific version** and reach it from an unrelated run (a config value, a scheduled job, an external system), save its **locator**. Every committed version exposes one via the `locator` property: a stable object-store address you can store anywhere. ```python @env.task async def publish() -> str: vol = Volume.new(name="my-dataset") await vol.mount() # ... write data ... ro = await vol.finalize(message="v1") return ro.locator # e.g. persist this string somewhere ``` Later, in a different run, with no shared task input, load it back with `Volume.from_locator`. It returns a read-only `ROVolume` with everything recovered (the data index, bucket, store type, stats and lineage), so you can mount it directly or `fork()` it to branch and write: ```python @env.task async def consume(addr: str) -> int: ro = await Volume.from_locator(addr) # -> ROVolume, no task context needed data = await ro.mount() # read-only return len(list(data.glob("**/*"))) ``` The locator stays resolvable as long as the producing run's outputs are retained. `locator` is `None` for a freshly created volume that hasn't been committed yet: there's no published version to point at. ## Next - **Tasks > Build tasks > Volumes > Performance, caching and tuning** - commit cost is part of the write path; this is where the numbers are. - **Tasks > Build tasks > Volumes > Use a volume in a task** - where commits come from. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/volumes/performance === The chunk cache, the shared node cache, mount options, measured trade-offs against local disk, and how to tell a slow mount from a wedged one. # Performance, caching and tuning A Volume is a file system over object storage, so caching and mount options decide most of what you will feel. Read the first section even if you skip the rest: the default cache location is the worst one available, and fixing it is a single argument. ## The chunk cache Reads go through a local **chunk cache**. Where that cache lives is the single biggest lever on read performance, and by default it is in the worst place: unset, it falls back to `$HOME`, which on every managed Kubernetes is the container's overlayfs - the slowest writable thing on the node. With `allow_volumes()`, each mount whose cache is in that default location gets a budget from the container's ephemeral-storage limit: half of what is still unclaimed from 50% of the limit, and at least 1 GiB. The mount returns its budget when it unmounts. Requires `flyteplugins-union` 0.15.0 or later. **Give it a real disk.** `cache_size` attaches a sized `emptyDir` and tells the client its budget: ```python pod_template = allow_volumes(cache_size="50Gi") ``` The budget matters as much as the disk. Without it the client keeps its own 100 GiB default, overruns the `emptyDir`'s limit, and kubelet evicts the pod - a worse failure than a cache that is merely smaller than you hoped. The published budget is about 90% of the size you give, leaving headroom for the client's own bookkeeping and the imprecision of its accounting. It is per mount: split it with `mount(cache_size_mb=...)` when one task mounts several volumes. ## Shared node cache With `shared_node_cache=True`, read-only mounts in the pod use a chunk cache shared by every pod on that node, so a chunk is fetched from object storage once per *node* rather than once per *pod*: ```python pod_template = allow_volumes(cache_size="50Gi", shared_node_cache=True) ``` This is worth reaching for when many pods on a node read the same volume - a fan-out over one dataset, or several tasks sharing a model. It is not a general speed-up: pods reading unrelated volumes share nothing but the disk. The task pod gains no privilege from it. The shared directory arrives as an inline CSI volume from the same mount broker that serves the volume channel, and the broker bind-mounts a per-namespace subtree of the node's cache - so other namespaces are not visible, and the pod still has no `hostPath` and no capabilities. It needs a broker configured with a node cache directory, which the dataplane chart enables by default (`uvolMountBroker.nodeCache`); a pod that asks for one where the broker has none fails to start rather than quietly falling back. > [!NOTE] > **Read-only only, and that is a correctness rule rather than a policy.** > JuiceFS keeps its write-back staging queue *inside* the cache directory, so > two writers sharing one directory would interleave each other's > not-yet-uploaded blocks. A writable mount therefore never shares: > `shared_node_cache=True` on one raises an error, and the per-mount default > falls back to the pod's own cache. Per mount, `mount(shared_node_cache=...)` decides: | Value | Behavior | |---|---| | unset (default) | Use the shared cache when the pod exposes one and the mount is read-only; otherwise use the pod's own. | | `True` | Require it. Errors if the pod exposes none, or if the mount is writable. | | `False` | Never share; always use the pod's own cache. | An explicit `mount(cache_dir=...)` wins over all of it. > [!NOTE] > Every client sharing the directory runs its own eviction against its own > budget, so they can evict each other. Expect hit rates to vary with whatever > else is mounted on the node - it is a shared cache, not a reservation. ## Tuning the mount `mount()` accepts options to match the I/O profile of your workload: where to mount, how aggressively to upload, and how long to cache metadata: ```python data = await vol.mount( mount_path="/tmp/data", # a writable mount point (default: ~/flyte-volume/) max_uploads=100, # raise upload concurrency for write-heavy bursts (default 50) attr_cache=120.0, # cache file metadata longer (default 60s) entry_cache=120.0, # cache name lookups longer dir_entry_cache=120.0, # cache directory listings longer ) ``` | Option | Default | Use it toโ€ฆ | |---|---|---| | `mount_path` | `~/flyte-volume/` | Mount somewhere other than the default. | | `max_uploads` | `50` | Raise the cap on concurrent uploads. Bump it during write-heavy bursts of many small files, where the default concurrency can't saturate the upload link to object storage. | | `attr_cache` / `entry_cache` / `dir_entry_cache` | `60.0` | Cache file metadata, name lookups, and directory listings longer to collapse repeated `stat`/listing calls. | > [!NOTE] > Raising the cache TTLs is safe because a Volume has a single writer while it is > mounted. It helps most when a tool repeatedly stats or lists the same paths > (common with package managers and build systems). The volume client runs in the task's pod, so its memory counts toward the task's `memory` in `flyte.Resources`. Leave room for it. By default, the client's Go memory is held near 2 GiB. This is a soft limit (`GOMEMLIMIT`), and the client can go over it. Requires `flyteplugins-union` 0.15.5 or later. To change the limit, set `UNION_VOLUME_CLIENT_MEMORY_LIMIT` in the task environment's `env_vars` to a Go size such as `1536MiB`, or to `off` for no limit. A value that isn't a Go size falls back to `2GiB`, with a warning. A `GOMEMLIMIT` set on the task does not reach the client. ## Performance and trade-offs A Volume is a durable, object-store-backed file system, so it behaves differently from a local disk. Know the trade-offs before reaching for one: - **It is not local memory or disk.** Reads and writes go through a cache over object storage. Sequential, file-system-style I/O is fast, but small random operations have higher latency than `tmpfs` or a local SSD. For raw throughput into memory (streaming model weights, say), a purpose-built loader reading directly from object storage will beat mounting a Volume. - **Writes are decoupled from durability.** With write-back (the default), writes land in a local cache and upload in the background; the cost of making them durable is paid at `commit()` / `finalize()`, not on each write. Budget for commit time separately from your write loop. - **Per-file work dominates with many small files.** Mounting itself stays fast even with tens of thousands of files, but operations that touch every file (creating or traversing them) are bounded by per-file metadata cost. The **Tasks > Build tasks > Volumes > Performance, caching and tuning > Tuning the mount** exist to absorb this; reach for them on file-count-heavy workloads. - **Versions are retained.** Every commit keeps an immutable version, so commit on a deliberate cadence and prune versions you no longer need. ### Benchmark Numbers from a single run on AWS (S3 storage, `us-east-2` region) on a 4 vCPU / 8 GiB pod, via `benchmarks/volume_benchmark.py`. They depend heavily on cloud provider, region, file sizes, and instance type, so treat them as ballpark and re-run the benchmark for your own environment. Head-to-head against a local disk (the pod's container filesystem): | Operation | Local disk | Volume | |---|---|---| | Sequential write (512 MB) | ~2,200 MB/s | ~930 MB/s | | Commit 512 MB to durable storage | n/a | ~3.3 s (~160 MB/s) | | Mount time, 100 โ†’ 50,000 files | n/a | ~0.55 s โ†’ ~0.63 s | A Volume trades raw speed for durability and sharing. Sequential writes run ~0.4ร— local disk: even though uploads are async, each write still passes through the FUSE layer and the client's chunking/hashing into the cache. Mounting stays sub-second even at 50k files, and making 512 MB durable adds a few seconds at `commit()`. > [!NOTE] > The per-file metadata figures from this run are not reproduced here: they were > measured against the metadata store that used to be the default, and the > current one is substantially faster for creates and stats. Re-run the > benchmark in your own environment if file-count-heavy throughput is what you > are sizing for. ## Debugging a mount When a volume is slow, or a task looks stuck on file I/O, turn on the **volume report**. It samples the live mount while the task runs and publishes a `Volume` tab on the task's **Tasks > Build tasks > Reports**: throughput over time, a marker at each `commit()` and `finalize()`, and a health line. ```python vol = Volume.new(name="my-dataset") vol.report = True # set before mount(); sampling starts at mount data = await vol.mount() ``` The setting belongs to that handle only. It does not travel with the volume, so a branch from `fork()`, or a volume a later task receives, needs it set again. To cover every mount without per-handle code, set the environment variable on the task environment instead: ```python env = flyte.TaskEnvironment( name="my-env", env_vars={"UNION_VOLUME_REPORT": "1"}, ) ``` The report is flushed at every seal point, so the charts survive a task that fails later. Read the health line first, because it separates the two situations that look identical from inside the task: - **healthy** - requests are being served, and the number waiting is shown. Slow is then a tuning question: see **Tasks > Build tasks > Volumes > Performance, caching and tuning > Tuning the mount** and **Tasks > Build tasks > Volumes > Performance, caching and tuning > Performance and trade-offs**. - **wedged** - requests have sat unmoved long enough that nothing inside the pod will recover them. The line names the channel, how many requests are waiting and for how long. Abort the channel or replace the pod; waiting will not help. - **unknown** - no health answer is available, which is what you see when the mount does not go through the node's mount broker. > [!NOTE] > The report can never fail a mount. If sampling cannot start or a probe goes > unanswered, the task runs exactly as it would have without it. ## Next - **Tasks > Build tasks > Volumes > Block volumes** - if per-file metadata cost is what is hurting, this is the bigger lever than any option here. - **Tasks > Build tasks > Volumes > Use a volume in a task** - where `mount()` is called. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/volumes/block-volumes === A Volume whose content is one ext4 disk image, for small-file, single-writer workloads like build and package caches that need near-local-disk speed. # Block volumes A **block volume** is a [Volume](./_index) whose content is a single ext4 disk image rather than a tree of individual files. When you mount it, the image is attached as a loop device and mounted as an ordinary ext4 file system, so the kernel handles every `open`, `stat` and `mkdir` itself instead of making a network-backed round trip for each one. Everything else is still a Volume: it lives in object storage, `commit()` records immutable versions, forks are copy-on-write and share unchanged data, and you pass it between tasks like any other Volume. What changes is the trade-off: block volumes are much faster on workloads made of many small files, in return for a size limit, a single writer, and a cluster-level opt-in. ## When to use a block volume Reach for a block volume when a **single task writes and reads many small files**, and the same state should carry over from one run to the next: - **Build caches.** BuildKit, Go (`GOCACHE`), Bazel, `ccache`, Gradle. - **Package caches and environments.** pip and uv caches, virtualenvs, `node_modules`, Cargo and Maven repositories. - **Source trees and workspaces.** Checkouts that a build or agent churns through file by file. These workloads are dominated by per-file metadata operations, which is exactly where a regular Volume pays the most. Measured on the same cluster: | Workload | Local disk | Regular Volume | Block volume | |---|---|---|---| | Write 5,000 small files | n/a | 6.9 s | 0.44 s | | BuildKit build, cold cache | 59 s | 125 s | 67 s | | `go build`, cold cache | 304 s | 677 s | 322 s | Stay with a **regular Volume** when: - **Many tasks read the same data at once.** A block volume mounts read-write only, so every reader works on its own fork. Regular Volumes allow any number of concurrent read-only mounts. - **You want to browse or inspect individual files** from outside a task. The files of a block volume exist only inside its image. - **The data is mostly large files.** Sequential I/O on large files is already fast on a regular Volume, and it has no size limit to manage. - **The code writing to it is untrusted.** See **Tasks > Build tasks > Volumes > Block volumes > Setup**. | | Regular Volume | Block volume | |---|---|---| | **Content** | Each file stored separately | One ext4 image | | **Small-file performance** | Network round trip per operation | Near local disk | | **Size** | Unlimited | Fixed; grow it with `grow()` | | **Immutable version type** | `ROVolume` | `ROBlockVolume` (an `ROVolume`) | | **Read-only mounts** | Yes, any number at once | No: fork, then mount the fork | | **Browse files without mounting** | Yes (`flyte explore volume`) | No | | **Cluster setup** | Mount broker | Mount broker **and** an administrator opt-in | ## Setup A block volume uses the same image and pod template as any Volume. See [Volumes: Setup](./_index#setup). ```python import flyte from flyteplugins.union.io import BlockVolume, ROBlockVolume, ROVolume, RWVolume, allow_volumes env = flyte.TaskEnvironment( name="builds", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-union"), pod_template=allow_volumes(cache_size="50Gi"), resources=flyte.Resources(cpu="4", memory="8Gi"), ) ``` Attaching an image makes the node's kernel parse a file system whose bytes the task controls. The mount broker therefore allows block volumes only for the workloads the cluster administrator permits, by namespace, by service account, or both. By default, a cluster in low-privilege mode allows none and any other cluster allows every pod. If a task isn't allowed, its `mount()` fails with the broker's reason. On a self-managed cluster, see **Self-managed deployment > Advanced configurations > Volumes > Enable the mount broker > Enable block volumes**. > [!NOTE] > **Privileged pods without the broker**, such as a BuildKit builder, can use > block volumes too. The client then attaches the image itself with `losetup` > and `mount`, so the image needs `util-linux` and `e2fsprogs`. The task code is > the same. ## Create and use a block volume `BlockVolume.new()` takes a `size`, the most the file system can hold. The image is **sparse**: only what ext4 actually writes is stored or uploaded, so a generous size costs nothing up front. ```python @env.task async def warm_cache() -> ROBlockVolume: cache = BlockVolume.new(name="go-build-cache", size="64G") root = await cache.mount() # an ext4 mount, used like any directory run_build(gocache=root / "go") return await cache.finalize(message="warm") ``` The first `mount()` creates and formats the image. Sizes use binary units (`"512M"`, `"64G"`, `"1T"`). ## Use it in a later task: fork, then mount `finalize()` and `commit()` on a block volume return an `ROBlockVolume`, the immutable version of a block volume. It is an `ROVolume`, so anything that accepts an `ROVolume` accepts it. Because a block image can only be mounted read-write, a downstream task **forks** it and mounts the fork, even when it only needs to read. The fork is a `BlockVolume` again, and it shares every unchanged block with its parent, so forking a large cache is cheap: ```python @env.task async def build(cache: ROBlockVolume) -> ROBlockVolume: work = await cache.fork(name="go-build-cache") # a writable BlockVolume root = await work.mount() run_build(gocache=root / "go") return await work.finalize(message="after build") ``` Declaring the input as `ROBlockVolume` makes the requirement part of the task signature: passing a regular volume fails at the task boundary, not partway through the task. An input declared `ROVolume` accepts either kind. A block volume still arrives as an `ROBlockVolume`, and `is_block` tells you which kind you received: ```python @env.task async def inspect(vol: ROVolume) -> int: if vol.is_block: # an ROBlockVolume vol = await vol.fork(name="inspect-scratch") # fork to read it root = await vol.mount() return len(list(root.rglob("*"))) ``` Calling `mount()` on an `ROBlockVolume` raises an error that tells you to fork it. ## Checkpoint while you work `commit()` records a version without unmounting, as on any Volume. Before the snapshot the client trims the space ext4 has freed, so deleted files stop costing storage, but only if the image hasn't been trimmed since it was mounted or no trim has finished in the last `UNION_VOLUME_COMMIT_TRIM_INTERVAL_S` seconds (6 hours by default). Otherwise `commit()` skips the trim, and space freed since the last trim is reclaimed by a later trim or by `finalize()`. Requires `flyteplugins-union` 0.18.0 or later; earlier versions trim before every snapshot. ```python await work.commit(message="after step 1") ``` The client runs the first trim after a mount in the background, so that `commit()` usually doesn't have to. Requires `flyteplugins-union` 0.15.5 or later. That first trim walks the whole image, because ext4 forgets what it trimmed when it unmounts. On a large volume this takes tens of seconds. The client runs it 300 seconds after the mount, and every later trim covers only the space freed since. `finalize()` also trims before it unmounts. If the background trim hasn't run yet, or is turned off, the first `commit()` or `finalize()` pays for the full trim itself. Three environment variables control trimming. Set them in the task environment's `env_vars`: | Variable | Default | Effect | |---|---|---| | `UNION_VOLUME_EARLY_TRIM_S` | `300` | Seconds after the mount to run the background trim. `off` disables it. | | `UNION_VOLUME_COMMIT_TRIM_INTERVAL_S` | `21600` | Minimum seconds between the last finished trim and a trim by `commit()`. `0` trims at every `commit()`. Requires `flyteplugins-union` 0.18.0 or later. | | `UNION_VOLUME_TRIM` | on | `0`, `false` or `off` turns off every trim, including the ones by `commit()` and `finalize()`. | By default the snapshot is taken **without pausing writers**. It is *crash-consistent*, like a snapshot of a running disk: when a fork of it is mounted, ext4 replays its journal and the file system is consistent, but a write that was in progress when the snapshot was taken may be missing from it. When you need a clean image instead, for example at a point where you know all writes are complete, pass `freeze=True`: ```python await work.commit(message="release", freeze=True) ``` This freezes the file system for the moment it takes to pin the snapshot: writers wait, then resume before the snapshot is uploaded. If the freeze had to be released early, the commit fails rather than publish a snapshot it can't vouch for. As on every Volume, `commit()`, not `fsync`, is what makes data durable. ## Grow a block volume A block volume that runs out of space fails writes with `ENOSPC`, the same as a full disk. Grow it while it is mounted; the image and the file system grow together, and writers keep running: ```python await work.grow("128G") print(work.size) # "128G" ``` Block volumes never shrink. The new size is recorded on the volume, so its commits and forks keep it. > [!NOTE] > ext4 allocates one inode per 16 KiB of image, so a volume of very many tiny > files can run out of inodes before it runs out of bytes. Growing the volume > adds inodes too. ## Convert between regular and block volumes There is no in-place conversion: the two layouts store data differently and share nothing. Converting creates a new volume and copies every file into it, preserving permissions, timestamps, symlinks and hard links. Top-level entries are copied in parallel (`workers=8` by default), so two hard links under *different* top-level directories become two files; pass `workers=1` to keep every link. ```python @env.task async def to_block(src: ROVolume) -> ROBlockVolume: bv = await BlockVolume.from_volume(src, name="source-tree-blk") return await bv.finalize(message="converted from source-tree") @env.task async def to_regular(src: ROBlockVolume) -> ROVolume: rw = await RWVolume.from_block(src, name="source-tree") return await rw.finalize(message="converted from source-tree-blk") ``` `from_volume` sizes the image from the source's recorded usage, counting both bytes and files, with headroom. Pass `size=` to choose it yourself. Both methods return the new volume already mounted, so you can keep working in it before you finalize it. The source isn't modified. ## Trade-offs - **A size limit.** Choose a generous `size`: an unused size costs nothing. Grow the volume when it fills. - **One writer at a time.** This is true of every mounted Volume, but a block volume also has no read-only mounts. Fork it for every additional reader. - **Only where the cluster allows it.** Attaching an image exposes the node kernel to the task's file system bytes, so administrators of shared clusters may restrict block volumes to trusted workloads. - **More upload on heavy churn.** The client stores the image in fixed-size pieces, and a small change rewrites a whole piece. Workloads that rewrite many files between commits upload more than the same work on a regular Volume. ## Reference - API: `BlockVolume` (`new()`, `commit()`, `grow()`, `from_volume()`), `ROBlockVolume` (`fork()`), `RWVolume.from_block()` and `Volume.is_block`. - Trimming: `$UNION_VOLUME_EARLY_TRIM_S`, `$UNION_VOLUME_COMMIT_TRIM_INTERVAL_S` and `$UNION_VOLUME_TRIM`. See **Tasks > Build tasks > Volumes > Block volumes > Checkpoint while you work**. - The rest of the Volume model (forking, artifacts, locators and the chunk cache) works the same way. See [Volumes](./_index). - Cluster setup: **Self-managed deployment > Advanced configurations > Volumes > Enable the mount broker > Enable block volumes**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/dataclasses-and-structures === Pass dataclasses and Pydantic models between tasks as materialized values. # Data classes and structures Dataclasses and Pydantic models are fully supported in Flyte as **materialized data types**: Structured data where the full content is serialized and passed between tasks. Use these as you would normally, passing them as inputs and outputs of tasks. Unlike **offloaded types** like **Tasks > Build tasks > DataFrames**, **Tasks > Build tasks > Files and directories**, data class and Pydantic model data is fully serialized, stored, and deserialized between tasks. This makes them ideal for configuration objects, metadata, and smaller structured data where all fields should be serializable. ## Example: Combining dataclasses and Pydantic models This example demonstrates how data classes and Pydantic models work together as materialized data types, showing nested structures and batch processing patterns: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # "pydantic", # ] # main = "main" # params = "" # /// import asyncio from dataclasses import dataclass from typing import List from pydantic import BaseModel import flyte env = flyte.TaskEnvironment(name="ex-mixed-structures") @dataclass class InferenceRequest: feature_a: float feature_b: float @dataclass class BatchRequest: requests: List[InferenceRequest] batch_id: str = "default" class PredictionSummary(BaseModel): predictions: List[float] average: float count: int batch_id: str @env.task async def predict_one(request: InferenceRequest) -> float: """ A dummy linear model: prediction = 2 * feature_a + 3 * feature_b + bias(=1.0) """ return 2.0 * request.feature_a + 3.0 * request.feature_b + 1.0 @env.task async def process_batch(batch: BatchRequest) -> PredictionSummary: """ Processes a batch of inference requests and returns summary statistics. """ # Process all requests concurrently tasks = [predict_one(request=req) for req in batch.requests] predictions = await asyncio.gather(*tasks) # Calculate statistics average = sum(predictions) / len(predictions) if predictions else 0.0 return PredictionSummary( predictions=predictions, average=average, count=len(predictions), batch_id=batch.batch_id ) @env.task async def summarize_results(summary: PredictionSummary) -> str: """ Creates a text summary from the prediction results. """ return ( f"Batch {summary.batch_id}: " f"Processed {summary.count} predictions, " f"average value: {summary.average:.2f}" ) @env.task async def main() -> str: batch = BatchRequest( requests=[ InferenceRequest(feature_a=1.0, feature_b=2.0), InferenceRequest(feature_a=3.0, feature_b=4.0), InferenceRequest(feature_a=5.0, feature_b=6.0), ], batch_id="demo_batch_001" ) summary = await process_batch(batch) result = await summarize_results(summary) return result if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataclasses-and-structures/example.py* === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/dataframes === Pass DataFrames between tasks by reference instead of materializing them. # DataFrames By default, return values in Python are materialized - meaning the actual data is downloaded and loaded into memory. This applies to simple types like integers, as well as more complex types like DataFrames. To avoid downloading large datasets into memory, Flyte V2 exposes **Flyte SDK > flyte.io > DataFrame**: a thin, uniform wrapper type for DataFrame-style objects that allows you to pass a reference to the data, rather than the fully materialized contents. The `flyte.io.DataFrame` type provides built-in serialization for `pandas` and `pyarrow`, and plugins such as `flyteplugins-polars` add more engines. This lets you move data between different DataFrame backends. DataFrame contents are written to the data plane object store and passed between tasks by reference. For the full map of what goes in the bucket versus what stays in the control plane database, see **Get started > Core concepts > Where your data lives**. > [!NOTE] > Because a DataFrame is passed by reference, a downstream cached task does not get a cache hit on identical content stored at a new path. To cache on content, attach a hash with `flyte.io.HashFunction` - see **Tasks > Configure tasks > Caching > Content-based caching for DataFrames, files, and directories**. ## Setting up the environment and sample data For our example we will start by setting up our task environment with the required dependencies and create some sample data. ``` from typing import Annotated import numpy as np import pandas as pd import flyte import flyte.io env = flyte.TaskEnvironment( "dataframe_usage", image= flyte.Image.from_debian_base().with_pip_packages("pandas", "pyarrow", "numpy"), resources=flyte.Resources(cpu="1", memory="2Gi"), ) BASIC_EMPLOYEE_DATA = { "employee_id": range(1001, 1009), "name": ["Alice", "Bob", "Charlie", "Diana", "Ethan", "Fiona", "George", "Hannah"], "department": ["HR", "Engineering", "Engineering", "Marketing", "Finance", "Finance", "HR", "Engineering"], "hire_date": pd.to_datetime( ["2018-01-15", "2019-03-22", "2020-07-10", "2017-11-01", "2021-06-05", "2018-09-13", "2022-01-07", "2020-12-30"] ), } ADDL_EMPLOYEE_DATA = { "employee_id": range(1001, 1009), "salary": [55000, 75000, 72000, 50000, 68000, 70000, np.nan, 80000], "bonus_pct": [0.05, 0.10, 0.07, 0.04, np.nan, 0.08, 0.03, 0.09], "full_time": [True, True, True, False, True, True, False, True], "projects": [ ["Recruiting", "Onboarding"], ["Platform", "API"], ["API", "Data Pipeline"], ["SEO", "Ads"], ["Budget", "Forecasting"], ["Auditing"], [], ["Platform", "Security", "Data Pipeline"], ], } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/dataframes.py* ## Create a raw DataFrame Now, let's create a task that returns a native Pandas DataFrame: ``` @env.task async def create_raw_dataframe() -> pd.DataFrame: return pd.DataFrame(BASIC_EMPLOYEE_DATA) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/dataframes.py* This is the most basic use-case of how to pass DataFrames (of all kinds, not just Pandas). We simply create the DataFrame as normal, and return it. Because the task has been declared to return a supported native DataFrame type (in this case `pandas.DataFrame`), Flyte will automatically detect it, serialize it correctly and upload it at task completion enabling it to be passed transparently to the next task. Flyte supports auto-serialization for the following DataFrame types: * `pandas.DataFrame` * `pyarrow.Table` * `polars.DataFrame` and `polars.LazyFrame` (requires `flyteplugins-polars`; see **Tasks > Build tasks > DataFrames > Polars DataFrames**) * `flyte.io.DataFrame` (see below) ## Create a flyte.io.DataFrame Alternatively you can also create a `flyte.io.DataFrame` object directly from a native object with the `from_df` method: ``` @env.task async def create_flyte_dataframe() -> Annotated[flyte.io.DataFrame, "parquet"]: pd_df = pd.DataFrame(ADDL_EMPLOYEE_DATA) fdf = flyte.io.DataFrame.from_df(pd_df) return fdf ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/dataframes.py* The `flyte.io.DataFrame` class creates a thin wrapper around objects of any standard DataFrame type. It serves as a generic "any DataFrame type" (a concept that Python itself does not currently offer). As with native DataFrame types, Flyte will automatically serialize and upload the data at task completion. The advantage of the unified `flyte.io.DataFrame` wrapper is that you can be explicit about the storage format that makes sense for your use case, by using an `Annotated` type where the second argument encodes format or other lightweight hints. The example above does this: its return type, `Annotated[flyte.io.DataFrame, "parquet"]`, stores the DataFrame as Parquet. ## Automatically convert between types You can use Flyte to automatically download and convert the DataFrame between types when needed: ``` @env.task async def join_data(raw_dataframe: pd.DataFrame, flyte_dataframe: pd.DataFrame) -> flyte.io.DataFrame: joined_df = raw_dataframe.merge(flyte_dataframe, on="employee_id", how="inner") return flyte.io.DataFrame.from_df(joined_df) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/dataframes.py* This task takes two DataFrames as input. We'll pass one raw Pandas DataFrame, and one `flyte.io.DataFrame`. Flyte automatically converts the `flyte.io.DataFrame` to a Pandas DataFrame (since we declared that as the input type) before passing it to the task. The actual download and conversion happens only when we access the data, in this case, when we do the merge. ## Downloading DataFrames When a task receives a `flyte.io.DataFrame`, you can request a concrete backend representation. For example, to download as a pandas DataFrame: ``` @env.task async def download_data(joined_df: flyte.io.DataFrame): downloaded = await joined_df.open(pd.DataFrame).all() print("Downloaded Data:\n", downloaded) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/dataframes.py* The `open()` call delegates to the DataFrame handler for the stored format and converts to the requested in-memory type. ## Run the example Finally, we can define a `main` function to run the tasks defined above and a `__main__` block to execute the workflow: ``` @env.task async def main(): raw_df = await create_raw_dataframe () flyte_df = await create_flyte_dataframe () joined_df = await join_data (raw_df, flyte_df) await download_data (joined_df) if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/dataframes.py* ## Polars DataFrames The `flyteplugins-polars` package extends Flyte's DataFrame support to `polars.DataFrame` and `polars.LazyFrame`. Install it alongside the core SDK and it registers automatically. No additional configuration required. ```bash pip install flyteplugins-polars ``` Both types are serialized as Parquet when passed between tasks, just like other DataFrame backends. ### Setup ``` import polars as pl import flyte env = flyte.TaskEnvironment( name="polars-dataframes", image=flyte.Image.from_debian_base(name="polars").with_pip_packages( "flyteplugins-polars>=2.0.0", "polars" ), resources=flyte.Resources(cpu="1", memory="2Gi"), ) EMPLOYEE_DATA = { "employee_id": [1001, 1002, 1003, 1004, 1005, 1006], "name": ["Alice", "Bob", "Charlie", "Diana", "Ethan", "Fiona"], "department": ["Engineering", "Engineering", "Marketing", "Finance", "Finance", "Engineering"], "salary": [75000, 72000, 50000, 68000, 70000, 80000], "years_experience": [5, 4, 2, 6, 5, 7], } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/polars_dataframes.py* ### Eager DataFrames Use `pl.DataFrame` when you want immediate evaluation. Flyte serializes it to Parquet on output and deserializes it on input: ``` @env.task async def create_dataframe() -> pl.DataFrame: """Create a Polars DataFrame. Polars DataFrames are passed between tasks as serialized Parquet files stored in the Flyte blob store โ€” no manual upload required. """ return pl.DataFrame(EMPLOYEE_DATA) @env.task async def filter_high_earners(df: pl.DataFrame) -> pl.DataFrame: """Filter and enrich a Polars DataFrame.""" return ( df.filter(pl.col("salary") > 60000) .with_columns( (pl.col("salary") / pl.col("years_experience")).alias("salary_per_year") ) .sort("salary", descending=True) ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/polars_dataframes.py* ### Lazy DataFrames Use `pl.LazyFrame` when you want to defer computation and let Polars optimize the full query plan before executing. Flyte handles serialization the same way as `pl.DataFrame`: ``` @env.task async def create_lazyframe() -> pl.LazyFrame: """Create a Polars LazyFrame. LazyFrames defer computation until collected, allowing Polars to optimize the full query plan. They are serialized to Parquet just like DataFrames when passed between tasks. """ return pl.LazyFrame(EMPLOYEE_DATA) @env.task async def aggregate_by_department(lf: pl.LazyFrame) -> pl.DataFrame: """Aggregate salary statistics by department using a LazyFrame. The query plan is built lazily and executed only when collect() is called. """ return ( lf.group_by("department") .agg( pl.col("salary").mean().alias("avg_salary"), pl.col("salary").max().alias("max_salary"), pl.len().alias("headcount"), ) .sort("avg_salary", descending=True) .collect() ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/polars_dataframes.py* The `collect()` call in `aggregate_by_department` is what triggers execution of the lazy plan. The `LazyFrame` passed between tasks is serialized as Parquet at that point. ### Run the example ``` @env.task async def main(): df = await create_dataframe() filtered = await filter_high_earners(df=df) print("High earners:") print(filtered) lf = await create_lazyframe() summary = await aggregate_by_department(lf=lf) print("Department summary:") print(summary) if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/dataframes/polars_dataframes.py* ## Lance datasets The `flyteplugins-lance` package adds a `lance` format to `flyte.io.DataFrame`, letting a `lance.LanceDataset` move between tasks. Like the Polars plugin, it registers itself on install. ```bash pip install flyteplugins-lance ``` Declare `lance.LanceDataset` on the receiving task and, unlike the Parquet-backed types above, nothing is materialized: the task gets a live handle and streams from it. ``` import tempfile import lance import pyarrow as pa @env.task async def build_dataset(n: int = 10_000) -> lance.LanceDataset: uri = f"{tempfile.mkdtemp()}/points.lance" lance.write_dataset(pa.table({"id": list(range(n)), "value": [i * i for i in range(n)]}), uri) return lance.dataset(uri) @env.task async def summarize(ds: lance.LanceDataset) -> dict: # `ds` is a live handle. Stream it in batches; nothing is materialized whole. total = 0 for batch in ds.scanner(columns=["value"], batch_size=1024).to_batches(): total += sum(batch.column("value").to_pylist()) return {"rows": ds.count_rows(), "sum_of_values": total} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/lance/lance_example.py* Reach for it when a task wants scattered rows instead of all of them: shuffled training batches, point lookups by id, vector similarity search. Returning a handful of rows costs Parquet a whole row group, and costs Flyte's Parquet decoder the entire table. Lance reads the rows you asked for. One thing to know before you commit to it: a `lance` input can only arrive as a `lance.LanceDataset` or a `pyarrow.Table`, and the `pyarrow.Table` decoder reads the whole dataset into memory, so streaming is the `lance.LanceDataset` path specifically. There is no lance-to-pandas handler either, so declaring `pd.DataFrame` fails at the task boundary. The [Lance integration](../../../integrations/lance/_index) page has the workaround, along with multimodal and blob-encoded columns, predicate pushdown, fragment-parallel reads, and why a dataset carrying indices has to be handed off by reference. ## See also To display a DataFrame as an HTML table in a task report, define a `flyte.types.Renderable` for it โ€” see **Tasks > Build tasks > Reports > Rendering a custom type** on the Reports page. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/handling-custom-types === Teach Flyte to serialize a type its type system does not already handle. # Custom types Flyte has a rich type system that handles most Python types automatically. However, there are cases where you may want to pass custom types into a run or between actions. By default, if Flyte doesn't recognize a type, it uses Python pickle to serialize the data. While this works, pickle has several drawbacks: - **Inefficiency**: Pickle can be very inefficient for certain data types - **Language compatibility**: Pickle is Python-specific and doesn't work with other languages - **Version fragility**: Pickled data can break between Python versions - **Opacity**: Pickled data appears as bytes or file links in the UI, with no automatic form generation Consider types like Polars DataFrames or PyTorch Tensors. Using pickle for these is extremely inefficient compared to native serialization formats like Parquet or tensor-specific formats. Flyte SDK addresses this by allowing you to create and share type extensions. ## Types of extensions Flyte supports two types of type extensions: 1. **Type transformers**: For scalar types (integers, strings, files, directories, custom objects) 2. **DataFrame extensions**: For tabular data types that benefit from DataFrame-specific handling DataFrame types are special because they have associated metadata (columns, schemas), can be serialized to efficient formats like Parquet, support parallel uploads from engines like Spark, and can be partitioned. ## Creating a type transformer Type transformers convert between Python types and Flyte's internal representation. Here's how to create one for a custom `PositiveInt` type. ### Step 1: Define your custom type ```python # custom_type.py class PositiveInt: """A wrapper type that only accepts positive integers.""" def __init__(self, value: int): if not isinstance(value, int): raise TypeError(f"Expected int, got {type(value).__name__}") if value <= 0: raise ValueError(f"Expected positive integer, got {value}") self._value = value @property def value(self) -> int: return self._value def __repr__(self) -> str: return f"PositiveInt({self._value})" ``` ### Step 2: Create the type transformer ```python # transformer.py from typing import Type from flyteidl2.core import literals_pb2, types_pb2 from flyte import logger from flyte.types import TypeEngine, TypeTransformer, TypeTransformerFailedError from my_transformer.custom_type import PositiveInt class PositiveIntTransformer(TypeTransformer[PositiveInt]): """ Type transformer for PositiveInt that validates and transforms positive integers. """ def __init__(self): super().__init__(name="PositiveInt", t=PositiveInt) def get_literal_type(self, t: Type[PositiveInt]) -> types_pb2.LiteralType: """Returns the Flyte literal type for PositiveInt.""" return types_pb2.LiteralType( simple=types_pb2.SimpleType.INTEGER, structure=types_pb2.TypeStructure(tag="PositiveInt"), ) async def to_literal( self, python_val: PositiveInt, python_type: Type[PositiveInt], expected: types_pb2.LiteralType, ) -> literals_pb2.Literal: """Converts a PositiveInt instance to a Flyte Literal.""" if not isinstance(python_val, PositiveInt): raise TypeTransformerFailedError( f"Expected PositiveInt, got {type(python_val).__name__}" ) return literals_pb2.Literal( scalar=literals_pb2.Scalar( primitive=literals_pb2.Primitive(integer=python_val.value) ) ) async def to_python_value( self, lv: literals_pb2.Literal, expected_python_type: Type[PositiveInt] ) -> PositiveInt: """Converts a Flyte Literal back to a PositiveInt instance.""" if not lv.scalar or not lv.scalar.primitive: raise TypeTransformerFailedError( f"Cannot convert literal {lv} to PositiveInt: missing scalar primitive" ) value = lv.scalar.primitive.integer try: return PositiveInt(value) except (TypeError, ValueError) as e: raise TypeTransformerFailedError( f"Cannot convert value {value} to PositiveInt: {e}" ) def guess_python_type( self, literal_type: types_pb2.LiteralType ) -> Type[PositiveInt]: """Guesses the Python type from a Flyte literal type.""" if ( literal_type.simple == types_pb2.SimpleType.INTEGER and literal_type.structure and literal_type.structure.tag == "PositiveInt" ): return PositiveInt raise ValueError(f"Cannot guess PositiveInt from literal type {literal_type}") ``` ### Step 3: Register the transformer Create a registration function that can be called to register your transformer: ```python def register_positive_int_transformer(): """Register the PositiveIntTransformer in the TypeEngine.""" TypeEngine.register(PositiveIntTransformer()) logger.info("Registered PositiveIntTransformer in TypeEngine") ``` ## Distributing type plugins To share your type transformer as an installable package, configure it as a Flyte plugin using entry points. ### Configure pyproject.toml Add the entry point to your `pyproject.toml`: ```toml [project] name = "my_transformer" version = "0.1.0" description = "Custom type transformer" requires-python = ">=3.10" dependencies = [] [project.entry-points."flyte.plugins.types"] my_transformer = "my_transformer.transformer:register_positive_int_transformer" ``` The entry point group `flyte.plugins.types` tells Flyte to automatically load this transformer when the package is installed. ### Automatic loading When your plugin package is installed, Flyte automatically loads the type transformer at runtime. This happens during `flyte.init()` or `flyte.init_from_config()`. ## Controlling plugin loading Loading many type plugins can add overhead to initialization. You can disable automatic plugin loading: ```python import flyte # Disable automatic loading of type transformer plugins flyte.init(load_plugin_type_transformers=False) ``` By default, `load_plugin_type_transformers` is `True`. ## Using custom types in tasks Once registered, use your custom type like any built-in type: ```python import flyte from my_transformer.custom_type import PositiveInt env = flyte.TaskEnvironment(name="custom_types") @env.task async def process_positive(value: PositiveInt) -> int: """Process a positive integer.""" return value.value * 2 if __name__ == "__main__": flyte.init_from_config() # The custom type works seamlessly run = flyte.run(process_positive, value=PositiveInt(42)) run.wait() print(run.outputs()[0]) # 84 ``` ## DataFrame extensions For tabular data types, Flyte provides a specialized extension mechanism through `flyte.io.DataFrame`. DataFrame extensions support: - Automatic conversion to/from Parquet format - Column metadata and schema information - Parallel uploads from distributed engines - Partitioning support DataFrame extensions use encoders and decoders from `flyte.io.extend`. Documentation for creating DataFrame extensions is coming soon. ## Best practices 1. **Use specific types over pickle**: Define type transformers for any custom types used frequently in your workflows 2. **Keep transformers lightweight**: Avoid expensive operations in `to_literal` and `to_python_value` 3. **Add validation**: Validate data in your transformer to catch errors early 4. **Use meaningful tags**: The `TypeStructure.tag` helps identify your type in the Flyte UI 5. **Be judicious with plugins**: Only install the plugins you need to minimize initialization overhead ## See also To render a custom type as HTML in a task report, define a `flyte.types.Renderable` for it โ€” see **Tasks > Build tasks > Reports > Rendering a custom type** on the Reports page. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/custom-context === Pass configuration through a task hierarchy without threading it through every signature. # Custom context Custom context provides a mechanism for implicitly passing configuration and metadata through your entire task execution hierarchy without adding parameters to every task. It is ideal for cross-cutting concerns such as tracing, environment metadata, or experiment identifiers. Think of custom context as **execution-scoped metadata** that automatically flows from parent to child tasks. > **๐Ÿ“ Note** > > In Flyte 1 the runtime context was accessed with `current_context()` (the `flytekit.current_context` API). Flyte 2 uses `flyte.ctx()`, shown below. ## Overview Custom context is an implicit key-value configuration map that is automatically available to tasks during execution. It is stored in the blob store of your Union/Flyte instance together with the taskโ€™s inputs, making it available across tasks without needing to pass it explicitly. You can access it in a Flyte task via: ```python flyte.ctx().custom_context ``` Custom context is fundamentally different from standard task inputs. Task inputs are explicit, strongly typed parameters that you declare as part of a taskโ€™s signature. They directly influence the taskโ€™s computation and therefore participate in Flyteโ€™s caching and reproducibility guarantees. Custom context, on the other hand, is implicit metadata. It consists only of string key/value pairs, is not part of the task signature, and does not affect task caching. Because it is injected by the Flyte runtime rather than passed as a formal input, it should be used only for environmental or contextual information, not for data that changes the logical output of a task. ## When to use it and when not to Custom context is perfect when you need metadata, not domain data, to flow through your tasks. Good use cases: - Tracing IDs, span IDs - Experiment or run metadata - Environment region, cluster ID - Logging correlation keys - Feature flags - Session IDs for 3rd-party APIs (e.g., an LLM session) Avoid using for: - Business/domain data - Inputs that change task outputs - Anything affecting caching or reproducibility - Large blobs of data (keep it small) It is the cleanest mechanism when you need something available everywhere, but not logically an input to the computation. ## Setting custom context There are two ways to set custom context for a Flyte run: 1. Set it once for the entire run when you launch (`with_runcontext`, or the `flyte run` flags in **Tasks > Build tasks > Custom context > Setting custom context > From the CLI**): this establishes the base context for the execution 2. Set or override it inside task code using `flyte.custom_context(...)` context manager: this changes the active context for that task block and any nested tasks called from it Both are legitimate and complementary. The important behavioral rules to understand are: - `with_runcontext(...)` sets the run-level base. Values provided here are available everywhere unless overridden later. Use this for metadata that should apply to most or all tasks in the run (experiment name, top-level trace id, run id, etc.). - `flyte.custom_context(...)` is used inside task code to set or override values for that scope. It does affect nested tasks invoked while that context is active. In practice this means you can override run-level entries, add new keys for downstream tasks, or both. - Merging & precedence: contexts are merged; when the same key appears in multiple places the most recent/innermost value wins (i.e., values set by `flyte.custom_context(...)` override the run-level values from `with_runcontext(...)` for the duration of that block). ### Run-level context Set base metadata once when starting the run: ``` import flyte env = flyte.TaskEnvironment("custom-context-example") @env.task async def leaf_task() -> str: # Reads run-level context print("leaf sees:", flyte.ctx().custom_context) return flyte.ctx().custom_context.get("trace_id") @env.task async def root() -> str: return await leaf_task() if __name__ == "__main__": flyte.init_from_config() # Base context for the entire run flyte.with_runcontext(custom_context={"trace_id": "root-abc", "experiment": "v1"}).run(root) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/custom-context/run_context.py* Output (every task sees the base keys unless overridden): ```bash leaf sees: {"trace_id": "root-abc", "experiment": "v1"} ``` ### From the CLI Set the run-level context from `flyte run` with two repeatable flags. Both require `flyte` 2.12.2 or later. - `--custom-context KEY=VALUE` sets a key to a literal value. Everything after the first `=` is the value. - `--custom-context-from-env VAR` sets key `VAR` to the value of the local environment variable `VAR`. Use `KEY=VAR` to store it under a different key. The command fails if `VAR` is not set. ```bash flyte run \ --custom-context experiment=calibration \ --custom-context-from-env API_BASE_URL \ deployed-task my_env.my_task:v1 ``` For file tasks, `--local` and `--tui` runs, and `deployed-task`, the flags pass the merged values to `with_runcontext(custom_context=...)`, the same as setting them from Python. - If both flags set the same key, `--custom-context` wins. - Keys reserved by Flyte are rejected with `Custom context key(s) [...] are reserved by Flyte.` - Custom context is stored as run metadata. Don't use it for secrets. ### Overriding inside a task (local override that affects nested tasks) Use `flyte.custom_context(...)` inside a task to override or add keys for downstream calls: ``` @env.task async def downstream() -> str: print("downstream sees:", flyte.ctx().custom_context) return flyte.ctx().custom_context.get("trace_id") @env.task async def parent() -> str: print("parent initial:", flyte.ctx().custom_context) # Override the trace_id for the nested call(s) with flyte.custom_context(trace_id="child-override"): val = await downstream() # downstream sees trace_id="child-override" # After the context block, run-level values are back print("parent after:", flyte.ctx().custom_context) return val ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/custom-context/override_context.py* If the run was started with `{"trace_id": "root-abc"}`, this prints: ```bash parent initial: {"trace_id": "root-abc"} downstream sees: {"trace_id": "child-override"} parent after: {"trace_id": "root-abc"} ``` Note that the override affected the nested downstream task because it was invoked while the `flyte.custom_context` block was active. ### Adding new keys for nested tasks You can add keys (not just override): ```python with flyte.custom_context(experiment="exp-blue", run_group="g-7"): await some_task() # some_task sees both base keys + the new keys ``` ## Accessing custom context Always via the Flyte runtime: ```python ctx = flyte.ctx().custom_context value = ctx.get("key") ``` You can access the custom context using either `flyte.ctx().custom_context` or the shorthand `flyte.get_custom_context()`, which returns the same dictionary of key/value pairs. Values are always strings, so parse as needed: ```python timeout = int(ctx["timeout_seconds"]) ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/abort-tasks === Stop actions that are no longer needed while a run is still going. # Abort and cancel actions When running complex workflows, you may need to stop actions that are no longer needed. This can happen when one branch of your workflow makes others redundant, when a task fails and its siblings should not continue, or when you need to manually intervene in a running workflow. Flyte provides three mechanisms for stopping actions: - **Automatic cleanup**: When a root action completes, all its in-progress descendant actions are automatically aborted. - **Programmatic cancellation**: Cancel specific `asyncio` tasks from within your workflow code. - **External abort**: Stop individual actions via the CLI, the UI, or the API. For background on runs and actions, see **Get started > Core concepts > Runs and actions**. ## Action lifetime The lifetime of all actions in a **Get started > Core concepts > Runs and actions** is tied to the lifetime of the root action (the first task that was invoked). When the root action exits (whether it succeeds, fails, or returns early) all in-progress descendant actions are automatically aborted and no new actions can be enqueued. This means you don't need to manually clean up child actions. Flyte handles it for you. Consider this example where `main` exits after 10 seconds, but it has spawned a `sleep_for` action that is set to run for 30 seconds: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # main = "main" # params = "seconds = 30" # /// import asyncio import flyte env = flyte.TaskEnvironment(name="action_lifetime") @env.task async def do_something(): print("Doing something") await asyncio.sleep(5) print("Finished doing something") @env.task async def sleep_for(seconds: int): print(f"Sleeping for {seconds} seconds") try: await asyncio.sleep(seconds) await do_something() except asyncio.CancelledError: print("sleep_for was cancelled") return print(f"Finished sleeping for {seconds} seconds") @env.task async def main(seconds: int): print("Starting main") asyncio.create_task(sleep_for(seconds)) await asyncio.sleep(10) print("Main finished") if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, seconds=30) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/abort-tasks/action_lifetime.py* When `main` returns after 10 seconds, the `sleep_for` action (which still has 20 seconds remaining) is automatically aborted. The `sleep_for` task receives an `asyncio.CancelledError`, giving it a chance to handle the cancellation gracefully. ## Canceling actions programmatically As a workflow author, you can cancel specific in-progress actions by canceling their corresponding `asyncio` tasks. This is useful in scenarios like hyperparameter optimization (HPO), where one action converges to the desired result and the remaining actions can be stopped to save compute. To cancel actions programmatically: 1. Launch actions using `asyncio.create_task()` and retain references to the returned task objects. 2. When the desired condition is met, call `.cancel()` on the tasks you want to stop. ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # main = "main" # params = "n = 30, f = 10.0" # /// import asyncio import flyte import flyte.errors env = flyte.TaskEnvironment("cancel") @env.task async def sleepers(f: float, n: int): await asyncio.sleep(f) @env.task async def failing_task(f: float): raise ValueError("I will fail!") @env.task async def main(n: int, f: float): sleeping_tasks = [] for i in range(n): sleeping_tasks.append(asyncio.create_task(sleepers(f, i))) await asyncio.sleep(f) try: await failing_task(f) await asyncio.gather(*sleeping_tasks) except flyte.errors.RuntimeUserError as e: if e.code == "ValueError": print(f"Received ValueError, canceling {len(sleeping_tasks)} sleeping tasks") for t in sleeping_tasks: t.cancel() return if __name__ == "__main__": flyte.init_from_config() print(flyte.run(main, 30, 10.0)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/abort-tasks/cancel_tasks.py* In this code: * The `main` task launches 30 `sleepers` actions in parallel using `asyncio.create_task()`. * It then calls `failing_task`, which raises a `ValueError`. * The error is caught as a `flyte.errors.RuntimeUserError` (since user-raised exceptions are wrapped by Flyte). * On catching the error, `main` cancels all sleeping tasks by calling `.cancel()` on each one, freeing their compute resources. This pattern lets you react to runtime conditions and stop unnecessary work. For more on handling errors within workflows, see **Tasks > Build tasks > Error handling**. ## External abort Sometimes you need to stop an action manually, outside the workflow code itself. You can abort individual actions using the CLI, the UI, or the API. When an action is externally aborted, the parent action that awaits it receives a `flyte.errors.ActionAbortedError`. You can catch this error to handle the abort gracefully. ### Aborting via the CLI To abort a specific action: ```bash flyte abort ``` Use `--project` and `--domain` to target a specific **Get started > Core concepts > Projects and domains**. For all available options, see the **Flyte CLI > flyte > flyte abort**. ### Handling external aborts When using `asyncio.gather()` with `return_exceptions=True`, externally aborted actions return an `ActionAbortedError` instead of raising it. This lets you inspect results and handle aborts on a per-action basis: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # main = "main" # params = "n = 10, sleep_for = 30.0" # /// import asyncio import flyte import flyte.errors env = flyte.TaskEnvironment("external_abort") @env.task async def long_sleeper(sleep_for: float): await asyncio.sleep(sleep_for) @env.task async def main(n: int, sleep_for: float) -> str: coros = [long_sleeper(sleep_for) for _ in range(n)] results = await asyncio.gather(*coros, return_exceptions=True) for i, r in enumerate(results): if isinstance(r, flyte.errors.ActionAbortedError): print(f"Action [{i}] was externally aborted") return "Hello World!" if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, 10, 30.0) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/abort-tasks/external_abort.py* In this code: * The `main` task launches 10 `long_sleeper` actions in parallel. * If any action is externally aborted (via the CLI, the UI, or the API) while running, `asyncio.gather` captures the `ActionAbortedError` as a result instead of propagating it. * The `main` task iterates over the results and logs which actions were aborted. * Because the abort is handled, `main` can continue executing and return its result normally. Without `return_exceptions=True`, an external abort would raise `ActionAbortedError` directly, which you can handle with a standard `try...except` block. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/container-tasks === Run any container image as a task, with no Flyte SDK installed inside it. Container tasks are one of Flyte's superpowers. They allow you to execute tasks using any container image without requiring the Flyte SDK to be installed in that container. This means you can run code written in any language, execute shell scripts, or even use pre-built containers pulled directly from the internet while still maintaining Flyte's data orchestration capabilities. ## What are container tasks? A container task is a special type of Flyte task that executes arbitrary container images. Unlike standard `@task` decorated functions that require the Flyte SDK, container tasks can run: - Code written in any programming language (Rust, Go, Java, R, etc.) - Legacy containers with unsupported Python versions - Pre-built bioinformatics or scientific computing containers - Shell scripts and command-line tools - Dynamically generated code in sandboxed environments ## How data flows in and out The magic of container tasks lies in Flyte's **copilot sidecar system**. When you execute a container task, Flyte: 1. Launches your specified container alongside a copilot sidecar container 2. Uses shared Kubernetes pod volumes to pass data between containers 3. Reads inputs from `input_data_dir` and writes outputs to `output_data_dir` 4. Automatically handles serialization and deserialization of typed data This means you can construct workflows where some tasks are container tasks while others are Python functions, and data will flow between them. ## Basic usage Here's a simple example that runs a shell command in an Alpine container: ```python import flyte from flyte.extras import ContainerTask greeting_task = ContainerTask( name="echo_and_return_greeting", image=flyte.Image.from_base("alpine:3.18"), input_data_dir="/var/inputs", output_data_dir="/var/outputs", inputs={"name": str}, outputs={"greeting": str}, command=[ "/bin/sh", "-c", "echo 'Hello, my name is {{.inputs.name}}.' | tee -a /var/outputs/greeting" ], ) ``` ### Template syntax for inputs Container tasks support template-style references to inputs using the syntax `{{.inputs.}}`. This gets replaced with the actual input value at runtime: ```python command=["/bin/sh", "-c", "echo 'Processing {{.inputs.user_id}}' > /var/outputs/result"] ``` ### Using container tasks in workflows Container tasks integrate with Python tasks: ```python container_env = flyte.TaskEnvironment.from_task("container_env", greeting_task) env = flyte.TaskEnvironment(name="hello_world", depends_on=[container_env]) @env.task async def say_hello(name: str = "flyte") -> str: print("Hello container task") return await greeting_task(name=name) ``` ## Advanced: Passing files and directories Container tasks can accept `File` and `Dir` inputs. For these types, use path-based syntax (not template syntax) in your commands: ```python from flyte.io import File import pathlib code_runner = ContainerTask( name="python_code_runner", image="ghcr.io/astral-sh/uv:debian-slim", input_data_dir="/var/inputs", output_data_dir="/var/outputs", inputs={"script.py": File, "a": int, "b": int}, outputs={"result": int}, command=[ "/bin/sh", "-c", "uv run /var/inputs/script.py {{.inputs.a}} {{.inputs.b}} > /var/outputs/result" ], ) @env.task async def execute_script() -> int: path = pathlib.Path(__file__).parent / "my_script.py" script_file = await File.from_local(path) return await code_runner(**{"script.py": script_file, "a": 10, "b": 20}) ``` Note that when passing files, the input key can include the filename (e.g., `"script.py"`), and you reference it in the command as `/var/inputs/script.py`. ## Use case: Agentic sandbox execution Container tasks are perfect for running AI-generated code in isolated environments. You can generate a data analysis script dynamically and execute it safely: ```python import flyte from flyte.extras import ContainerTask from flyte.io import File import pathlib env = flyte.TaskEnvironment(name="agentic_sandbox") @env.task async def run_generated_code(script_content: str, param_a: int, param_b: int) -> int: # Define a container task that runs arbitrary Python code sandbox = ContainerTask( name="code_sandbox", image="ghcr.io/astral-sh/uv:debian-slim", input_data_dir="/var/inputs", output_data_dir="/var/outputs", inputs={"script": File, "a": int, "b": int}, outputs={"result": int}, command=[ "/bin/sh", "-c", "uv run --script /var/inputs/script {{.inputs.a}} {{.inputs.b}} > /var/outputs/result" ], ) # Save the generated script to a temporary file temp_path = pathlib.Path("/tmp/generated_script.py") temp_path.write_text(script_content) # Execute it in the sandbox script_file = await File.from_local(temp_path) return await sandbox(script=script_file, a=param_a, b=param_b) ``` This pattern allows you to: - Generate code using LLMs or other AI systems - Execute it in a controlled, isolated environment - Capture results and integrate them back into your workflow - Maintain full observability and reproducibility ## Use case: Legacy and specialized containers Many scientific and bioinformatics tools are distributed as pre-built containers. Container tasks let you integrate them directly: ```python # Run a bioinformatics tool blast_task = ContainerTask( name="run_blast", image="ncbi/blast:latest", input_data_dir="/data", output_data_dir="/results", inputs={"query": File, "database": str}, outputs={"alignments": File}, command=[ "blastn", "-query", "/data/query", "-db", "{{.inputs.database}}", "-out", "/results/alignments", "-outfmt", "6" ], ) # Run legacy code with an old Python version legacy_task = ContainerTask( name="legacy_python", image="python:2.7", # Unsupported Python version input_data_dir="/app/inputs", output_data_dir="/app/outputs", inputs={"data_file": File}, outputs={"processed": File}, command=[ "python", "/legacy_app/process.py", "/app/inputs/data_file", "/app/outputs/processed" ], ) ``` ## Use case: Multi-language workflows Build workflows that span multiple languages: ```python # Rust task for high-performance computation rust_task = ContainerTask( name="rust_compute", image="rust:1.75", inputs={"n": int}, outputs={"result": int}, input_data_dir="/inputs", output_data_dir="/outputs", command=["./compute_binary", "{{.inputs.n}}"], ) # Python task for orchestration @env.task async def multi_lang_workflow(iterations: int) -> dict: # Call Rust task for heavy computation computed = await rust_task(n=iterations) # Process results in Python processed = await python_analysis_task(computed) return {"rust_result": computed, "analysis": processed} ``` ## Configuration options ### ContainerTask parameters - **name**: Unique identifier for the task - **image**: Container image to use (string or `Image` object) - **command**: Command to execute in the container (list of strings) - **inputs**: Dictionary mapping input names to types - **outputs**: Dictionary mapping output names to types - **input_data_dir**: Directory where Flyte writes input data (default: `/var/inputs`) - **output_data_dir**: Directory where Flyte reads output data (default: `/var/outputs`) - **arguments**: Additional command arguments (list of strings) - **metadata_format**: Format for metadata serialization (`"JSON"`, `"YAML"`, or `"PROTO"`) - **local_logs**: Whether to print container logs during local execution (default: `True`) ### Supported input/output types Container tasks support all standard Flyte types: - Primitives: `str`, `int`, `float`, `bool` - Temporal: `datetime.datetime`, `datetime.timedelta` - File system: `File`, `Dir` - Complex types: dataclasses, Pydantic models (serialized as JSON/YAML/PROTO) ## Best practices 1. **Use specific image tags**: Prefer `alpine:3.18` over `alpine:latest` for reproducibility 2. **Keep containers focused**: Each container task should do one thing well 3. **Handle errors gracefully**: Ensure your container commands exit with appropriate status codes 4. **Test locally first**: Container tasks can run locally with Docker, making debugging easier 5. **Consider image size**: Smaller images lead to faster task startup times 6. **Document input/output contracts**: Clearly specify what data flows in and out ## Local execution Container tasks require Docker to be installed and running on your local machine. When you run them locally, Flyte will: 1. Pull the specified image (if not already available) 2. Mount local directories for inputs and outputs 3. Stream container logs to your console 4. Extract outputs after container completion This makes it easy to develop and test container tasks before deploying to a remote cluster. ## When to use container tasks Choose container tasks when you need to: - Run code in languages other than Python - Execute pre-built tools or legacy applications - Isolate potentially unsafe code (AI-generated scripts) - Use specific runtime environments or dependencies - Integrate external tools without Python wrappers - Execute shell scripts or command-line utilities For Python code that can use the Flyte SDK, standard `@task` decorated functions are usually simpler and more efficient. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/links === Attach clickable URLs to a task so the UI can reach external tools. # Links Links let you add clickable URLs to tasks that appear in the Flyte UI. Use them to connect tasks to external tools like experiment trackers, monitoring dashboards or custom internal services. ![Links in the Flyte UI](../../../_static/images/integrations/wandb/single_node_auto_flyte.png) You can attach links to tasks in two ways: - **Statically** in the task decorator with `links=` - **Dynamically** at call time with `task.override(links=...)` `Link` is a Python [Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol) that you subclass to define how URLs are generated. The Weights & Biases plugin provides a **Integrations > Weights & Biases > Wandb** as an example. ## Creating a link To create a link, subclass `Link` as a dataclass and implement the `get_link()` method. The method returns the URL string to display in the UI: ```python from dataclasses import dataclass import flyte from flyte import Link @dataclass class GrafanaLink(Link): dashboard_url: str name: str = "Grafana" def get_link( self, run_name: str, project: str, domain: str, context: dict, parent_action_name: str, action_name: str, pod_name: str, **kwargs, ) -> str: return f"{self.dashboard_url}?var-pod={pod_name}" env = flyte.TaskEnvironment(...) @env.task(links=(GrafanaLink(dashboard_url="https://grafana.example.com/d/abc123"),)) def my_task() -> str: return "done" ``` The link appears as a clickable "Grafana" link in the Flyte UI for every execution of `my_task`. ## Using execution metadata The `get_link()` method receives execution metadata that you can use to construct dynamic URLs. Here's an example modeled on the [built-in Wandb](../../../integrations/wandb/_index) link that uses the `context` dict to resolve a run ID: ```python from dataclasses import dataclass from typing import Optional from flyte import Link @dataclass class Wandb(Link): project: str entity: str id: Optional[str] = None name: str = "Weights & Biases" def get_link( self, run_name: str, project: str, domain: str, context: dict[str, str], parent_action_name: str, action_name: str, pod_name: str, **kwargs, ) -> str: run_id = self.id or context.get("wandb_id", run_name) return f"https://wandb.ai/{self.entity}/{self.project}/runs/{run_id}" ``` The `name` attribute controls the display label in the UI. See the **Flyte SDK > flyte > Link > Methods > get_link()** for more details. Note that `action_name` and `pod_name` are template variables (`{{.actionName}}` and `{{.podName}}`) that are populated by the backend at runtime. ## Dynamic links with override Use `task.override(links=...)` to set links at runtime. This is useful when link parameters depend on runtime values like run IDs or configuration: ```python import os import flyte from flyteplugins.wandb import Wandb env = flyte.TaskEnvironment(...) WANDB_PROJECT = "my-ml-project" WANDB_ENTITY = "my-team" @env.task def train_model(config: dict) -> dict: # Training logic here return {"accuracy": 0.95} @env.task async def main(wandb_id: str) -> dict: result = train_model.override( links=( Wandb( project=WANDB_PROJECT, entity=WANDB_ENTITY, id=wandb_id, ), ) )(config={"lr": 0.001}) return result if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, wandb_id="my-run-id") ``` The `override` approach lets you attach links with values that are only known at runtime, such as dynamically generated run IDs. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/reports === Display and update custom output in the UI while a task runs. # Reports The reports feature allows you to display and update custom output in the UI during task execution. > **๐Ÿ“ Note** > > Reports are the Flyte 2 successor to **Decks** in Flyte 1. Where Flyte 1 used `enable_deck=True` and the `flytekit.Deck` API, Flyte 2 uses `report=True` and the `flyte.report` API described below. First, you set the `report=True` flag in the task decorator. This enables the reporting feature for that task. Within a task with reporting enabled, a `flyte.report.Report` object is created automatically. > [!NOTE] Import `flyte.report` explicitly > `flyte.report` is a submodule that `import flyte` does **not** import automatically. > You must import it explicitly: > > ```python > import flyte.report > ``` > > Without this, calls like `flyte.report.replace()` or `flyte.report.flush()` raise > `AttributeError: module 'flyte' has no attribute 'report'`, most commonly hit in local or > notebook runs. This applies to all `flyte.*` submodules: import the specific submodule you use, > not just the top-level `flyte` package. A `Report` object contains one or more tabs, each of which contains HTML. You can write HTML to an existing tab and create new tabs to organize your content. Initially, the `Report` object has one tab (the default tab, named `main`) with no content. To write content: - `flyte.report.log()` appends HTML content directly to the default tab. - `flyte.report.replace()` replaces the content of the default tab with new HTML. To get or create a new tab: - `flyte.report.get_tab()` allows you to specify a unique name for the tab, and it will return the existing tab if it already exists or create a new one if it doesn't. It returns a `flyte.report._report.Tab` You can `log()` or `replace()` HTML on the `Tab` object just as you can directly on the `Report` object. To access the current `Report` object directly โ€” for example, to enumerate its tabs or assemble the final HTML โ€” call `flyte.report.current_report()`. Finally, you send the report to the Flyte backend and make it visible in the UI: - `flyte.report.flush()` dispatches the report (in its current state) to the backend. You do **not** have to call `flyte.report.flush()` explicitly at the end of a task: when a task with `report=True` finishes, Flyte automatically performs a final flush for you. Calling `flyte.report.flush()` yourself is only necessary when you want to *stream* updates to the UI while the task is still running (see **Tasks > Build tasks > Reports > Streaming example** below). ## A simple example ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # main = "main" # params = "" # /// import flyte import flyte.report env = flyte.TaskEnvironment(name="reports_example") @env.task(report=True) async def task1(): await flyte.report.replace.aio("

The quick, brown fox jumps over a lazy dog.

") tab2 = flyte.report.get_tab("Tab 2") tab2.log("

The quick, brown dog jumps over a lazy fox.

") await flyte.report.flush.aio() if __name__ == "__main__": flyte.init_from_config() r = flyte.run(task1) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/reports/simple.py* Here we define a task `task1` that uses `flyte.report.replace()` to set the content of the default tab, then creates a new tab named "Tab 2" with `flyte.report.get_tab()` and logs additional HTML content to it. Finally, `flyte.report.flush()` is called to send the report to the backend. ## A more complex example Here is another example. We import the necessary modules, set up the task environment, define the main task with reporting enabled and define the data generation function: ``` import json import random import flyte import flyte.report env = flyte.TaskEnvironment( name="globe_visualization", ) @env.task(report=True) async def generate_globe_visualization(): await flyte.report.replace.aio(get_html_content()) await flyte.report.flush.aio() def generate_globe_data(): """Generate sample data points for the globe""" cities = [ {"city": "New York", "country": "USA", "lat": 40.7128, "lng": -74.0060}, {"city": "London", "country": "UK", "lat": 51.5074, "lng": -0.1278}, {"city": "Tokyo", "country": "Japan", "lat": 35.6762, "lng": 139.6503}, {"city": "Sydney", "country": "Australia", "lat": -33.8688, "lng": 151.2093}, {"city": "Paris", "country": "France", "lat": 48.8566, "lng": 2.3522}, {"city": "Sรฃo Paulo", "country": "Brazil", "lat": -23.5505, "lng": -46.6333}, {"city": "Mumbai", "country": "India", "lat": 19.0760, "lng": 72.8777}, {"city": "Cairo", "country": "Egypt", "lat": 30.0444, "lng": 31.2357}, {"city": "Moscow", "country": "Russia", "lat": 55.7558, "lng": 37.6176}, {"city": "Beijing", "country": "China", "lat": 39.9042, "lng": 116.4074}, {"city": "Lagos", "country": "Nigeria", "lat": 6.5244, "lng": 3.3792}, {"city": "Mexico City", "country": "Mexico", "lat": 19.4326, "lng": -99.1332}, {"city": "Bangkok", "country": "Thailand", "lat": 13.7563, "lng": 100.5018}, {"city": "Istanbul", "country": "Turkey", "lat": 41.0082, "lng": 28.9784}, {"city": "Buenos Aires", "country": "Argentina", "lat": -34.6118, "lng": -58.3960}, {"city": "Cape Town", "country": "South Africa", "lat": -33.9249, "lng": 18.4241}, {"city": "Dubai", "country": "UAE", "lat": 25.2048, "lng": 55.2708}, {"city": "Singapore", "country": "Singapore", "lat": 1.3521, "lng": 103.8198}, {"city": "Stockholm", "country": "Sweden", "lat": 59.3293, "lng": 18.0686}, {"city": "Vancouver", "country": "Canada", "lat": 49.2827, "lng": -123.1207}, ] categories = ["high", "medium", "low", "special"] data_points = [] for city in cities: data_point = {**city, "value": random.randint(10, 100), "category": random.choice(categories)} data_points.append(data_point) return data_points ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/reports/globe_visualization.py* We then define the HTML content for the report: ```python def get_html_content(): data_points = generate_globe_data() html_content = f""" ... """ return html_content ``` (We exclude it here due to length. You can find it in the [source file](https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/reports/globe_visualization.py)). Finally, we run the workflow: ``` if __name__ == "__main__": flyte.init_from_config() r = flyte.run(generate_globe_visualization) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/reports/globe_visualization.py* When the workflow runs, the report will be visible in the UI: ![Globe visualization](../../../_static/images/user-guide/globe_visualization.png) ## Streaming example Above we demonstrated reports that are sent to the UI once, at the end of the task execution. But, you can also stream updates to the report during task execution and see the display update in real-time. You do this by calling `flyte.report.flush()` periodically during task execution, instead of just at the end. As a shortcut, you can also pass `do_flush=True` to `flyte.report.log()` or `flyte.report.replace()` to flush immediately after writing the content. > [!NOTE] > In the earlier examples we explicitly call `flyte.report.flush()` to send the report to the UI. > As noted above, that final flush is optional: it happens automatically when the task completes. > For streaming reports, on the other hand, calling `flyte.report.flush()` periodically (or passing `do_flush=True` > to `flyte.report.log()` / `flyte.report.replace()`) is what makes the intermediate updates appear. First we import the necessary modules, and set up the task environment: ``` import asyncio import json import math import random import time from datetime import datetime from typing import List import flyte import flyte.report env = flyte.TaskEnvironment(name="streaming_reports") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/reports/streaming_reports.py* Next we define the HTML content for the report: ```python DATA_PROCESSING_DASHBOARD_HTML = """ ... """ ``` (We exclude it here due to length. You can find it in the [source file]( https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/reports/streaming_reports.py)). Finally, we define the task that renders the report (`data_processing_dashboard`), the driver task of the workflow (`main`), and the run logic: ``` @env.task(report=True) async def data_processing_dashboard(total_records: int = 50000) -> str: """ Simulates a data processing pipeline with real-time progress visualization. Updates every second for approximately 1 minute. """ await flyte.report.log.aio(DATA_PROCESSING_DASHBOARD_HTML, do_flush=True) # Simulate data processing processed = 0 errors = 0 batch_sizes = [800, 850, 900, 950, 1000, 1050, 1100] # Variable processing rates start_time = time.time() while processed < total_records: # Simulate variable processing speed batch_size = random.choice(batch_sizes) # Add some processing delays occasionally if random.random() < 0.1: # 10% chance of slower batch batch_size = int(batch_size * 0.6) await flyte.report.log.aio(""" """, do_flush=True) elif random.random() < 0.05: # 5% chance of error errors += random.randint(1, 5) await flyte.report.log.aio(""" """, do_flush=True) else: await flyte.report.log.aio(f""" """, do_flush=True) processed = min(processed + batch_size, total_records) current_time = time.time() elapsed = current_time - start_time rate = int(batch_size) if elapsed < 1 else int(processed / elapsed) success_rate = ((processed - errors) / processed) * 100 if processed > 0 else 100 # Update dashboard await flyte.report.log.aio(f""" """, do_flush=True) print(f"Processed {processed:,} records, Errors: {errors}, Rate: {rate:,}" f" records/sec, Success Rate: {success_rate:.2f}%", flush=True) await asyncio.sleep(1) # Update every second if processed >= total_records: break # Final completion message total_time = time.time() - start_time avg_rate = int(total_records / total_time) await flyte.report.log.aio(f"""

๐ŸŽ‰ Processing Complete!

  • Total Records: {total_records:,}
  • Processing Time: {total_time:.1f} seconds
  • Average Rate: {avg_rate:,} records/second
  • Success Rate: {success_rate:.2f}%
  • Errors Handled: {errors}
""", do_flush=True) print(f"Data processing completed: {processed:,} records processed with {errors} errors.", flush=True) return f"Processed {total_records:,} records successfully" @env.task async def main(): """ Main task to run both reports. """ await data_processing_dashboard(total_records=50000) if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/reports/streaming_reports.py* The key to the live update ability is the `while` loop that appends Javascript to the report. The Javascript calls execute on append to the document and update it. When the workflow runs, you can see the report updating in real-time in the UI: ![Data Processing Dashboard](../../../_static/images/user-guide/data_processing_dashboard.png) ## Rendering a custom type The examples above build report HTML by hand. When you have a **custom type** โ€” or a DataFrame, or a `StructuredDataset` โ€” that you render the same way in many places, you can define a reusable **renderer** for the type and attach it to the type, instead of repeating the HTML-building logic at every call site. A renderer is any class that satisfies the `flyte.types.Renderable` protocol: it implements a single `to_html(self, value) -> str` method that returns an HTML fragment for a value of your type. ```python from flyte.types import Renderable class Molecule: def __init__(self, name: str, smiles: str): self.name = name self.smiles = smiles class MoleculeRenderer(Renderable): """A Renderable for the Molecule type.""" def to_html(self, mol: Molecule) -> str: return f"

{mol.name}

{mol.smiles}
" ``` You attach the renderer to the type with `typing.Annotated`, then dispatch a value through its attached renderer with `flyte.types.TypeEngine.to_html()`. Log the resulting HTML to the report just like any other content: ```python from typing import Annotated import flyte import flyte.report from flyte.types import TypeEngine env = flyte.TaskEnvironment(name="custom_renderer") # Attaching the renderer to the type is the "registration". RenderedMolecule = Annotated[Molecule, MoleculeRenderer()] @env.task(report=True) async def show_molecule() -> Molecule: mol = Molecule("caffeine", "CN1C=NC2=C1C(=O)N(C(=O)N2C)C") # Dispatch the value through the renderer attached to RenderedMolecule. html = TypeEngine.to_html(mol, RenderedMolecule) await flyte.report.log.aio(html) await flyte.report.flush.aio() return mol if __name__ == "__main__": flyte.init_from_config() print(flyte.run(show_molecule).url) ``` `TypeEngine.to_html()` finds the `Renderable` attached to the type via `Annotated`, calls its `to_html()`, and returns the HTML string โ€” which you then send to the report with `flyte.report.log()` (or `replace()`). The same pattern works for a DataFrame or `StructuredDataset`: annotate the type with a renderer that turns the frame into an HTML table. > [!NOTE] > The report contains only what you explicitly `log()` or `replace()`. Returning a value whose type has a renderer attached does **not** by itself add it to the report โ€” render the value and log the HTML, as shown above. Flyte's SDK also implements a few renderers of this kind internally โ€” for pandas and PyArrow DataFrames and for Markdown strings. These aren't exposed as public API (only the `flyte.types.Renderable` protocol is), so treat them as examples of the same pattern rather than importable helpers. ## Fetching a report after the run Everything above is about *writing* a report from inside a task. To *read* a finished report from outside the run, for example to embed it in a notebook or attach it to a CI job, fetch it through the remote API: ```python import flyte from flyte.remote import Run flyte.init_from_config() run = Run.get("my-run-name") html = run.get_report() ``` `get_report()` returns the report as an HTML string. It requests a signed download link for the report artifact and downloads the contents, so the call needs an initialized client. By default it returns the report for the latest attempt. Pass `attempt` to fetch an earlier one: ```python html = run.get_report(attempt=1) ``` `Run.get_report()` returns the report of the run's **root action**. A run whose tasks call other tasks has a report per action, so to fetch the report for a nested action, use `flyte.remote.Action.get_report()` on that action instead: ```python from flyte.remote import Action action = Action.get(run_name="my-run-name", name="6n505tdw46zu7fpmgtui1r1uw") html = action.get_report() ``` Nested actions are named deterministically from the parent action, the task identity, the inputs and the call sequence, so the name is a generated string rather than the task's function name. List the actions in a run to find the one you want: ```bash flyte get action my-run-name ``` Both are synchronous by default. From async code, call the `.aio` variant: ```python html = await run.get_report.aio() ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/notebooks === Write and run Flyte workloads from inside a Jupyter notebook. # Notebooks Flyte is designed to work with Jupyter notebooks, allowing you to write and execute workflows directly within a notebook environment. ## Iterating on and running a workflow Download the following notebook file and open it in your favorite Jupyter environment: [interactive.ipynb](../../../_static/public/interactive.ipynb) In this example we have a simple workflow defined in our notebook. You can iterate on the code in the notebook while running each cell in turn. Note that the `flyte.init()` call at the top of the notebook looks like this: ```python flyte.init( endpoint="https://union.example.com", org="example_org", project="example_project", domain="development", ) ``` You will have to adjust it to match your Union server endpoint, organization, project, and domain. ## Accessing runs and downloading logs Similarly, you can download the following notebook file and open it in your favorite Jupyter environment: [remote.ipynb](../../../_static/public/remote.ipynb) In this example we use the `flyte.remote` package to list existing runs, access them, and download their details and logs. For a guide on working with runs, actions, inputs, and outputs, see **Tasks > Run and deploy tasks > Interact with runs and actions**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/orchestrator-tasks === Run driver tasks that only call other tasks without a pod of their own, so they start in milliseconds and hold no compute while they wait. # Orchestrator tasks Some workflows run for a long time but do very little. Take an order: charge the card, wait up to a week for the warehouse to confirm the order has shipped, then email the customer, or refund the order if it did not ship. The work takes seconds. The waiting takes days. ```python import flyte import flyte.errors import flyte.orchestrator env = flyte.TaskEnvironment(name="orders") @env.task async def charge_card(order_id: str) -> None: ... @env.task async def refund(order_id: str) -> None: ... @env.task async def email_customer(order_id: str) -> None: ... @flyte.orchestrator.task async def order(order_id: str) -> str: await charge_card(order_id) shipped = flyte.new_condition( "shipped", prompt=f"Has order {order_id} shipped?", data_type=bool, timeout=7 * 24 * 3600, ) try: has_shipped = shipped.wait() # Pauses here and holds no pod. except flyte.errors.ConditionTimedoutError: await refund(order_id) return "timed out" if not has_shipped: await refund(order_id) return "refunded" await email_customer(order_id) return "done" ``` Written as a regular `@env.task`, `order` would busy-wait: it would hold a pod, with its CPU and memory, for up to a week while it waits for one signal. As an orchestrator task it has no pod at all. It holds nothing while it waits, and the three tasks it calls start their own pods only when they run. Union.ai runs the body of an orchestrator task in a small sandbox on a shared worker instead of in a container. When the function calls a task, it is suspended until the result comes back. The tasks it calls run as ordinary tasks, in their own containers, with their own resources. > [!NOTE] Union.ai only > Orchestrator tasks are available in Union.ai only, and need the latest Union.ai platform release. > Confirm with your Union.ai solutions team that your deployment has it. > Install the latest `flyte` SDK, 2.12.3 or later, with the `sandbox` extra: > `pip install -U "flyte[sandbox]>=2.12.3"`. The extra installs the Monty interpreter that local > runs use. ## Why use orchestrator tasks - **No busy waiting.** A regular driver task sits in a pod doing nothing while its children run. A suspended orchestrator holds no container, CPU, memory, or quota until a result comes back. - **Fast starts.** There is no pod to schedule and no image to pull, so an orchestrator starts in milliseconds rather than seconds. This matters for short control logic and for agent loops that take many quick steps, where container start-up would otherwise dominate. - **Lower cost.** You stop paying for drivers that are only waiting. The saving grows with the number of drivers you run at once and how long each one waits. - **No deadlocks from resource starvation.** When many regular drivers start together, they can fill the cluster or the project's quota, leaving no room for the child tasks they are waiting on. Nothing finishes. Orchestrators do not take up task pod resources, so they cannot starve their own children. An orchestrator is still a task. Each call it makes is a child action, recorded, retried, and shown in the UI like any other. ## When not to use orchestrator tasks The function runs in a [Monty](https://github.com/pydantic/monty) sandbox, Pydantic's restricted Python interpreter, on a worker that many orchestrators share. That makes it fast and cheap, and it also sets clear limits. Use a regular `@env.task` instead when: - **The driver needs libraries.** An orchestrator cannot import your dependencies, read files, or make network calls. Only a small part of the standard library, such as `asyncio` and `datetime`, is available. If the driver logic depends on packages, or on code whose behavior you need to reason about with its dependencies, keep it in a regular task. - **The driver reads or converts large data.** Every value that passes between the orchestrator and its tasks is converted at the sandbox boundary, and each orchestrator has a fixed memory limit (256 MiB by default). Pass references such as `flyte.io.File`, `flyte.io.Dir`, and dataframes through the orchestrator, and do the reading, parsing, and transforming inside tasks. ## Write an orchestrator task Decorate a function with `@flyte.orchestrator.task`. Inside it you can use loops, conditions, `try`/`except`, and plain values, and call tasks without `await`: ```python import flyte import flyte.orchestrator import flyte.remote add = flyte.remote.Task.get("math.add", auto_version="latest") multiply = flyte.remote.Task.get("math.multiply", auto_version="latest") @flyte.orchestrator.task def sum_of_squares(numbers: list[int]) -> int: total = 0 for n in numbers: total = add(total, multiply(n, n)) return total if __name__ == "__main__": flyte.init_from_config() run = flyte.run(sum_of_squares, numbers=[1, 2, 3]) print(run.url) ``` Start an orchestrator task with `flyte.run`, as above, or with `flyte run` on the command line. `flyte deploy` does not deploy orchestrator tasks, so you cannot fetch one later with `flyte.remote.Task.get()`. The orchestrator finds the tasks it calls in the module's globals. They can be: - **Remote tasks**, fetched with `flyte.remote.Task.get()`. Nothing is built, so the run is submitted straight away. See **Tasks > Build tasks > Remote tasks**. To pass positional arguments to a remote task with more than one input, that task must have been deployed with `flyte` 2.12.3 or later. Tasks deployed with an older SDK must be called with keyword arguments. - **Local tasks** defined with `@env.task` in your code. Their image and code bundle are built when you run the orchestrator, as for any `flyte.run`, and their specs travel with it. Nothing has to be deployed first. - **Other orchestrator tasks.** Each call is a separate child action. Define an orchestrator before any orchestrator that calls it. You can mix the kinds in one function: ```python import flyte import flyte.orchestrator import flyte.remote env = flyte.TaskEnvironment(name="shapes") @env.task def square(x: int) -> int: return x * x @env.task def describe(label: str, value: int) -> str: return f"{label} = {value}" add = flyte.remote.Task.get("math.add", auto_version="latest") @flyte.orchestrator.task def mixed_pipeline(x: int, y: int) -> str: total = add(square(x), square(y)) return describe("sum of squares", total) ``` ### Run tasks in parallel Write the orchestrator as `async def` to run several tasks at once. Task calls then return awaitables, as in any async task, and `asyncio.gather` waits for all of them: ```python import asyncio import flyte.orchestrator import flyte.remote summarize = flyte.remote.Task.get("docs.summarize", auto_version="latest") @flyte.orchestrator.task async def review(docs: list[str]) -> list[str]: return await asyncio.gather(*[summarize(doc=d) for d in docs]) ``` ### Handle task failures A task that fails raises an error inside the orchestrator, where you can catch it. The orchestrator runs without the SDK's exception classes, so catch the built-in exception: ```python import flyte.orchestrator import flyte.remote check = flyte.remote.Task.get("math.fail_if_negative", auto_version="latest") @flyte.orchestrator.task def tolerant(x: int) -> str: try: return "ok " + str(check(x)) except RuntimeError as e: return "recovered: " + str(e) ``` ### Retry an orchestrator, or stop it from retrying Set `retries` to run the orchestrator again when it raises an error. Each attempt runs the function from the start. The tasks it calls are not run twice: a call with the same task, inputs, and position in the run gets the result of the task the earlier attempt launched. To fail the run without using up `retries`, raise `flyte.errors.NonRecoverableError`. This needs `flyte` 2.13.1 or later. A failed task surfaces in the orchestrator as a `RuntimeError`, so to stop retrying when a task fails, catch that error and raise `NonRecoverableError` yourself: ```python import flyte.errors import flyte.orchestrator import flyte.remote check = flyte.remote.Task.get("math.fail_if_negative", auto_version="latest") @flyte.orchestrator.task(retries=3) def strict(x: int) -> int: if x > 1_000: raise flyte.errors.NonRecoverableError(f"{x} is too large") try: return check(x) except RuntimeError as e: raise flyte.errors.NonRecoverableError("check failed: " + str(e)) ``` The run fails with the error code `NonRecoverableError`. Inside the orchestrator, `NonRecoverableError` is a `RuntimeError`, so an `except RuntimeError` block around the `raise` catches it. ### Wait for a person An orchestrator can pause until someone approves a step or supplies a value from the UI or the API, using `flyte.new_condition` and the condition's `wait()`. Call `wait()` without `await`, even in an `async def` orchestrator. While it waits, nothing runs and no pod is held, whether that is for an hour or a week: ```python import flyte import flyte.orchestrator import flyte.remote evaluate = flyte.remote.Task.get("models.evaluate", auto_version="latest") publish = flyte.remote.Task.get("models.publish", auto_version="latest") @flyte.orchestrator.task def deploy(model: str) -> str: report = evaluate(model) approval = flyte.new_condition( "approve", prompt=f"Deploy {model}? {report}", timeout=24 * 60 * 60, ) if approval.wait(): return publish(model) return "rejected" ``` A condition's `data_type` can be `bool`, `int`, `float`, or `str`, and `timeout` is in seconds or a `timedelta`. Only the function's source is shipped, so import `timedelta` inside the function if you use it. Webhooks are not supported in orchestrator tasks. If a condition is not signaled in time, `wait()` raises `flyte.errors.ConditionTimedoutError`, as it does in any task. Inside an orchestrator this is the built-in `TimeoutError`, so `except TimeoutError` catches it too, but only there. If it fails or is aborted, `wait()` raises `RuntimeError`. See **Tasks > Build tasks > External conditions** for how to signal a condition. ## Values inside an orchestrator Values pass between the orchestrator and its tasks as they do between tasks, but the orchestrator can only look inside some of them: | Value | Inside the orchestrator | |-------|-------------------------| | `None`, `bool`, `int`, `float`, `str`, and lists and string-keyed dicts of them | Readable and writable | | `File` and `Dir` | A named tuple of `path`, `name`, `format`, and `hash`. The fields are readable, but the contents cannot be opened. | | Dataframes, dataclasses, Pydantic models (including volumes) | Opaque. The orchestrator can pass them on, return them, or keep them in a list or dict, but cannot read their fields. | To read the contents of a file or a dataframe, call a task. ## Settings and limits `@flyte.orchestrator.task` takes these arguments: | Argument | Default | Description | |----------|---------|-------------| | `name` | `.` | Task name. | | `queue` | The run's queue | Queue to run on. The tasks the orchestrator calls run on the same queue. | | `timeout_ms` | `30000` | Time the function may spend executing, and separately the total time it may sleep. Time spent waiting for tasks or conditions does not count. The worker caps it at its own limit. | | `max_stack_depth` | `256` | Maximum recursion depth. | | `cache` | `"disable"` | Cache policy for the orchestrator itself. The tasks it calls keep their own cache settings. | | `retries` | `0` | Retries for the orchestrator itself. | ```python import flyte.orchestrator @flyte.orchestrator.task(timeout_ms=5_000, retries=2, queue="critical") def pipeline(x: int) -> int: ... ``` The worker also applies limits that you cannot set on the decorator: - **Memory:** 256 MiB per orchestrator by default, the same for every orchestrator on a worker. Going over it fails the run with `MemoryError`. - **Task calls:** 10,000 per run by default. Going over it fails the run with `TooManyTaskCalls`, which the function cannot catch. - **Value nesting:** values passed to tasks can be nested at most 32 levels deep. - **Error messages:** kept to their first 10 KiB. Hitting a limit is a user error, so it counts against `retries` like any other failure of the orchestrator. The exception is `WorkerMemoryPressure`: an orchestrator stopped because another one on the same worker went over the memory limit fails with this system error, and it is retried without using up `retries`. ## Orchestrators that need a container `@flyte.orchestrator.task` may call only tasks and conditions. If the driver also needs **Tasks > Build tasks > Traces** or durable operations such as `flyte.durable.sleep`, use `env.orchestrator.task` on a `TaskEnvironment`. It runs the same restricted Python, but inside a container built from the environment's image, so it starts like a regular task and holds a pod: ```python import flyte env = flyte.TaskEnvironment(name="pipelines") @env.task def add(x: int, y: int) -> int: return x + y @env.orchestrator.task def pipeline(x: int, y: int) -> int: return add(add(x, y), 1) ``` `env.orchestrator.task` also accepts code as a string, for orchestration logic generated at runtime, for example by an LLM. With the `env` and `add` task from the previous example: ```python pipeline = env.orchestrator.task( "add(x, y) * 2", tasks=[add], inputs={"x": int, "y": int}, output=int, ) ``` The last expression in the string is the return value. For more on running generated code, see **Agents > Sandboxing > Workflow sandboxing in Flyte**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/remote-tasks === Call an already-deployed task without importing its code or dependencies. # Remote tasks Remote tasks let you use previously deployed tasks without importing their code or dependencies. This enables teams to share and reuse tasks without managing complex dependency chains or container images. ## Prerequisites Remote tasks must be deployed before you can use them. See the [task deployment guide](../task-deployment/_index) for details. ## Basic usage Use `flyte.remote.Task.get()` to reference a deployed task: ```python import flyte import flyte.remote env = flyte.TaskEnvironment(name="my_env") # Get the latest version of a deployed task data_processor = flyte.remote.Task.get( "data_team.spark_analyzer", auto_version="latest" ) # Use it in your task @env.task async def my_task(data_path: str) -> flyte.io.DataFrame: # Call the reference task like any other task result = await data_processor(input_path=data_path) return result ``` You can run this directly without deploying it: ```bash flyte run my_workflow.py my_task --data_path s3://my-bucket/data.parquet ``` ## Understanding lazy loading Remote tasks use **lazy loading** to keep module imports fast and enable flexible client configuration. When you call `flyte.remote.Task.get()`, it returns a lazy reference that doesn't actually fetch the task from the server until the first invocation. ### When tasks are fetched The remote task is fetched from the server only when: - You call `flyte.run()` with the task - You invoke the task with the `()` operator inside another task - You explicitly call `.fetch()` on the lazy reference ```python import flyte.remote # This does NOT make a network call - returns a lazy reference data_processor = flyte.remote.Task.get( "data_team.spark_analyzer", auto_version="latest" ) # The task is fetched here when you invoke it run = flyte.run(data_processor, input_path="s3://my-bucket/data.parquet") ``` ### Benefits of lazy loading **Fast module loading**: Since no network calls are made during import, your Python modules load quickly even when referencing many remote tasks. **Late binding**: You can call `flyte.init()` after importing remote tasks, and the correct client will be bound when the task is actually invoked: ```python import flyte import flyte.remote # Load remote task reference at module level data_processor = flyte.remote.Task.get( "data_team.spark_analyzer", auto_version="latest" ) # Initialize the client later flyte.init_from_config() # The task uses the client configured above run = flyte.run(data_processor, input_path="s3://data.parquet") ``` ### Error handling Because of lazy loading, if a referenced task doesn't exist, you won't get an error when calling `get()`. Instead, the error occurs during invocation, raising a `flyte.errors.RemoteTaskNotFoundError`: ```python import flyte import flyte.remote import flyte.errors # This succeeds even if the task doesn't exist data_processor = flyte.remote.Task.get( "nonexistent.task", auto_version="latest" ) try: # Error occurs here during invocation run = flyte.run(data_processor, input_path="s3://data.parquet") except flyte.errors.RemoteTaskNotFoundError as e: print(f"Task not found or invocation failed: {e}") # Handle the error - perhaps use a fallback task # or notify the user that the task needs to be deployed ``` You can also catch errors when using remote tasks within other tasks: ```python import flyte.errors @env.task async def pipeline_with_fallback(data_path: str) -> dict: try: # Try to use the remote task result = await data_processor(input_path=data_path) return {"status": "success", "result": result} except flyte.errors.RemoteTaskNotFoundError as e: # Fallback to local processing print(f"Remote task failed: {e}, using local fallback") return {"status": "fallback", "result": local_process(data_path)} except flyte.errors.RemoteTaskUsageError as e: raise ValueError(f"Bad Usage of remote task, maybe arguments dont match!") ``` ### Eager fetching with `fetch()` While lazy loading is convenient, you can explicitly fetch a task upfront using the `fetch()` method. This is useful for: - **Catching errors early**: Validate that the task exists before execution starts - **Caching**: Avoid the network call on first invocation when running multiple times - **Service initialization**: Pre-load tasks when your service starts ```python import flyte import flyte.remote import flyte.errors # Get the lazy reference data_processor = flyte.remote.Task.get( "data_team.spark_analyzer", auto_version="latest" ) try: # Eagerly fetch the task details task_details = data_processor.fetch() # Now the task is cached - subsequent calls won't hit the remote service # You can pass either the original reference or task_details to flyte.run run1 = flyte.run(data_processor, input_path="s3://data1.parquet") run2 = flyte.run(task_details, input_path="s3://data2.parquet") except flyte.errors.RemoteTaskNotFoundError as e: print(f"Task not found failed at startup: {e}") raise except flyte.errors.RemoteTaskUsageError as e: print(f"Task run validation failed....") # Handle the error before any execution attempts ``` For async contexts, use `await fetch.aio()`: ```python import flyte.remote async def initialize_service(): processor_ref = flyte.remote.Task.get( "data_team.spark_analyzer", auto_version="latest" ) try: # Fetch asynchronously task_details = await processor_ref.fetch.aio() print(f"Task {task_details.name} loaded successfully") return processor_ref # Return the cached reference except flyte.errors.RemoteTaskNotFoundError as e: print(f"Failed to load task: {e}") raise # Initialize once at service startup cached_processor = None async def startup(): global cached_processor cached_processor = await initialize_service() # Later in your service async def process_request(data_path: str): # The task is already cached from initialization # No network call on first invocation run = flyte.run(cached_processor, input_path=data_path) return run ``` **When to use eager fetching**: - **Service startup**: Fetch all remote tasks during initialization to validate they exist and cache them - **Multiple invocations**: If you'll invoke the same task many times, fetch once to cache it - **Fail-fast validation**: Catch configuration errors before execution begins **When lazy loading is better**: - **Single-use tasks**: If you only invoke the task once, lazy loading is simpler - **Import-time overhead**: Keep imports fast by deferring network calls - **Conditional usage**: If the task may not be needed, don't fetch it upfront ### Module-level vs dynamic loading **Module-level loading (recommended)**: Load remote tasks at the module level for cleaner, more maintainable code: ```python import flyte.remote # Module-level - clear and maintainable data_processor = flyte.remote.Task.get( "data_team.spark_analyzer", auto_version="latest" ) @env.task async def my_task(data_path: str): return await data_processor(input_path=data_path) ``` **Dynamic loading**: You can also load remote tasks dynamically within a task if needed: ```python @env.task async def dynamic_pipeline(task_name: str, data_path: str): # Load the task based on runtime parameters processor = flyte.remote.Task.get( f"data_team.{task_name}", auto_version="latest" ) try: result = await processor(input_path=data_path) return result except flyte.errors.RemoteTaskNotFoundError as e: raise ValueError(f"Task {task_name} not found: {e}") ``` ## Complete example This example shows how different teams can collaborate using remote tasks. ### Team A: Spark environment Team A maintains Spark-based data processing tasks: ```python # spark_env.py from dataclasses import dataclass import flyte env = flyte.TaskEnvironment(name="spark_env") @dataclass class AnalysisResult: mean_value: float std_dev: float @env.task async def analyze_data(data_path: str) -> AnalysisResult: # Spark code here (not shown) return AnalysisResult(mean_value=42.5, std_dev=3.2) @env.task async def compute_score(result: AnalysisResult) -> float: # More Spark processing return result.mean_value / result.std_dev ``` Deploy the Spark environment: ```bash flyte deploy spark_env/ ``` ### Team B: ML environment Team B maintains PyTorch-based ML tasks: ```python # ml_env.py from pydantic import BaseModel import flyte env = flyte.TaskEnvironment(name="ml_env") class PredictionRequest(BaseModel): feature_x: float feature_y: float class Prediction(BaseModel): score: float confidence: float model_version: str @env.task async def run_inference(request: PredictionRequest) -> Prediction: # PyTorch model inference (not shown) return Prediction( score=request.feature_x * 2.5, confidence=0.95, model_version="v2.1" ) ``` Deploy the ML environment: ```bash flyte deploy ml_env/ ``` ### Team C: Orchestration Team C builds a workflow using remote tasks from both teams without needing Spark or PyTorch dependencies: ```python # orchestration_env.py import flyte.remote env = flyte.TaskEnvironment(name="orchestration") # Reference tasks from other teams analyze_data = flyte.remote.Task.get( "spark_env.analyze_data", auto_version="latest" ) compute_score = flyte.remote.Task.get( "spark_env.compute_score", auto_version="latest" ) run_inference = flyte.remote.Task.get( "ml_env.run_inference", auto_version="latest" ) @env.task async def orchestrate_pipeline(data_path: str) -> float: # Use Spark tasks without Spark dependencies analysis = await analyze_data(data_path=data_path) # Access attributes from the result # (Flyte creates a fake type that allows attribute access) print(f"Analysis: mean={analysis.mean_value}, std={analysis.std_dev}") data_score = await compute_score(result=analysis) # Use ML task without PyTorch dependencies # Pass Pydantic models as dictionaries prediction = await run_inference( request={ "feature_x": analysis.mean_value, "feature_y": data_score } ) # Access Pydantic model attributes print(f"Prediction: {prediction.score} (confidence: {prediction.confidence})") return prediction.score ``` Run the orchestration task directly (no deployment needed): **Using Python API**: ```python if __name__ == "__main__": flyte.init_from_config() run = flyte.run( orchestrate_pipeline, data_path="s3://my-bucket/data.parquet" ) print(f"Execution URL: {run.url}") # You can wait for the execution run.wait() # You can then retrieve the outputs print(f"Pipeline result: {run.outputs()}") ``` **Using CLI**: ```bash flyte run orchestration_env.py orchestrate_pipeline --data_path s3://my-bucket/data.parquet ``` ## Invoke remote tasks in a script. You can also run any remote task directly using a script in a similar way ```python import flyte import flyte.models import flyte.remote flyte.init_from_config() # Fetch the task remote_task = flyte.remote.Task.get("package-example.calculate_average", auto_version="latest") # Create a run. Pass keyword arguments: flyte.run doesn't bind positional arguments to a remote task's inputs in the order the task declares them. run = flyte.run(remote_task, numbers=[1.0, 2.0, 3.0]) print(f"Execution URL: {run.url}") # you can view the phase print(f"Current Phase: {run.phase}") # You can wait for the execution run.wait() # Only available after flyte >= 2.0.0b39 print(f"Current phase: {run.phase}") # Phases can be compared to if run.phase == flyte.models.ActionPhase.SUCCEEDED: print(f"Run completed!") # You can then retrieve the outputs print(f"Pipeline result: {run.outputs()}") ``` ## Why use remote tasks? Remote tasks solve common collaboration and dependency management challenges: **Cross-team collaboration**: Team A has deployed a Spark task that analyzes large datasets. Team B needs this analysis for their ML pipeline but doesn't want to learn Spark internals, install Spark dependencies, or build Spark-enabled container images. With remote tasks, Team B simply references Team A's deployed task. **Platform reusability**: Platform teams can create common, reusable tasks (data validation, feature engineering, model serving) that other teams can use without duplicating code or managing complex dependencies. **Microservices for data workflows**: Remote tasks work like microservices for long-running tasks or agents, letting teams share deployed functionality without sharing code. ## When to use remote tasks Use remote tasks when you need to: - Use functionality from another team without their dependencies - Share common tasks across your organization - Build reusable platform components - Avoid dependency conflicts between different parts of your workflow - Create modular, maintainable data pipelines ## How remote tasks work ### Security model By default, remote tasks run in the **caller's project and domain**. A remote task called from inside a task becomes an action in the caller's run, so its pod runs in the **caller's** Kubernetes namespace. Its service account, and the IAM role bound to it, are resolved there, not in the callee's project. If the callee's task environment names a `service_account`, that account must exist in the caller's namespace. You can instead start a remote task as a separate run in the callee's project and domain: fetch it with `flyte.remote.Task.get(..., project=..., domain=...)` and start it with `flyte.with_runcontext(project=..., domain=...).run(...)`. This is a separate run, not an action in the caller's run: the caller gets a `Run` handle to `wait()` on and read `outputs()` from, not the task's return value. The identity that starts the run (from inside a task, the credentials the task runs with) must be allowed to create runs in the callee's project. ### Type system Remote tasks use Flyte's default types as inputs and outputs. Flyte's type system translates data between tasks without requiring the original dependencies: | Remote Task Type | Flyte Type | |-------------------|------------| | DataFrames (`pandas`, `polars`, `spark`, etc.) | `flyte.io.DataFrame` | | Object store files | `flyte.io.File` | | Object store directories | `flyte.io.Dir` | | Pydantic models | Dictionary (Flyte creates a representation) | Any DataFrame type (pandas, polars, spark) automatically becomes `flyte.io.DataFrame`, allowing data exchange between tasks using different DataFrame libraries. You can also write custom integrations or explore Flyte's plugin system for additional types. For Pydantic models specifically, you don't need the exact model locally. Pass a dictionary as input, and Flyte will handle the translation. ## Versioning options Reference tasks support flexible versioning: **Specific version**: ```python task = flyte.remote.Task.get( "team_a.process_data", version="v1.2.3" ) ``` **Latest version** (`auto_version="latest"`): ```python # Always use the most recently deployed version task = flyte.remote.Task.get( "team_a.process_data", auto_version="latest" ) ``` **Current version** (`auto_version="current"`): ```python # Use the same version as the calling task's deployment # Useful when all environments deploy with the same version # Can only be used from within a task context task = flyte.remote.Task.get( "team_a.process_data", auto_version="current" ) ``` ## Customizing remote tasks Remote tasks can be customized by overriding various properties without modifying the original deployed task. This allows you to adjust resource requirements, retry strategies, caching behavior, and more based on your specific use case. ### Available overrides The `override()` method on remote tasks accepts the following parameters: - **short_name** (`str`): A short name for the task instance - **resources** (`flyte.Resources`): CPU, memory, GPU, and storage limits - **retries** (`flyte.RetryStrategy`): Retry strategy. Passing a nonzero `int` raises `AssertionError` - **timeout** (`flyte.TimeoutType`): Task execution timeout - **env_vars** (`Dict[str, str]`): Environment variables to set - **secrets** (`flyte.SecretRequest`): Secrets to inject - **max_inline_io_bytes** (`int`): Maximum size for inline IO in bytes - **cache** (`flyte.Cache`): Cache behavior and settings - **queue** (`str`): Execution queue to use - **reusable** (`flyte.ReusePolicy | "off"`): Run the call on a **Tasks > Configure tasks > Reusable containers** pool, or pass `"off"` to run it in a one-off container. Requires `flyte` 2.12.4 or later. Overriding `reusable` with a `flyte.ReusePolicy` runs the call on its own warm pool, separate from the deployed task's pool. Calls with the same overrides share that pool. To get a warm pool of bigger containers, pass `resources=` in the same `override()` call. You can apply the override to `python` tasks and to tasks that are already reusable. The task's image must include `unionai-reuse`. Other task types, such as Spark, raise `flyte.errors.RemoteTaskUsageError`. Reusable containers run only on a Union backend. ### Override examples **Increase resources for a specific use case**: ```python import flyte.remote # Get the base task data_processor = flyte.remote.Task.get( "data_team.spark_analyzer", auto_version="latest" ) # Override with more resources for large dataset processing large_data_processor = data_processor.override( resources=flyte.Resources( cpu="16", memory="64Gi", disk="200Gi" ) ) @env.task async def process_large_dataset(data_path: str): # Use the customized version return await large_data_processor(input_path=data_path) ``` **Add retries and timeout**: ```python from datetime import timedelta # Override with retries and timeout for unreliable operations reliable_processor = data_processor.override( retries=flyte.RetryStrategy(count=3), timeout=timedelta(hours=2) ) @env.task async def robust_pipeline(data_path: str): return await reliable_processor(input_path=data_path) ``` **Configure caching**: ```python # Override cache settings cached_processor = data_processor.override( cache=flyte.Cache( behavior="override", version_override="v2", serialize=True ) ) ``` **Set environment variables and secrets**: ```python # Override with custom environment and secrets custom_processor = data_processor.override( env_vars={ "LOG_LEVEL": "DEBUG", "REGION": "us-west-2" }, secrets=flyte.Secret(key="my-secret-key", as_env_var="API_KEY") ) ``` **Multiple overrides**: ```python from datetime import timedelta # Combine multiple overrides production_processor = data_processor.override( short_name="prod_spark_analyzer", resources=flyte.Resources(cpu="8", memory="32Gi"), retries=flyte.RetryStrategy(count=5), timeout=timedelta(hours=4), env_vars={"ENV": "production"}, queue="high-priority" ) @env.task async def production_pipeline(data_path: str): return await production_processor(input_path=data_path) ``` ### Chain overrides You can chain multiple `override()` calls to incrementally adjust settings: ```python from datetime import timedelta # Start with base task processor = flyte.remote.Task.get("data_team.analyzer", auto_version="latest") # Add resources processor = processor.override(resources=flyte.Resources(cpu="4", memory="16Gi")) # Add retries for production if is_production: processor = processor.override(retries=flyte.RetryStrategy(count=5), timeout=timedelta(hours=2)) # Use the customized task result = await processor(input_path="s3://data.parquet") ``` ## Best practices ### 1. Use meaningful task names Remote tasks are accessed by name, so use clear, descriptive naming: ```python # Good customer_segmentation = flyte.remote.Task.get("ml_platform.customer_segmentation", auto_version="latest") # Avoid task1 = flyte.remote.Task.get("team_a.task1", auto_version="latest") ``` ### 2. Document task interfaces Since remote tasks abstract away implementation details, clear documentation of inputs, outputs, and behavior is essential: ```python @env.task async def process_customer_data( customer_ids: list[str], date_range: tuple[str, str] ) -> flyte.io.DataFrame: """ Process customer data for the specified date range. Args: customer_ids: List of customer IDs to process date_range: Tuple of (start_date, end_date) in YYYY-MM-DD format Returns: DataFrame with processed customer features """ ... ``` ### 3. Prefer module-level loading Load remote tasks at the module level rather than inside functions for cleaner code: ```python import flyte.remote # Good - module level data_processor = flyte.remote.Task.get("team.processor", auto_version="latest") @env.task async def my_task(data: str): return await data_processor(input=data) ``` This approach: - Makes dependencies clear and discoverable - Reduces code duplication - Works well with lazy loading (no performance penalty) Dynamic loading within tasks is also supported when you need runtime flexibility. ### 4. Handle versioning thoughtfully - Use `auto_version="latest"` during development for rapid iteration - Use specific versions in production for stability and reproducibility - Use `auto_version="current"` when coordinating multienvironment deployments ### 5. Deploy remote tasks first Always deploy the remote tasks before using them. Tasks that reference them can be run directly without deployment: Deploy the remote task environments first: ```bash flyte deploy spark_env/ flyte deploy ml_env/ ``` Then run the orchestration task directly (no deployment needed): ```bash flyte run orchestration_env.py orchestrate_pipeline ``` If you want to deploy the orchestration task as well (for scheduled runs or to be referenced by other tasks), deploy it after its dependencies: ```bash flyte deploy orchestration_env/ ``` ## Limitations 1. **Lazy error detection**: Because of lazy loading, errors about missing or invalid tasks only occur during invocation, not when calling `get()`. You'll receive a `flyte.errors.RemoteTaskNotFoundError` if the task doesn't exist and `flyte.errors.RemoteTaskUsageError` if it can't be invoked in the way you are passing either arguments or overrides. 2. **Type fidelity**: While Flyte translates types, you work with Flyte's representation of Pydantic models, not the exact original types 3. **Deployment order**: Referenced tasks must be deployed before tasks that reference them can be invoked 4. **Context requirement**: Using `auto_version="current"` requires running within a task context 5. **Dictionary inputs**: Pydantic models must be passed as dictionaries, which loses compile-time type checking 6. **Positional arguments need a recent deployment**: Inside a task, a remote task call binds positional arguments in the order the task declares its inputs. A task deployed with a `flyte` version earlier than 2.12.3 takes keyword arguments only, and a positional call raises `flyte.errors.RemoteTaskUsageError`. Redeploy it to call it with positional arguments. ## Next steps - Learn about [task deployment](../task-deployment/_index) - Explore [task environments and configuration](../task-configuration/_index) === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/error-handling === Catch and recover from task failures, including out-of-memory errors, timeouts, missing GPU capacity, and GPU hardware faults. # Error handling One of the key features of Flyte 2 is the ability to recover from user-level errors in a workflow execution. This includes out-of-memory errors, timeouts, GPUs that can't be scheduled or that fault mid-run, oversized inline I/O, and other exceptions. In a distributed system with heterogeneous compute, certain types of errors are expected and even, in a sense, acceptable. Flyte 2 recognizes this and allows you to handle them gracefully as part of your workflow logic. This ability is a direct result of the fact that workflows are now written in regular Python, giving you all the power and flexibility of Python error handling. When a task fails, Flyte surfaces the failure to the calling task as a typed exception that you can catch with a standard `try...except` block and respond to however you like: retry with more resources, fall back to a different code path, or clean up and re-raise. ## How Flyte represents failures When a downstream task fails, the failure propagates to the awaiting parent task as an exception from the `flyte.errors` module. Every native exception derives from a small hierarchy of base classes: - `flyte.errors.BaseRuntimeError`: the root of all Flyte runtime errors. - `flyte.errors.RuntimeUserError`: the failure was caused by your code (a bug, an exception you raised, an out-of-memory condition, and so on). An exception you raise inside a task, say a `ValueError`, is wrapped and surfaces to the parent as a `flyte.errors.RuntimeUserError`. - `flyte.errors.RuntimeSystemError`: the failure was caused by the platform rather than your code. - `flyte.errors.RuntimeUnknownError`: the failure could not be classified as a user or system error. Every concrete error carries a `code` attribute (a short, stable string identifier, often the exception's class name, e.g. `"TaskTimeoutError"`) that you can inspect when logging or branching. Because the errors form a hierarchy, you can catch broadly (`except flyte.errors.RuntimeUserError`) or narrowly (`except flyte.errors.OOMError`), depending on how specific your recovery logic needs to be. ## Catching and recovering from errors The most common pattern is to catch a specific exception and re-run the failing task with a different configuration. The following example intentionally triggers an out-of-memory error, catches the `flyte.errors.OOMError`, and retries the task with more memory: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # main = "main" # params = "" # /// import asyncio import flyte import flyte.errors env = flyte.TaskEnvironment(name="fail", resources=flyte.Resources(cpu=1, memory="250Mi")) @env.task def oomer() -> int: """Allocate enough memory to trigger an out-of-memory error.""" large_list = [0] * 100000000 print(len(large_list)) return 42 @env.task def main() -> int: """Retry an out-of-memory task with more resources.""" try: return oomer() except flyte.errors.OOMError as e: print(f"Failed with oom trying with more resources: {e}, of type {type(e)}, {e.code}") try: return oomer.override(resources=flyte.Resources(cpu=1, memory="1Gi"))() except flyte.errors.OOMError as e: print(f"Failed with OOM Again giving up: {e}, of type {type(e)}, {e.code}") raise e if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/error-handling/error_handling.py* In this code, we do the following: * Import the necessary modules, including `flyte.errors`. * Set up the task environment with a modest resource allocation of 1 CPU and 250 MiB of memory. * Define the `oomer` task, which allocates a large list and is likely to run out of memory. * Define the `main` task (the top-level workflow task) that contains the failure-recovery logic. The `try...except` block in `main` runs `oomer`. If it exhausts memory, `main` catches the `flyte.errors.OOMError` and retries by calling `oomer.override(resources=...)()` with a larger memory allocation. A nested `try...except` re-raises the error if the retry also runs out of memory. This type of dynamic error handling lets you gracefully recover from user-level errors in your workflows using patterns you already know from ordinary Python. For a complete, self-tuning version of this pattern that caches the optimal memory setting across runs, see the [`resource_tuner` example](https://github.com/flyteorg/flyte-sdk/blob/main/examples/advanced/resource_tuner.py). > [!NOTE] Programmatic recovery vs. automatic retries > Catching an exception and re-running a task is *programmatic* recovery: you decide what to do differently on > the next attempt. This is distinct from Flyte's *automatic* retries (`retries=N` on a task), which simply > re-run the same attempt unchanged. The two compose: automatic retries handle transient failures, while a > `try...except` handles failures you want to respond to deliberately. See > **Tasks > Configure tasks > Retries and timeouts**. ### Out-of-memory on the GPU `flyte.errors.OOMError` covers the container running out of host memory, which the platform detects when it kills the pod. Running out of *GPU* memory is different: the process keeps running and your framework raises its own exception, such as `torch.cuda.OutOfMemoryError`. Like any exception raised in a task, it reaches the parent as a `flyte.errors.RuntimeUserError`, with the exception's class name as its `code`: ```python @env.task async def main() -> str: try: return await train(batch_size=64) except flyte.errors.RuntimeUserError as e: if e.code != "OutOfMemoryError": raise # The GPU ran out of memory: retry with a smaller batch. return await train(batch_size=32) ``` ## Falling back when GPU capacity isn't available A task that asks for a scarce accelerator can sit in the **Queued** or **Waiting for resources** phase for a long time if the cluster has none free. Set **Tasks > Configure tasks > Retries and timeouts > Timeouts > `max_queued_time`: fail fast when capacity isn't available** to bound that wait. When it fires, the parent catches `flyte.errors.MaxQueuedTimeExceededError` and can try a different accelerator instead of waiting forever: ```python from datetime import timedelta import flyte import flyte.errors gpu_env = flyte.TaskEnvironment( name="trainer", resources=flyte.Resources(cpu=8, memory="64Gi", gpu="H100:1"), ) driver = flyte.TaskEnvironment(name="driver", depends_on=[gpu_env]) @gpu_env.task(timeout=flyte.Timeout(max_queued_time=timedelta(minutes=10))) async def train(epochs: int) -> str: ... # Tried in order. The first one that is scheduled within max_queued_time wins. GPU_OPTIONS = ["H100:1", "A100 80G:1", "L40s:1"] @driver.task async def main(epochs: int = 3) -> str: for gpu in GPU_OPTIONS: try: resources = flyte.Resources(cpu=8, memory="64Gi", gpu=gpu) return await train.override(resources=resources)(epochs=epochs) except flyte.errors.MaxQueuedTimeExceededError as e: print(f"No {gpu} capacity within 10 minutes, trying the next option: {e}") raise RuntimeError(f"No capacity for any of {GPU_OPTIONS}") ``` The per-attempt queue budget is what keeps each step of the fallback short. Without it, the first option would wait until capacity appeared or a `deadline` fired, and the loop would never advance. ### Routing each option to a different queue Different GPU pools often live behind different **Tasks > Configure tasks > Queues**, each bound to its own cluster or node pool. Override `queue` along with `resources` so each option is scheduled where that GPU actually exists: ```python # (queue, GPU) pairs, tried in order. PLACEMENTS = [ ("gpu-h100", "H100:1"), ("gpu-a100", "A100 80G:1"), ("gpu-l40s-secondary", "L40s:1"), ] @driver.task async def main(epochs: int = 3) -> str: for queue, gpu in PLACEMENTS: try: resources = flyte.Resources(cpu=8, memory="64Gi", gpu=gpu) return await train.override(queue=queue, resources=resources)(epochs=epochs) except flyte.errors.MaxQueuedTimeExceededError: print(f"Queue {queue} had no {gpu} capacity, moving on") raise RuntimeError("No queue had capacity") ``` Queues are created by your platform admin; see **Clusters and queues > Managing queues**. ### Telling the timeout bounds apart Each bound in `flyte.Timeout` raises its own subclass of `flyte.errors.TaskTimeoutError`, so the parent can tell "never started" from "started but ran too long": | Exception | Bound that fired | Typical response | |---|---|---| | `flyte.errors.MaxQueuedTimeExceededError` | `max_queued_time`: the attempt never started running. | Try a different accelerator, queue, or cluster. | | `flyte.errors.MaxRuntimeExceededError` | `max_runtime`: the attempt ran too long. | Give it more time, more compute, or less work. | | `flyte.errors.DeadlineExceededError` | `deadline`: the total budget across all attempts ran out. | Usually give up, since the time budget is gone. | Existing `except flyte.errors.TaskTimeoutError` handlers catch all three. A backend that doesn't report which bound fired raises the base `flyte.errors.TaskTimeoutError`, so keep a handler for it if you need to support older deployments. ## Handling GPU hardware faults (Xid errors) GPUs fail in ways CPUs don't: a GPU can fall off the PCIe bus, hit an uncorrectable ECC error, or report an NVIDIA **Xid** (or an NVSwitch **SXid**) that kills the process. When the platform attributes a task failure to one of these faults, the parent receives a `flyte.errors.GPUFaultError`. It has two concrete subclasses, and they mean very different things: - `flyte.errors.GPUFaultUserError`: the workload caused the fault. User-severity Xids (13, 31, 43, 45) include out-of-bounds memory accesses and illegal instructions. The GPU is healthy once the process exits, but the same code will fault again. These faults count against the task's own retry budget, so by the time you see this error the task's retries are already used up. Fix the code, or change what you run (a different kernel, precision, or batch size); don't simply re-run it. - `flyte.errors.GPUFaultSystemError`: the hardware failed, for example an uncorrectable ECC error, a GPU that fell off the bus, or an NVLink error. The platform retries these without charging your retry budget and reschedules onto other hardware where it can. You only see this error after the platform has given up, so retrying in place is unlikely to help. Move to a different GPU type, queue, or cluster instead. **Availability:** platform-side GPU fault detection is not enabled on Union clusters, so the platform does not raise these errors. The classes are available in the SDK. Catch `flyte.errors.GPUFaultError` to handle both, then branch on the attributes: | Attribute | Meaning | |---|---| | `code` | `GpuXidError` (catch-all), `GpuFallenOffBus`, `GpuEccUncorrectable`, `GpuRowRemapPending`, `GpuNvlinkError`, or `GpuGspError`. | | `xid` / `sxid` | The NVIDIA Xid or NVSwitch SXid number. Only one is set, depending on `fault_kind`. | | `fault_name` | A readable name for the fault. | | `severity` | `"user"`, `"warn"`, or `"critical"`. | | `node`, `gpu_uuid`, `gpu_index`, `pci_bus_id` | Where the fault happened. Useful when reporting bad hardware. | | `process` | The process the driver attributed the fault to. | Any of these attributes can be `None` if the platform didn't supply them, so read them defensively. The following example puts the pieces together. It walks a list of GPU options and moves on when an option can't be scheduled, when its hardware fails, or when the model doesn't fit in its memory. A fault caused by the workload itself is re-raised, because a different GPU won't fix a bug: ```python @driver.task async def main(epochs: int = 3) -> str: for gpu in GPU_OPTIONS: resources = flyte.Resources(cpu=8, memory="64Gi", gpu=gpu) try: return await train.override(resources=resources)(epochs=epochs) except flyte.errors.MaxQueuedTimeExceededError: print(f"No {gpu} capacity, trying the next option") except flyte.errors.GPUFaultSystemError as e: print(f"{gpu} hardware fault {e.code} (xid={e.xid}) on node {e.node}, trying the next option") except flyte.errors.GPUFaultUserError as e: print(f"Workload fault {e.fault_name} (xid={e.xid}); a different GPU won't help") raise except flyte.errors.RuntimeUserError as e: if e.code != "OutOfMemoryError": raise print(f"Model doesn't fit on {gpu}, trying the next option") raise RuntimeError(f"No GPU option succeeded: {GPU_OPTIONS}") ``` Order matters: `GPUFaultUserError` and `MaxQueuedTimeExceededError` are both subclasses of `RuntimeUserError`, so their clauses must come before the generic `RuntimeUserError` clause. > [!NOTE] GPU fault errors depend on the platform > These exceptions are raised only when the platform detected and classified the fault. On a platform or > version that doesn't, the same failure arrives as an ordinary runtime error with no fault attributes. Don't > depend on `GPUFaultError` firing: keep a handler for ordinary task failures as well. ## Handling the failure of a run you launched A task (or a script) can also launch a whole *run* with `flyte.run` rather than calling a task as a sub-action, for example to compose several independent runs into a larger pipeline. A sub-action failure raises in the parent automatically. A run you launched doesn't, because `flyte.run` returns a `flyte.remote.Run` handle immediately. Wait on the handle, then call `flyte.remote.Run.raise_for_status()` (requires `flyte` 2.10.3 or later): ```python run = await flyte.run.aio(train, epochs=3) await run.wait.aio(quiet=True) await run.raise_for_status.aio() # Does nothing if the run succeeded. result = (await run.outputs.aio())[0] ``` Like `requests.Response.raise_for_status`, it does nothing when the run succeeded. Otherwise it raises the same exception that awaiting the task as a sub-action would have raised, so everything on this page applies to runs too: - A run that timed out raises the matching `flyte.errors.TaskTimeoutError` subclass, such as `flyte.errors.MaxQueuedTimeExceededError`. - An aborted run raises `flyte.errors.ActionAbortedError`, including the abort reason. - A failed run raises the error converted from its error code: `flyte.errors.OOMError`, a `flyte.errors.GPUFaultError` subclass, or a `flyte.errors.RuntimeUserError` carrying your exception's class name as its `code`. - A run that hasn't finished raises `flyte.errors.RuntimeUserError` with code `RunNotDoneError`. Call `wait()` first. Outside an async context, use the synchronous forms: `run.wait()` then `run.raise_for_status()`. The capacity fallback from earlier works the same way at the run level. The following driver launches a training run on an H100 and falls back to an A100 run if no H100 is scheduled in time: ```python async def run_to_completion(task, run_name: str, **inputs) -> str: run = await flyte.with_runcontext(name=run_name).run.aio(task, **inputs) await run.wait.aio(quiet=True) await run.raise_for_status.aio() return (await run.outputs.aio())[0] @flyte.trace async def train_h100(run_name: str, epochs: int) -> str: return await run_to_completion(train, run_name, epochs=epochs) @flyte.trace async def train_a100(run_name: str, epochs: int) -> str: a100 = train.override(resources=flyte.Resources(cpu=8, memory="64Gi", gpu="A100 80G:1")) return await run_to_completion(a100, run_name, epochs=epochs) @driver.task async def main(epochs: int = 3) -> str: # Child run names derive from this run's name, so they stay the same across retries. prefix = flyte.ctx().action.run_name try: return await train_h100(f"{prefix}-h100", epochs) except flyte.errors.MaxQueuedTimeExceededError: return await train_a100(f"{prefix}-a100", epochs) ``` Wrapping each launch in `@flyte.trace` with a stable run name makes the driver safe to retry. A finished step replays its recorded result or error. A step that was still waiting when the driver died launches again under the same name, and creating a run with an existing name returns that run, so the driver waits on it rather than starting a duplicate. For the full example, see [`run_of_runs.py`](https://github.com/flyteorg/flyte-sdk/blob/main/examples/advanced/run_of_runs.py). To send a child run to a different queue, pass `queue` when you launch it: `flyte.with_runcontext(name=run_name, queue="gpu-a100").run.aio(task, **inputs)`. ## Limiting inline I/O Small task inputs and outputs are passed *inline* (embedded directly in the task's metadata) rather than offloaded to blob storage. This is fast, but very large inline values are undesirable, so each task has a ceiling on the size of its inline I/O. You set this ceiling with the `max_inline_io_bytes` parameter on `@env.task`, and Flyte raises a `flyte.errors.InlineIOMaxBytesBreached` when an input or output exceeds it: ```python import flyte import flyte.errors env = flyte.TaskEnvironment( name="large_inline_io", resources=flyte.Resources(cpu=1, memory="250Mi"), ) @env.task(max_inline_io_bytes=100 * 1024) # Limit inline I/O to 100 KiB async def printer_task(x: str) -> str: print(f"Printer task received: {x}") return x @env.task async def large_inline_io() -> str: small = await printer_task("Hello, world!") print(f"Small string result: {small}") # A large string that exceeds the 100 KiB inline limit large_string = "A" * 10**6 # ~1 MiB try: return await printer_task(large_string) except flyte.errors.InlineIOMaxBytesBreached as e: print(f"Inline I/O limit breached: {e}") raise ``` The small string passes through, but the ~1 MiB string breaches the 100 KiB limit and raises `flyte.errors.InlineIOMaxBytesBreached`. The calling task raises the error, and only in remote runs; local runs don't enforce the limit. See **Tasks > Configure tasks > Additional task settings > Where the limit is checked**. When you expect large values, raise `max_inline_io_bytes` or pass the data as a `flyte.io.File` or `flyte.io.Dir` so it is offloaded to blob storage instead of traveling inline. A runnable version of this example is available as [`large_inline_io.py`](https://github.com/flyteorg/flyte-sdk/blob/main/examples/advanced/large_inline_io.py). ## Natively-supported exceptions Flyte raises typed exceptions for the failure modes it recognizes, so you can catch exactly the condition you care about. The most commonly caught errors are: | Exception | Raised when | |---|---| | `flyte.errors.OOMError` | A task exceeds its memory allocation. | | `flyte.errors.TaskTimeoutError` | A task exceeds one of its `flyte.Timeout` bounds. The subclasses below say which one. | | `flyte.errors.MaxQueuedTimeExceededError` | A task waits longer than `max_queued_time` to start, for example because no GPU is free. | | `flyte.errors.MaxRuntimeExceededError` | A task attempt runs longer than `max_runtime`. | | `flyte.errors.DeadlineExceededError` | A task doesn't finish within its `deadline`, across all attempts. | | `flyte.errors.GPUFaultUserError` | The workload caused a GPU fault, such as Xid 31 (GPU memory page fault). | | `flyte.errors.GPUFaultSystemError` | GPU hardware failed, such as an uncorrectable ECC error or a GPU that fell off the bus. | | `flyte.errors.InlineIOMaxBytesBreached` | An input or output exceeds the task's `max_inline_io_bytes` limit. | | `flyte.errors.RetriesExhaustedError` | A task fails after all of its automatic retries are used up. | | `flyte.errors.TaskInterruptedError` | A task running on interruptible (spot) compute is preempted. | | `flyte.errors.ActionAbortedError` | An action is aborted externally via the CLI, UI, or API. | | `flyte.errors.ImagePullBackOffError` | The task's container image cannot be pulled. | | `flyte.errors.NonRecoverableError` | A failure that should not be retried, regardless of the retry budget. | All of these except `flyte.errors.GPUFaultSystemError` derive from `flyte.errors.RuntimeUserError`, so a single `except flyte.errors.RuntimeUserError` catches them when you want uniform handling. `GPUFaultSystemError` is a `flyte.errors.RuntimeSystemError`, because the hardware failed rather than your code; catch it separately, or catch `flyte.errors.BaseRuntimeError` to handle everything. This is only a selection. For the complete catalog of catchable exception classes, see the [`flyte.errors` API reference](../../../api-reference/flyte-sdk/flyte.errors/_index). ## Related pages - **Tasks > Configure tasks > Retries and timeouts**: configure automatic retries and execution time limits. - **Tasks > Build tasks > Abort and cancel actions**: stop actions programmatically or externally, and handle `flyte.errors.ActionAbortedError`. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/traces === Make a called function observable and resumable with the flyte.trace decorator. # Traces The `@flyte.trace` decorator provides fine-grained observability and resumption capabilities for functions called within your Flyte workflows. Traces are used on **helper functions** that tasks call to perform specific operations like API calls, data processing, or computations. Traces are particularly useful for **Migration > From Flyte 1 to 2 > Gotchas and caveats > Non-deterministic behavior**, allowing you to track execution details and resume from failures. ## What are traced functions for? At the top level, Flyte workflows are composed of **tasks**. But it is also common practice to break down complex task logic into smaller, reusable functions by defining helper functions that tasks call to perform specific operations. Any helper functions defined or imported into the same file as a task definition are automatically uploaded to the Flyte environment alongside the task when it is deployed. At the task level, observability and resumption of failed executions is provided by caching, but what if you want these capabilities at a more granular level, for the individual operations that tasks perform? This is where **traced functions** come in. By decorating helper functions with `@flyte.trace`, you enable: - **Detailed observability**: Track execution time, inputs/outputs, and errors for each function call. - **Fine-grained resumption**: If a task fails and is retried, a traced call replays its recorded result instead of running again, but only if its function declares a return type and the call returned something other than `None`. Otherwise it runs again. A function with no return type annotation records no result to replay, even if it returns a value at run time. Each call that can replay is effectively a checkpoint within its task. Here is an example: ``` import asyncio import flyte env = flyte.TaskEnvironment("env") @flyte.trace async def call_llm(prompt: str) -> str: await asyncio.sleep(0.1) return f"LLM response for: {prompt}" @flyte.trace async def process_data(data: str) -> dict: await asyncio.sleep(0.2) return {"processed": data, "status": "completed"} @env.task async def research_workflow(topic: str) -> dict: llm_result = await call_llm(f"Generate research plan for: {topic}") processed_data = await process_data(llm_result) return {"topic": topic, "result": processed_data} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/traces/task_vs_trace.py* ## What gets traced Traces capture detailed execution information: - **Execution time**: How long each function call takes. - **Inputs and outputs**: Function parameters and return values. - **Checkpoints**: State that enables workflow resumption. ### Errors When a traced function that declares a return value raises, the error is recorded with the trace. In every case the exception propagates up to your task code, where you can handle it with standard error handling patterns. ### Supported function types The trace decorator works with: - **Asynchronous functions**: Functions defined with `async def`. - **Generator functions**: Functions that `yield` values. - **Async generators**: Functions that `async yield` values. > [!NOTE] > Currently tracing only works for asynchronous functions. Tracing of synchronous functions is coming soon. ``` @flyte.trace async def async_api_call(topic: str) -> dict: # Asynchronous API call await asyncio.sleep(0.1) return {"data": ["item1", "item2", "item3"], "status": "success"} @flyte.trace async def stream_data(items: list[str]): # Async generator function for streaming for item in items: await asyncio.sleep(0.02) yield f"Processing: {item}" @flyte.trace async def async_stream_llm(prompt: str): # Async generator for streaming LLM responses chunks = ["Research shows", " that machine learning", " continues to evolve."] for chunk in chunks: await asyncio.sleep(0.05) yield chunk @env.task async def research_workflow(topic: str) -> dict: llm_result = await async_api_call(topic) # Collect async generator results processed_data = [] async for item in stream_data(llm_result["data"]): processed_data.append(item) llm_stream = [] async for chunk in async_stream_llm(f"Summarize research on {topic}"): llm_stream.append(chunk) return { "topic": topic, "processed_data": processed_data, "llm_summary": "".join(llm_stream) } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/traces/function_types.py* ## Task orchestration pattern The typical Flyte workflow follows this pattern: ``` @flyte.trace async def search_web(query: str) -> list[dict]: # Search the web and return results await asyncio.sleep(0.1) return [{"title": f"Article about {query}", "content": f"Content on {query}"}] @flyte.trace async def summarize_content(content: str) -> str: # Summarize content using LLM await asyncio.sleep(0.1) return f"Summary of {len(content.split())} words" @flyte.trace async def extract_insights(summaries: list[str]) -> dict: # Extract insights from summaries await asyncio.sleep(0.1) return {"insights": ["key theme 1", "key theme 2"], "count": len(summaries)} @env.task async def research_pipeline(topic: str) -> dict: # Each helper function creates a checkpoint search_results = await search_web(f"research on {topic}") summaries = [] for result in search_results: summary = await summarize_content(result["content"]) summaries.append(summary) final_insights = await extract_insights(summaries) return { "topic": topic, "insights": final_insights, "sources_count": len(search_results) } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/traces/pattern.py* **Benefits of this pattern:** - If `search_web` succeeds but `summarize_content` fails, resumption skips the search step - Each operation is independently observable and debuggable - Clear separation between workflow coordination (task) and execution (traced functions) ## Relationship to caching and checkpointing Understanding how traces work with Flyte's other execution features: | Feature | Scope | Purpose | Default Behavior | |---------|-------|---------|------------------| | **Task Caching** | Entire task execution (`@env.task`) | Skip re-running tasks with same inputs | Disabled (enable with `cache="auto"`) | | **Traces** | Individual helper functions | Observability and fine-grained resumption | Manual (requires `@flyte.trace`) | | **Checkpointing** | Workflow state | Resume workflows from failure points | Automatic when traces are used | ### How they work together ``` @flyte.trace async def traced_data_cleaning(dataset_id: str) -> List[str]: # Creates checkpoint after successful execution. await asyncio.sleep(0.2) return [f"cleaned_record_{i}_{dataset_id}" for i in range(100)] @flyte.trace async def traced_feature_extraction(data: List[str]) -> dict: # Creates checkpoint after successful execution. await asyncio.sleep(0.3) return { "features": [f"feature_{i}" for i in range(10)], "feature_count": len(data), "processed_samples": len(data) } @flyte.trace async def traced_model_training(features: dict) -> dict: # Creates checkpoint after successful execution. await asyncio.sleep(0.4) sample_count = features["processed_samples"] # Mock accuracy based on sample count accuracy = min(0.95, 0.7 + (sample_count / 1000)) return { "accuracy": accuracy, "epochs": 50, "model_size": "125MB" } @env.task(cache="auto") # Task-level caching enabled async def data_pipeline(dataset_id: str) -> dict: # 1. If this exact task with these inputs ran before, # the entire task result is returned from cache # 2. If not cached, execution begins and each traced function # creates checkpoints for resumption cleaned_data = await traced_data_cleaning(dataset_id) # Checkpoint 1 features = await traced_feature_extraction(cleaned_data) # Checkpoint 2 model_results = await traced_model_training(features) # Checkpoint 3 # 3. If workflow fails at step 3, resumption will: # - Skip traced_data_cleaning (checkpointed) # - Skip traced_feature_extraction (checkpointed) # - Re-run only traced_model_training return {"dataset_id": dataset_id, "accuracy": model_results["accuracy"]} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/traces/caching_vs_checkpointing.py* ### Execution flow 1. **Task Submission**: Task is submitted with input parameters 2. **Cache Check**: Flyte checks if identical task execution exists in cache 3. **Cache Hit**: If cached, return cached result immediately (no traces needed) 4. **Cache Miss**: Begin fresh execution 5. **Trace Checkpoints**: Each `@flyte.trace` call that returns a value from a function with a declared return type creates a resumption point 6. **Failure Recovery**: If workflow fails, resume from last successful checkpoint 7. **Task Completion**: Final result is cached for future identical inputs === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/intra-task-checkpoints === Save progress inside a long-running task so a retry does not start over. # Intra-task checkpoints Long-running tasks (model training especially) can fail partway through: a spot instance is reclaimed, a pod is evicted, an out-of-memory error kills the process. When the task is retried, it normally starts over from the beginning. Intra-task checkpoints let a task save in-progress state to object storage as it runs and load that state at the start of the next attempt, so a retry resumes from where the previous attempt left off instead of repeating completed work. ## The checkpoint object Inside a running task, `flyte.ctx().checkpoint` returns a `flyte.Checkpoint` (or `None` when checkpointing isn't configured) bound to the action's checkpoint location in object storage: - **Save**: `await checkpoint.save(...)` (async tasks) or `checkpoint.save_sync(...)` (sync tasks and synchronous framework callbacks). Accepts raw `bytes`, a file path, or a directory path; a directory is stored as a single compressed archive. - **Load**: `await checkpoint.load()` or `checkpoint.load_sync()`. Returns a local `pathlib.Path` to the restored file or directory tree, or `None` when there is no previous checkpoint (i.e. on the first attempt). - `flyte.latest_checkpoint(root, glob_pattern="**/last.ckpt")` finds the newest checkpoint file under a restored directory tree, useful for frameworks like PyTorch Lightning that write `last.ckpt` files into a directory. Checkpoints only matter when the task can run more than once, so give the task retries with `@env.task(retries=...)`. Each retry attempt sees the checkpoint saved by the attempt before it. > [!NOTE] Checkpoints vs. caching vs. traces > > - **Task caching** skips an entire task when it has already run with the same inputs. > - ****Tasks > Build tasks > Traces**** checkpoint at the boundaries of helper functions called by a task. > - **Intra-task checkpoints** save state *within* a single task body (mid-loop, > mid-epoch) across retry attempts of the same action. ## Basic usage The simplest checkpoint is a raw byte payload. This task counts up to `n_iterations`, saving its progress on every iteration. A simulated failure kills it partway through; the retry loads the saved counter and continues rather than restarting from zero: ### Async ``` import flyte env = flyte.TaskEnvironment(name="checkpoint_generic") RETRIES = 3 @env.task(retries=RETRIES) async def use_checkpoint(n_iterations: int = 10) -> int: checkpoint = flyte.ctx().checkpoint # Load the previous attempt's checkpoint, if any. # On the first attempt there is none, so load() returns None. path = await checkpoint.load() start = int(path.read_bytes()) if path else 0 failure_interval = n_iterations // RETRIES index = start for index in range(start, n_iterations): if index > start and index % failure_interval == 0: # Simulate a failure so the next attempt resumes from the checkpoint raise RuntimeError(f"Simulated failure at iteration {index}") # Persist progress to object storage. await checkpoint.save(f"{index + 1}".encode()) return index ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/generic_checkpoint.py* ### Sync ``` import flyte env = flyte.TaskEnvironment(name="checkpoint_generic_sync") RETRIES = 3 @env.task(retries=RETRIES) def use_checkpoint(n_iterations: int = 10) -> int: checkpoint = flyte.ctx().checkpoint # Load the previous attempt's checkpoint, if any. # On the first attempt there is none, so load_sync() returns None. path = checkpoint.load_sync() start = int(path.read_bytes()) if path else 0 failure_interval = n_iterations // RETRIES index = start for index in range(start, n_iterations): if index > start and index % failure_interval == 0: # Simulate a failure so the next attempt resumes from the checkpoint raise RuntimeError(f"Simulated failure at iteration {index}") # Persist progress to object storage. checkpoint.save_sync(f"{index + 1}".encode()) return index ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/generic_checkpoint_sync.py* Running this with `n_iterations=10` produces three failed attempts and one successful one. Each attempt fails later than the last, because each one starts from the checkpoint its predecessor saved. ## Checkpointing ML training frameworks The same pattern applies to real training loops, whatever the framework: 1. **Load** the previous attempt's checkpoint at the start of the task; if one exists, restore the model/optimizer state and work out where to resume. 2. **Save** a checkpoint at a regular interval (every epoch or every N steps) as training progresses. Frameworks with their own checkpoint files (PyTorch Lightning, Hugging Face `Trainer`) already write them to a local directory; there you hook their callback system and mirror that directory to the Flyte checkpoint, then feed the restored directory back to the framework's native resume mechanism. ### PyTorch Save the model state dict, optimizer state, and epoch counter with `torch.save` after each epoch, and restore all three with `torch.load` on retry:
``` @env.task(retries=RETRIES) async def train_linear(epochs: int = 10) -> float: checkpoint = flyte.ctx().checkpoint model = nn.Linear(4, 1) opt = torch.optim.SGD(model.parameters(), lr=0.01) # Resume model, optimizer, and epoch from the previous attempt, if any. prev = await checkpoint.load() if prev: blob = torch.load(prev, map_location="cpu", weights_only=False) model.load_state_dict(blob["model"]) opt.load_state_dict(blob["opt"]) start = int(blob["epoch"]) + 1 else: start = 0 wpath = pathlib.Path("pytorch_linear") / "training.pt" wpath.parent.mkdir(parents=True, exist_ok=True) failure_interval = epochs // RETRIES for epoch in range(start, epochs): x = torch.randn(8, 4) y = torch.randn(8, 1) loss = torch.nn.functional.mse_loss(model(x), y) opt.zero_grad() loss.backward() opt.step() if epoch > start and epoch % failure_interval == 0: # Simulate a failure so the next attempt resumes from the checkpoint raise RuntimeError(f"Simulated failure at epoch {epoch}") # Save model, optimizer, and epoch state to object storage. torch.save( {"model": model.state_dict(), "opt": opt.state_dict(), "epoch": epoch}, wpath, ) await checkpoint.save(wpath) with torch.no_grad(): return float(model(torch.ones(1, 4)).squeeze().item()) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/pytorch_checkpoint.py* ### PyTorch Lightning Lightning already writes `last.ckpt` through its `ModelCheckpoint` callback. Subclass it to mirror the checkpoint directory to Flyte after each epoch (Lightning callbacks are synchronous, so use `flyte.Checkpoint.save_sync`):
``` class FlyteLightningCheckpointCallback(ModelCheckpoint): """A `ModelCheckpoint` that mirrors `dirpath` to the Flyte checkpoint after each epoch.""" def __init__(self, flyte_checkpoint: flyte.Checkpoint, *, dirpath: str | pathlib.Path, **kwargs) -> None: super().__init__(dirpath=str(dirpath), **kwargs) self._flyte_checkpoint = flyte_checkpoint @override def on_train_epoch_end(self, trainer: L.Trainer, pl_module: L.LightningModule) -> None: super().on_train_epoch_end(trainer, pl_module) if self.dirpath: # Lightning callbacks are synchronous, so use save_sync self._flyte_checkpoint.save_sync(pathlib.Path(self.dirpath)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/pytorch_lightning_checkpoint.py* In the task, restore the previous tree, pick the newest `last.ckpt` with `flyte.latest_checkpoint(restored_root, glob_pattern="**/last.ckpt")`, and hand it to `Trainer.fit(ckpt_path=...)`; Lightning restores the model, optimizer, and epoch from there:
CODE3 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/pytorch_lightning_checkpoint.py* ### Hugging Face Trainer `transformers.Trainer` writes `checkpoint-` directories under its `output_dir` (here, every epoch via `save_strategy="epoch"`). A `TrainerCallback` mirrors that directory to Flyte after each save:
``` class FlyteTrainerCheckpointCallback(TrainerCallback): """Mirror the Trainer's `output_dir` to the Flyte checkpoint after each epoch.""" def __init__(self, checkpoint: flyte.Checkpoint, output_dir: pathlib.Path) -> None: self._checkpoint = checkpoint self._output_dir = output_dir def on_epoch_end(self, args, state, control, **kwargs) -> None: # Trainer callbacks are synchronous, so use save_sync self._checkpoint.save_sync(self._output_dir) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/huggingface_trainer_checkpoint.py* On retry, restore the tree, locate the last Hugging Face checkpoint with `get_last_checkpoint`, and pass it to `trainer.train(resume_from_checkpoint=...)`:
CODE4 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/huggingface_trainer_checkpoint.py* ### scikit-learn For estimators that support incremental training with `partial_fit`, pickle the estimator together with a progress counter after each training chunk. A retry unpickles the bundle and continues from the next chunk:
CODE5 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/sklearn_partial_checkpoint.py* ### Unsloth LoRA fine-tuning with [Unsloth](https://unsloth.ai/) and `trl.SFTTrainer` uses the same callback-and-resume pattern as the Hugging Face `Trainer`, since `SFTTrainer` is built on it. Unsloth requires an NVIDIA, AMD, or Intel GPU, so the task environment requests one:
CODE6 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/unsloth_sft_checkpoint.py* > [!NOTE] Simulated failures in the runnable examples > The full example files for the basic, PyTorch, and scikit-learn cases inject a > failure at a regular interval (`failure_interval`) so you can watch the retries > resume from the checkpoint. In production code you would drop those lines; real > failures (preemptions, OOMs, crashes) trigger the same resume path. ## How checkpoints are stored Each action attempt gets a checkpoint prefix in the object store configured for your cluster. `flyte.Checkpoint.save` uploads a file as-is, stores a directory as a gzip-compressed tarball, and accepts raw `bytes` as a single blob. `flyte.Checkpoint.load` downloads the previous attempt's object into a local temporary workspace and returns the path: a restored directory tree, or the path to the single restored file. Saving repeatedly overwrites the same checkpoint object, so the cost of frequent checkpointing is upload bandwidth, not unbounded storage growth. Checkpoint how often you can afford to lose work: every epoch is typical for training loops. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/grouping-actions === Cluster related actions together so a large run stays readable in the UI. # Grouping actions Groups are an organizational feature in Flyte that allow you to logically cluster related task invocations (called "actions") for better visualization and management in the UI. Groups help you organize task executions into manageable, hierarchical structures regardless of whether you're working with large fanouts or smaller, logically-related sets of operations. ## What are groups? Groups provide a way to organize task invocations into logical units in the Flyte UI. When you have multiple task executions (whether from large **Tasks > Build tasks > Fanout**, sequential operations, or any combination of tasks), groups help organize them into manageable units. ### The problem groups solve Without groups, complex workflows can become visually overwhelming in the Flyte UI: - Multiple task executions appear as separate nodes, making it hard to see the high-level structure - Related operations are scattered throughout the workflow graph - Debugging and monitoring becomes difficult when dealing with many individual task executions Groups solve this by: - **Organizing actions**: Multiple task executions within a group are presented as a hierarchical "folder" structure - **Improving UI visualization**: Instead of many individual nodes cluttering the view, you see logical groups that can be collapsed or expanded - **Aggregating status information**: Groups show aggregated run status (success/failure) of their contained actions when you hover over them in the UI - **Maintaining execution parallelism**: Tasks still run concurrently as normal, but are organized for display ### How groups work Groups are declared using the `flyte.group` context manager. Any task invocations that occur within the `with flyte.group()` block are automatically associated with that group: ```python with flyte.group("my-group-name"): # All task invocations here belong to "my-group-name" result1 = await task_a(data) result2 = await task_b(data) result3 = await task_c(data) ``` The key points about groups: 1. **Context-based**: Use the `with flyte.group("name"):` context manager. 2. **Organizational tool**: Task invocations within the context are grouped together in the UI. 3. **UI folders**: Groups appear as collapsible/expandable folders in the Flyte UI run tree. 4. **Status aggregation**: Hover over a group in the UI to see aggregated success/failure information. 5. **Execution unchanged**: Tasks still execute in parallel as normal; groups only affect organization and visualization. **Important**: Groups do not aggregate outputs. Each task execution still produces its own individual outputs. Groups are purely for organization and UI presentation. ## Common grouping patterns ### Sequential operations Group related sequential operations that logically belong together: ``` @env.task async def data_pipeline(raw_data: str) -> str: with flyte.group("data-validation"): validated_data = await process_data(raw_data, "validate_schema") validated_data = await process_data(validated_data, "check_quality") validated_data = await process_data(validated_data, "remove_duplicates") with flyte.group("feature-engineering"): features = await process_data(validated_data, "extract_features") features = await process_data(features, "normalize_features") features = await process_data(features, "select_features") with flyte.group("model-training"): model = await process_data(features, "train_model") model = await process_data(model, "validate_model") final_model = await process_data(model, "save_model") return final_model ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/grouping-actions/grouping.py* ### Parallel processing with groups Groups work well with parallel execution patterns: ``` @env.task async def parallel_processing_example(n: int) -> str: tasks = [] with flyte.group("parallel-processing"): # Collect all task invocations first for i in range(n): tasks.append(process_item(i, "transform")) # Execute all tasks in parallel results = await asyncio.gather(*tasks) # Convert to string for consistent return type return f"parallel_results: {results}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/grouping-actions/grouping.py* ### Multi-phase workflows Use groups to organize different phases of complex workflows: ``` @env.task async def multi_phase_workflow(data_size: int) -> str: # First phase: data preprocessing preprocessed = [] with flyte.group("preprocessing"): for i in range(data_size): preprocessed.append(process_item(i, "preprocess")) phase1_results = await asyncio.gather(*preprocessed) # Second phase: main processing processed = [] with flyte.group("main-processing"): for result in phase1_results: processed.append(process_item(result, "transform")) phase2_results = await asyncio.gather(*processed) # Third phase: postprocessing postprocessed = [] with flyte.group("postprocessing"): for result in phase2_results: postprocessed.append(process_item(result, "postprocess")) final_results = await asyncio.gather(*postprocessed) # Convert to string for consistent return type return f"multi_phase_results: {final_results}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/grouping-actions/grouping.py* ### Conditional grouping Groups can be used with conditional logic: ``` @env.task async def conditional_processing(use_advanced_features: bool, input_data: str) -> str: base_result = await process_data(input_data, "basic_processing") if use_advanced_features: with flyte.group("advanced-features"): enhanced_result = await process_data(base_result, "advanced_processing") optimized_result = await process_data(enhanced_result, "optimize_result") return optimized_result else: with flyte.group("basic-features"): simple_result = await process_data(base_result, "simple_processing") return simple_result ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/grouping-actions/grouping.py* ## Key insights Groups are primarily an organizational and UI visualization tool; they don't change how your tasks execute or aggregate their outputs, but they help organize related task invocations (actions) into collapsible folder-like structures for better workflow management and display. The aggregated status information (success/failure rates) is visible when hovering over group folders in the UI. Groups make your Flyte workflows more maintainable and easier to understand, especially when working with complex workflows that involve multiple logical phases or large numbers of task executions. They serve as organizational "folders" in the UI's call stack tree, allowing you to collapse sections to reduce visual distraction while still seeing aggregated status information on hover. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/fanout === Run many tasks in parallel, and what changes at large scale. # Fanout Flyte is designed to scale, allowing you to run workflows with large fanouts. When you need to execute many tasks in parallel (such as processing a large dataset or running hyperparameter sweeps), Flyte provides powerful patterns to implement these operations efficiently. > **๐Ÿ“ Note** > > In Flyte 1, mapping a task over many inputs used `map_task()` (the `flytekit.map_task` API). In Flyte 2, fan out with `asyncio.gather()` or `flyte.map()`. This page covers the general `asyncio.gather` fanout pattern. For applying the *same* task to every item of a list (the direct successor to Flyte 1's `map_task`), see **Tasks > Build tasks > Mapping over inputs**. That page also covers concurrency limits, error handling, and use with reusable environments. > [!NOTE] > By default fanouts in Union are limited to a maximum size. > Adjustment can made to this maximum by consulting with the Union team. > Full documentation of this aspect of fanout is coming soon. ## Understanding fanout A "fanout" pattern occurs when you spawn multiple tasks concurrently. Each task runs in its own container and contributes an output that you later collect. The most common way to implement this is using the [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) function. In Flyte terminology, each individual task execution is called an "action": this represents a specific invocation of a task with particular inputs. When you call a task multiple times in a loop, you create multiple actions. ## Example We start by importing our required packages, defining our Flyte environment, and creating a simple task that fetches user data from a mock API. ``` import asyncio from typing import List, Tuple import flyte env = flyte.TaskEnvironment("fanout_env") @env.task async def fetch_data(user_id: int) -> dict: """Simulate fetching user data from an API - good for parallel execution.""" # Simulate network I/O delay await asyncio.sleep(0.1) return { "user_id": user_id, "name": f"User_{user_id}", "score": user_id * 10, "data": f"fetched_data_{user_id}" } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/fanout/fanout.py* ### Parallel execution Next we implement the most common fanout pattern, which is to collect task invocations and execute them in parallel using `asyncio.gather()`: ``` @env.task async def parallel_data_fetching(user_ids: List[int]) -> List[dict]: """Fetch data for multiple users in parallel - ideal for I/O bound operations.""" tasks = [] # Collect all fetch tasks - these can run in parallel since they're independent for user_id in user_ids: tasks.append(fetch_data(user_id)) # Execute all fetch operations in parallel results = await asyncio.gather(*tasks) return results ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/fanout/fanout.py* ### Running the example To actually run our example, we create a main guard that initializes Flyte and runs our main driver task: ``` if __name__ == "__main__": flyte.init_from_config() user_ids = [1, 2, 3, 4, 5] r = flyte.run(parallel_data_fetching, user_ids) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/fanout/fanout.py* ## How Flyte handles concurrency and parallelism In the example we use a standard `asyncio.gather()` pattern. When this pattern is used in a normal Python environment, the tasks would execute **concurrently** (cooperatively sharing a single thread through the event loop), but not in true **parallel** (multiple CPU cores simultaneously). However, **Flyte transforms this concurrency model into true parallelism**. When you use `asyncio.gather()` in a Flyte task: 1. **Flyte acts as a distributed event loop**: Instead of scheduling coroutines on a single machine, Flyte schedules each task action to run in its own container across the cluster 2. **Concurrent becomes parallel**: What would be cooperative multitasking in regular Python becomes true parallel execution across multiple machines 3. **Native Python patterns**: You use familiar `asyncio` patterns, but Flyte automatically distributes the work This means that when you write: ```python results = await asyncio.gather(fetch_data(1), fetch_data(2), fetch_data(3)) ``` Instead of three coroutines sharing one CPU, you get three separate containers running simultaneously, each with their own CPU, memory, and resources. Flyte bridges the gap between Python's concurrency model and distributed parallel computing, allowing for massive scalability while maintaining the familiar async/await programming model. ## Iterative fanout: recursive feature elimination Fanout isn't limited to a single parallel burst; you can fan out **repeatedly**, using the results of one round to shape the next. A good real-world example is [recursive feature elimination (RFE)](https://github.com/flyteorg/flyte-sdk/blob/main/examples/ml/rfe.py), a feature-selection technique that repeatedly trains a model with one candidate feature held out, drops the feature whose removal least hurts the score, and repeats until a single feature remains. Every iteration is itself a fanout: for each remaining feature, a `train` action runs in parallel with that feature dropped, scored by cross-validation. The `train` task evaluates the model with a single feature held out and returns its cross-validated score: ```python @worker.task async def train(features: list[str], drop: str) -> float: features.remove(drop) X, y = fetch_california_housing(as_frame=True, return_X_y=True) fold = KFold(n_splits=5, random_state=42, shuffle=True) model = LinearRegression() scores = cross_val_score(estimator=model, X=X[features], y=y, cv=fold, scoring="r2") return float(scores.mean()) ``` The `rfe` driver task runs the elimination loop. Each round wraps its fanout in a `flyte.group` context (see **Tasks > Build tasks > Grouping actions**) so the iterations appear as collapsible folders in the UI, and uses `asyncio.gather()` to evaluate every candidate feature in parallel: ```python @worker.task async def rfe(): x, _y = fetch_california_housing(as_frame=True, return_X_y=True) features = list(x.columns) for i in range(len(features) - 1): with flyte.group(f"iteration-{i}"): runs = {feature: train(list(features), drop=feature) for feature in features} values = await asyncio.gather(*(runs[feature] for feature in runs)) scores = dict(zip(runs.keys(), values)) best = max(scores, key=scores.get) features.remove(best) ``` Because each `train` call becomes its own action, every iteration's candidate evaluations run as separate containers in true parallel, while grouping keeps the nested rounds organized in the run tree. > **๐Ÿ“ Note** > > The full runnable example lives in the [Flyte SDK repository](https://github.com/flyteorg/flyte-sdk/blob/main/examples/ml/rfe.py). From a local checkout of the `flyte-sdk` repository, run it with `uv run --prerelease=allow examples/ml/rfe.py` (the command uses a repo-relative path). === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/map === Apply one task across every item of an iterable, in parallel. # Mapping over inputs `flyte.map` applies a single task to every item of one or more input iterables, running the invocations in parallel across the cluster and yielding their results **in input order**. It is the structured way to **Tasks > Build tasks > Fanout** uniform work: instead of assembling a list of coroutines by hand and passing them to `asyncio.gather`, you hand `flyte.map` the task and the inputs and it produces one action per item. Use `flyte.map` when every item goes through the *same* task. For fanning out across *different* tasks, or for full control over how invocations are assembled, use `asyncio.gather`. See **Tasks > Build tasks > Fanout**. ## Minimal example From a **synchronous** task, iterate the results with a plain `for` loop: ```python from typing import List import flyte env = flyte.TaskEnvironment(name="map-example") @env.task def process(x: int) -> str: return f"result-{x}" @env.task def main(n: int) -> List[str]: results: List[str] = [] for r in flyte.map(process, range(n)): if isinstance(r, Exception): raise r results.append(r) return results if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, 10) print(run.url) ``` Each item in `range(n)` becomes its own action, running in its own container, and the results come back in the same order as the inputs. ## Mapping from an async task: `flyte.map.aio` `flyte.map` returns a synchronous iterator. Inside an **async** task, use `flyte.map.aio`, which returns an async iterator you consume with `async for`: ```python @env.task async def main(n: int) -> List[str]: results: List[str] = [] async for r in flyte.map.aio(process, range(n)): if isinstance(r, Exception): raise r results.append(r) return results ``` `flyte.map.aio` works over both async and sync tasks, so you can call an existing synchronous task in parallel from an async context without rewriting it: useful when migrating a Flyte 1.x `map_task` or integrating legacy sync code. ## Signature and parameters ```python flyte.map( func, # the task (or functools.partial) to apply to each item *args, # one or more iterables, zipped item-by-item into func's arguments group_name=None, # optional name for the group of mapped actions (UI grouping) concurrency=0, # max actions in flight at once; 0 means unbounded (all at once) return_exceptions=True, ) ``` - **`func`**: the task to map. It receives one item per invocation. To hold some arguments constant across the map, wrap it with `functools.partial` (see **Tasks > Build tasks > Mapping over inputs > Binding constant arguments with `functools.partial`**). - **`*args`**: one or more input iterables. With multiple iterables they are **zipped**: the *i*-th invocation receives the *i*-th element of each, matching `func`'s positional parameters in order. - **`group_name`**: groups the resulting actions under a single label in the UI (see **Tasks > Build tasks > Grouping actions**). - **`concurrency`**: the maximum number of actions in flight at any moment. `0` (the default) submits everything at once. A positive value bounds the fan-out with a worker pool, so memory stays proportional to `concurrency` rather than to the total number of items. See **Tasks > Build tasks > Controlling parallel execution**. - **`return_exceptions`**: when `True` (the default), a failed invocation yields the raised exception as its result instead of aborting the whole map; check each result with `isinstance(r, Exception)`. When `False`, the first failure stops iteration and raises. Results are always yielded **in the order of the inputs**, regardless of the order in which the individual actions finish. ## Limiting concurrency For rate-limited APIs, GPU quotas, or connection limits, cap how many actions run at once with the `concurrency` parameter: ```python async for r in flyte.map.aio(call_llm_api, prompts, concurrency=3): ... ``` Only three actions are in flight at a time; as each completes, the next input is submitted. For a full comparison of `flyte.map(concurrency=N)` against `asyncio.Semaphore`, see **Tasks > Build tasks > Controlling parallel execution**. > [!NOTE] > `concurrency` limits how many actions run *at once*; it does not reduce the *total* number of > actions the map creates. A large map still counts every item against the run-level ceiling > (currently 200k actions per run). To keep a large fan-out under that limit, batch items so the map > produces fewer actions โ€” see > **Tasks > Build tasks > Controlling parallel execution > Per-map concurrency vs. the run-level action cap** > and **Scale your runs > Scale your workflows**. ## Handling errors By default (`return_exceptions=True`) the map runs to completion even if some invocations fail, and each failure surfaces as an exception object in the results stream: ```python @env.task def maybe_fail(x: int) -> str: if x == 2: raise ValueError("bad input") return f"ok-{x}" @env.task def main(n: int) -> None: for r in flyte.map(maybe_fail, range(n)): if isinstance(r, Exception): print(f"error: {r}") else: print(r) ``` Set `return_exceptions=False` to fail fast instead: iteration raises on the first failed action. ## Binding constant arguments with `functools.partial` Often you want to map over one argument while holding others constant. Bind the constants with `functools.partial`, leaving exactly one parameter free. That's the one `flyte.map` varies: ```python from functools import partial import flyte env = flyte.TaskEnvironment(name="map-partial") @env.task def score(compound_id: str, model_name: str, batch_id: str) -> str: return f"{compound_id}:{model_name}:{batch_id}" @env.task def main() -> None: compounds = [str(i) for i in range(3)] scorer = partial(score, model_name="v2", batch_id="run-42") # compound_id is the only parameter left unbound, so it is what map varies. results = list(flyte.map(scorer, compounds)) print("\n".join(results)) ``` `flyte.map` inserts each mapped value **positionally, right after the partial's bound positional arguments**, and requires **exactly one** parameter to be left unbound. Above, `model_name` and `batch_id` are bound as keywords, so the mapped value fills the first slot: `compound_id`. To vary a *later* parameter, bind the ones before it positionally and the ones after it by keyword. For example, `partial(score, "compound-1", batch_id="run-42")` maps `model_name`. `flyte.map` raises a `TypeError` if more or fewer than one parameter is left unbound, or if the mapped positional slot is also bound as a keyword. ## Mapping with reusable environments `flyte.map` composes naturally with **Tasks > Configure tasks > Reusable containers**: a warm pool of persistent containers that survive across invocations, eliminating per-action container startup overhead. This is the highest-throughput way to run a large map of short tasks. Attach a `flyte.ReusePolicy` to the task's `flyte.TaskEnvironment`, then map over it as usual: ```python import flyte env = flyte.TaskEnvironment( name="map-reusable", image=flyte.Image.from_debian_base().with_pip_packages("unionai-reuse"), reusable=flyte.ReusePolicy(replicas=4, concurrency=3), ) @env.task async def process(x: int) -> str: return f"result-{x}" @env.task async def main(n: int) -> list[str]: results: list[str] = [] async for r in flyte.map.aio(process, range(n)): if isinstance(r, Exception): raise r results.append(r) return results ``` The mapped actions are routed onto the reusable pool instead of each spinning up a fresh container. Two concurrency controls are in play, and they are independent: - **`ReusePolicy(replicas, concurrency)`** sizes the pool: total capacity is `replicas ร— concurrency` actions running at once (here, `4 ร— 3 = 12`). - **`flyte.map(concurrency=N)`** bounds how many map actions are submitted at once. Leave it at `0` to let the pool absorb the full fan-out, or set it to shape submission independently of pool size. > [!NOTE] > Reusable containers require the > [`unionai-reuse`](https://pypi.org/project/unionai-reuse/) runtime library in the task image, as > shown above. See **Tasks > Configure tasks > Reusable containers** for the full > `ReusePolicy` parameter reference and lifecycle details. ## Caching Caching is configured on the **task**, not on the map call: give the mapped task a **Tasks > Configure tasks > Caching** and each item is cached **independently**, because every item runs as its own task action with its own inputs. An item whose inputs are unchanged is a cache hit even when other items change or the list is reordered. Constant arguments bound with `functools.partial` become part of each item's cache key, so use **Tasks > Configure tasks > Caching > Caching with `flyte.map` > Excluding a bound argument from the per-element key** to exclude a bound value that shouldn't affect caching. See **Tasks > Configure tasks > Caching > Caching with `flyte.map`** for details. ## When to use `flyte.map` Reach for `flyte.map` when: - Every item goes through the **same** task. - You want built-in, in-order result collection and per-item error capture. - You want simple, declarative concurrency control via the `concurrency` parameter. Use **Tasks > Build tasks > Fanout** instead when you are fanning out across **different** tasks in one batch, or when you need full control over how the coroutines are assembled. Use an **Tasks > Build tasks > Controlling parallel execution** when different task types in the same batch need different concurrency limits. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/consuming-a-message-queue === Build a long-running task that pulls messages from an external queue such as SQS. # Consuming a message queue A common production pattern is a **queue consumer**: a long-running task that pulls messages from an external message queue (such as [AWS SQS](https://aws.amazon.com/sqs/)) and processes each message concurrently. Flyte 2 expresses this naturally by combining three building blocks you have already seen: - **Async tasks**: the consumer loop is an `async def` task that awaits I/O against the queue. - **Tasks > Build tasks > Fanout**: each received message is dispatched to its own `process_message` action with `asyncio.create_task()`, so processing runs in parallel across the cluster. - **Tasks > Configure tasks > Reusable containers**: a `ReusePolicy` keeps a warm pool of replicas ready, so messages are processed without per-message container cold-start. The complete, runnable source for this example, a producer (`generator.py`) and a consumer (`processor.py`), lives in the Flyte SDK repository under [`examples/queue-reader`](https://github.com/flyteorg/flyte-sdk/tree/main/examples/queue-reader). > [!NOTE] > This example reads from AWS SQS and therefore requires an SQS queue and AWS credentials > available to the running task (here the queue is passed as an ARN via the `QUEUE_ARN` > environment variable). The Flyte pattern shown below applies to any external queue: swap > the SQS client calls for your queue's client. ## The consumer ### Define the task environment The consumer runs in a **Tasks > Configure tasks > Reusable containers** `TaskEnvironment`. `replicas=3` keeps a warm pool of at least two replicas to avoid starvation while the parent consumer task occupies one, and `idle_ttl=300` shuts the pool down after five minutes of inactivity. The image is built from the script's own inline dependencies with `flyte.Image.from_uv_script`, plus the `unionai-reuse` runtime library that reusable containers require: ```python # /// script # requires-python = "==3.13" # dependencies = [ # "flyte", # "aioboto3>=11.3.0", # "asyncio", # ] # /// import asyncio import json import os from typing import List import aioboto3 import flyte env = flyte.TaskEnvironment( name="sqs_processor", resources=flyte.Resources(memory="500Mi", cpu=1), image=flyte.Image.from_uv_script( __file__, name="flyte", ).with_pip_packages("unionai-reuse>=0.1.3"), reusable=flyte.ReusePolicy( replicas=3, # 1 for the consumer loop + 2 workers, so processing never starves idle_ttl=300, # Idle time to keep the task environment alive ), ) # The queue is passed as an ARN via the QUEUE_ARN environment variable. DEFAULT_QUEUE_ARN = os.getenv("QUEUE_ARN") def get_queue_url_from_arn(queue_arn: str) -> str: """Convert an SQS ARN to a queue URL.""" parts = queue_arn.split(":") region = parts[3] account = parts[4] queue_name = parts[5] return f"https://sqs.{region}.amazonaws.com/{account}/{queue_name}" ``` ### Process a single message Each message is handled by its own task. These tasks run in parallel across the reusable pool, bounded by the number of worker replicas: with `replicas=3` and the default `concurrency=1`, the parent consumer loop occupies one replica and the other two each process a single message at a time, so about two messages are handled concurrently. To let a single replica handle more than one message at once, raise `concurrency` above 1: ```python @env.task async def process_message(message: dict) -> str: """Process a single message asynchronously and return the extracted word.""" body = json.loads(message["Body"]) word = body.get("word", "unknown") print(f"Task Processing message {body.get('message_id')}: {word}") return word ``` ### The consumer loop The driver task long-polls the queue, and for each message it receives it **dispatches a `process_message` action with `asyncio.create_task()`** rather than awaiting it inline. This is what fans the work out in parallel. It deletes each message once processing has started, then awaits all dispatched tasks with `asyncio.gather()`: ```python @env.task async def main(queue_arn: str = DEFAULT_QUEUE_ARN, max_messages: int = 10) -> List[str]: queue_url = get_queue_url_from_arn(queue_arn) session = aioboto3.Session(region_name="us-east-2") results = [] tasks = [] messages_received = 0 async with session.client("sqs") as sqs: while messages_received < max_messages: response = await sqs.receive_message( QueueUrl=queue_url, AttributeNames=["All"], MaxNumberOfMessages=1, # one message at a time WaitTimeSeconds=20, # long-polling timeout (max 20 seconds) ) messages = response.get("Messages", []) if not messages: continue message = messages[0] messages_received += 1 # Fan out: dispatch processing as a parallel action. process_task = asyncio.create_task(process_message(message)) tasks.append(process_task) # Delete the message once we've started processing it. await sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=message["ReceiptHandle"]) # Wait for all dispatched processing tasks to complete. if tasks: completed_tasks = await asyncio.gather(*tasks) results.extend(completed_tasks) return results ``` ### Run it Initialize Flyte from your config and run the consumer remotely: ```python if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, queue_arn=DEFAULT_QUEUE_ARN, max_messages=10) print(run.url) ``` ## The producer To exercise the consumer, the example includes a standalone [`generator.py`](https://github.com/flyteorg/flyte-sdk/tree/main/examples/queue-reader) that pushes ten JSON messages onto the same SQS queue with `boto3`. It is an ordinary Python script, not a Flyte task. Any producer that writes to the queue will do. ## Notes and gotchas - **Delete after receive, not after processing completes.** The example deletes each message as soon as it dispatches the processing task. If a `process_message` action can fail and you need at-least-once semantics, delete the message only after the task succeeds instead. - **`max_messages` bounds the run.** The consumer loop here stops after `max_messages`. For a continuously running consumer, drive it on a [trigger](../../triggers/_index) or remove the bound and manage the task lifecycle explicitly. - **Reusable containers require a Union backend.** See **Tasks > Configure tasks > Reusable containers** for the `ReusePolicy` parameters (`replicas`, `concurrency`, `idle_ttl`, `scaledown_ttl`) and their capacity math. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/controlling-parallelism === Cap how many fanned-out tasks run at once, for rate limits and quotas. # Controlling parallel execution When you **Tasks > Build tasks > Fanout** to many tasks, you often need to limit how many run at the same time. Common reasons include rate-limited APIs, GPU quotas, database connection limits, or simply avoiding overwhelming a downstream service. Flyte 2 provides two ways to control concurrency: [`asyncio.Semaphore`](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Semaphore) for fine-grained control, and `flyte.map` with a built-in `concurrency` parameter for simpler cases. ## The problem: unbounded parallelism A straightforward `asyncio.gather` launches every task at once. If you are calling an external API that allows only a few concurrent requests, this can cause throttling or errors: ``` import asyncio import flyte env = flyte.TaskEnvironment("controlling_parallelism") @env.task async def call_llm_api(prompt: str) -> str: """Simulate calling a rate-limited LLM API.""" # In a real workflow, this would call an external API. # The API might allow only a few concurrent requests. await asyncio.sleep(0.5) return f"Response to: {prompt}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/controlling-parallelism/controlling_parallelism.py* ``` @env.task async def process_all_at_once(prompts: list[str]) -> list[str]: """Send all requests in parallel with no concurrency limit. This can overwhelm a rate-limited API, causing errors or throttling. """ results = await asyncio.gather(*[call_llm_api(p) for p in prompts]) return list(results) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/controlling-parallelism/controlling_parallelism.py* With eight prompts, this fires eight concurrent API calls. That works fine when there are no limits, but will fail when the API enforces a concurrency cap. ## Using asyncio.Semaphore An `asyncio.Semaphore` acts as a gate: only a fixed number of tasks can pass through at a time. The rest wait until a slot opens up. ``` @env.task async def process_batch_with_semaphore( prompts: list[str], max_concurrent: int = 3, ) -> list[str]: """Process prompts in parallel, limiting concurrency with a semaphore. At most `max_concurrent` calls to the API run at any given time. The remaining tasks wait until a slot is available. """ semaphore = asyncio.Semaphore(max_concurrent) async def limited_call(prompt: str) -> str: async with semaphore: return await call_llm_api(prompt) results = await asyncio.gather(*[limited_call(p) for p in prompts]) return list(results) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/controlling-parallelism/controlling_parallelism.py* The pattern is: 1. Create a semaphore with the desired limit. 2. Wrap each task call in an inner async function that acquires the semaphore before calling and releases it after. 3. Pass all wrapped calls to `asyncio.gather`. All eight tasks are submitted immediately, but the Flyte orchestrator only allows three to run in parallel. As each one completes, the next waiting task starts. > [!NOTE] > The semaphore controls how many tasks execute concurrently on the Flyte cluster. > Each task still runs in its own container with its own resources: the semaphore simply limits how many containers are active at a time. ## Using flyte.map with concurrency For uniform work (applying the same task to a list of inputs), `flyte.map` with the `concurrency` parameter is simpler: CODE2 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/controlling-parallelism/controlling_parallelism.py* This achieves the same concurrency limit with less boilerplate. For the full `flyte.map` treatment (signature, return order, error handling, partials, and use with reusable environments), see [Mapping over inputs](map.md). ## Running the example CODE3 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/controlling-parallelism/controlling_parallelism.py* ## When to use each approach Use **`flyte.map(concurrency=N)`** when: - Every item goes through the same task. - You want the simplest possible code. Use **`asyncio.Semaphore`** when: - You need different concurrency limits for different task types within the same workflow. - You want to combine concurrency control with error handling (e.g., `asyncio.gather(*tasks, return_exceptions=True)`). - You are calling multiple different tasks in one parallel batch. ## Per-map concurrency vs. the run-level action cap The `concurrency` parameter (and `asyncio.Semaphore`) throttle how many actions run **at the same time**. They do **not** change how many actions your run creates in total. These are two separate limits, and they compose: - **Per-map `concurrency`** bounds the *in-flight* actions **within one map** โ€” a moving window over the fan-out. `flyte.map(process, items, concurrency=10)` keeps at most ten actions running at once, but every item still becomes its own action; they are just submitted through a bounded worker pool as slots free up. - **The run-level action cap** bounds the *total* number of actions in the whole run. A run currently supports up to **200k tracked actions**. This ceiling counts **every** action across the run โ€” summed over all maps and all fan-out โ€” not just the ones in flight at any instant. See [Scale your workflows](../../run-scaling/scale-your-workflows.md). Because these limits are independent, **lowering `concurrency` does not help you stay under the run cap.** A `flyte.map` over 500,000 items creates 500,000 actions whether `concurrency` is `0` or `10` โ€” the throttle only slows how fast they are submitted, so such a run still exceeds the 200k ceiling. To fit under the cap you must reduce the *total* action count by [**batching**](../../run-scaling/scale-your-workflows.md): have each action process a batch of items, so a large input maps to far fewer actions. In practice, use the two controls for different jobs: - **Batch to stay well under the run cap.** Size batches so the total number of mapped actions stays below 200k, especially when a single run contains multiple maps or other fan-out โ€” they all count against the same ceiling. - **Set `concurrency` to protect downstream resources.** Independently of total count, cap in-flight actions to respect rate-limited APIs, GPU quotas, or connection limits, and to keep memory proportional to `concurrency` rather than to the full input size. For the full run-scaling picture โ€” task overhead, batch sizing, and fan-out control โ€” see **Scale your runs > Scale your workflows**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/streaming-map-reduce === Process fanned-out results as they finish instead of waiting for all of them. # Streaming map-reduce When you **Tasks > Build tasks > Fanout** with [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather), you wait for **every** task to finish before doing anything with the results. For a map-reduce workload that is wasteful: the reduce step sits idle until the slowest mapper returns. A better pattern is to process results **as they complete** โ€” accumulating them into batches and kicking off reduce operations incrementally, while the remaining map tasks are still running. This is a *gradual* (or *streaming*) map-reduce, and it is built on the standard-library [`asyncio.as_completed`](https://docs.python.org/3/library/asyncio-task.html#asyncio.as_completed) function. ## When to use it Reach for streaming map-reduce when: - Map tasks have **uneven durations**, so waiting for the slowest one wastes time the faster ones could spend reducing. - You are processing a **large number of items** and want to reduce in batches rather than holding every intermediate result in memory at once. - The reduce step is **associative** โ€” batch results can themselves be reduced into a final result (counts, sums, aggregations, embeddings, inference outputs). If you simply need all results before a single reduce, plain `asyncio.gather` (see **Tasks > Build tasks > Fanout**) is simpler. If your goal is to *cap* how many map tasks run at once, see **Tasks > Build tasks > Controlling parallel execution**; the two patterns compose. ## Example We define an environment and two tasks: one that maps over a single item, and one that reduces a batch of results. ```python import asyncio import random import flyte env = flyte.TaskEnvironment( name="streaming_map_reduce", resources=flyte.Resources(cpu="1"), ) @env.task async def process_item(item: str) -> str: print(f"Processing {item}", flush=True) # Simulate varying processing times so results finish out of order. await asyncio.sleep(random.uniform(1, 5)) return f"processed_{item}" @env.task async def reduce_batch(items: list[str]) -> str: print(f"Reducing batch of {len(items)} items") return f"reduced_batch_of_{len(items)}_items" ``` ### Speed up the map step with reusable containers The map step fans out many short `process_item` actions, each of which would otherwise pay container-startup cost. On Union.ai you can make them reuse warm workers instead by giving the environment a **Tasks > Configure tasks > Reusable containers**: ```python reusable_image = flyte.Image.from_debian_base(name="streaming").with_pip_packages("unionai-reuse>=0.1.10") env = flyte.TaskEnvironment( name="streaming_map_reduce", resources=flyte.Resources(cpu="1"), reusable=flyte.ReusePolicy(replicas=20, idle_ttl=30), image=reusable_image, ) ``` Reusable containers require a Union.ai backend, so this optimization is not available when running on an open-source Flyte backend. ### The driver task The driver fans out all the map tasks up front, then walks the results in completion order with `asyncio.as_completed`. Each time a batch fills up, it launches a `reduce_batch` action **without blocking** โ€” the loop keeps consuming newly completed map results while the reduce runs. ```python @env.task async def streaming_reduce_processing() -> str: input_items = [f"item_{i}" for i in range(100)] # Fan out: start every item task immediately. tasks = [asyncio.create_task(process_item(item)) for item in input_items] batch_size = 10 accumulated_values: list[str] = [] reducers: list[asyncio.Task] = [] print(f"Started {len(tasks)} tasks, will reduce in batches of {batch_size}") # Consume results as each task finishes, rather than waiting for all of them. for task in asyncio.as_completed(tasks): result = await task accumulated_values.append(result) # Once a batch has accumulated, kick off a reduce without blocking the loop. if len(accumulated_values) >= batch_size: print(f"Triggering reduce for batch of {len(accumulated_values)}") reducer_task = asyncio.create_task(reduce_batch(accumulated_values.copy())) reducers.append(reducer_task) accumulated_values.clear() # Reduce any stragglers that did not fill a full batch. if accumulated_values: print(f"Handling final batch of {len(accumulated_values)} stragglers") reducers.append(asyncio.create_task(reduce_batch(accumulated_values))) # Wait for every batch reduce to finish. reduced_results = await asyncio.gather(*reducers) # Combine the batch results into a single final result. final_result = await reduce_batch(reduced_results) print(f"Completed {len(reducers)} reduce operations, final result: {final_result}") return final_result ``` ### Running the example ```python if __name__ == "__main__": flyte.init_from_config() run = flyte.run(streaming_reduce_processing) print(run.url) ``` ## How it works The key building blocks are all standard `asyncio`: 1. **`asyncio.create_task(process_item(item))`** schedules each map action. Because `process_item` is a Flyte task, each of these runs in its own container on the cluster โ€” the fanout is real distributed parallelism, not single-machine concurrency (see **Tasks > Build tasks > Fanout** for how Flyte turns `asyncio` into distributed execution). 2. **`asyncio.as_completed(tasks)`** yields the task handles in the order they *finish*, not the order they were submitted. This is what lets the driver react to the fastest map results first. 3. **`asyncio.create_task(reduce_batch(...))`** launches each reduce as its own Flyte action and appends it to `reducers` without awaiting it, so map consumption and reduction overlap. 4. **`asyncio.gather(*reducers)`** joins all the in-flight batch reduces before the final combine step. The result is a pipeline where reduce work begins as soon as the first batch of map results is ready, instead of after the last map task returns. > [!NOTE] > `as_completed` returns awaitables in completion order but gives you no control over *how many* map tasks run at once โ€” it schedules all of them. > To bound the map fanout as well, combine this pattern with an `asyncio.Semaphore` or `flyte.map(concurrency=...)` from **Tasks > Build tasks > Controlling parallel execution**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/structured-concurrency-anyio === Use anyio or trio instead of asyncio, since the graph is built from what you await. # Structured concurrency with anyio Flyte builds a task's dependency graph from what you `await` โ€” not from any particular async library. `asyncio` is the default and the one used throughout the **Tasks > Build tasks > Fanout**, **Tasks > Build tasks > Controlling parallel execution**, and **Tasks > Build tasks > Task dependencies and ordering** guides, but it is not the only option. Any structured-concurrency runtime that drives coroutines works, and [`anyio`](https://anyio.readthedocs.io/) is a popular one. Its **task groups** give you a top-level alternative to raw `asyncio.gather` / `asyncio.create_task`, with clearer lifetime and error-propagation semantics. Use `anyio` when you want structured concurrency โ€” a scope that owns the tasks it spawns, waits for all of them on exit, and cancels the siblings automatically if one fails โ€” instead of tracking `asyncio.create_task` handles by hand. ## The task-group pattern An `anyio` task group is an `async with` block. You spawn work into it with `start_soon`, and the block does not exit until every spawned task has finished. Because task groups don't return the spawned tasks' values directly, this example uses [`aioresult`](https://aioresult.readthedocs.io/)'s `ResultCapture` to collect each result. We define a reusable environment and a simple per-item task. `anyio` and `aioresult` are ordinary pip dependencies, so we add them to the image: ```python from dataclasses import dataclass import aioresult import anyio import flyte env = flyte.TaskEnvironment( name="anyio_batch", resources=flyte.Resources(cpu="1"), image=flyte.Image.from_debian_base(name="anyio").with_pip_packages("anyio", "aioresult"), ) @dataclass class InferenceRequest: feature_a: float feature_b: float @env.task async def predict_one(request: InferenceRequest) -> float: # A dummy linear model: 2 * feature_a + 3 * feature_b + bias(=1.0) return 2.0 * request.feature_a + 3.0 * request.feature_b + 1.0 ``` The driver task fans out over the batch inside a task group: ```python @env.task async def predict_batch(requests: list[InferenceRequest]) -> list[float]: captured = [] async with anyio.create_task_group() as tg: # Start each prediction; they run at the same time. for req in requests: captured.append(aioresult.ResultCapture.start_soon(tg, predict_one, req)) # The `async with` block has exited, so every task has completed. return [c.result() for c in captured] ``` What happens here mirrors an `asyncio.gather` fanout, but with structured-concurrency guarantees: 1. **`start_soon` schedules each `predict_one`** into the group. As with `asyncio`, Flyte runs each action in its own container, so the batch executes in true parallel across the cluster โ€” the runtime you use to express concurrency does not change how Flyte distributes the work. 2. **Leaving the `async with` block is the fan-in edge.** The group blocks until all spawned tasks finish, exactly as `await asyncio.gather(...)` would. `predict_batch` cannot return until every prediction is in. 3. **`ResultCapture` collects the return values**, which you read with `.result()` after the group closes. > [!NOTE] > Task groups give you cancellation for free: if any task in the group raises, `anyio` cancels the remaining siblings and propagates the error out of the `async with` block. You get the "cancel the rest on failure" behavior that requires manual `.cancel()` bookkeeping with `asyncio` (see [Abort and cancel actions](abort-tasks.md#canceling-actions-programmatically)). ## When to use anyio Reach for `anyio` when: - You want **structured concurrency** โ€” spawned work is scoped to a block, awaited on exit, and cancelled together on error โ€” rather than manually pairing `asyncio.create_task` handles with `asyncio.gather`. - Your code (or a library you depend on) already uses `anyio` or `trio`, and you want one consistent concurrency model. Stay with `asyncio` when: - You just need to fan out and collect results โ€” `await asyncio.gather(...)` is simpler (see [Fanout](fanout.md)). - You need fine-grained, dependency-driven scheduling where different consumers await different producers (see [Task dependencies and ordering](task-dependencies.md)). Either way, the underlying model is the same: Flyte reads the dependency graph from your `await`s and turns concurrent coroutines into distributed parallel actions. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/task-dependencies === How ordering comes from ordinary Python data flow rather than an explicit DAG. # Task dependencies and ordering Flyte 1 built a workflow's DAG (directed acyclic graph) explicitly: you declared nodes and wired their edges with the `>>` operator or `create_node`. Flyte 2 has no such API. Instead, **the dependency graph is inferred from the data you `await`**. When you await one task's result and pass it into another, Flyte records the edge; tasks that share no data run independently. This page shows how to express the ordering patterns you used to build by hand โ€” sequencing, fan-out, fan-in, and fine-grained dependency-driven scheduling โ€” using ordinary Python `asyncio`. If you are coming from Flyte 1, read **Migration > From Flyte 1 to 2 > Parallelism and fan-out** first for the migration mapping. ## The dependency graph is implicit There is nothing special to learn: a data dependency *is* the edge. ```python import asyncio import flyte env = flyte.TaskEnvironment(name="pipeline") @env.task async def extract() -> str: return "raw" @env.task async def transform(data: str) -> str: return f"transformed({data})" @env.task async def load(data: str) -> str: return f"loaded({data})" @env.task async def main() -> str: raw = await extract() # runs first clean = await transform(raw) # waits for extract โ€” it consumes `raw` return await load(clean) # waits for transform โ€” it consumes `clean` ``` Each `await` means "wait for this to finish before continuing," so a chain of `await`s that pass results downstream runs sequentially โ€” exactly like a linear Flyte 1 workflow. You never declare the edges; passing `raw` into `transform` and `clean` into `load` *is* the DAG. ## Ordering without a data dependency Sometimes you need task `B` to run after task `A` even though `B` does not consume `A`'s output โ€” for example, `A` writes to a store that `B` reads out-of-band, or `A` must finish before you send a notification. Because ordering comes from `await`, you force it simply by awaiting `A` before invoking `B`: CODE0 You do not need a special "run after" construct โ€” a preceding `await` is the ordering primitive. ## Fan-out and fan-in **Fan-out** launches independent tasks concurrently; **fan-in** collects their results into a single downstream task. Use [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) to await several tasks at once โ€” Flyte runs each in its own container in parallel (see [Fanout](fanout.md)): CODE1 The `await asyncio.gather(...)` establishes the fan-in edge: `combine` cannot start until all three upstream tasks have produced their results. ## Dependency-driven scheduling The pattern that most often motivates "replicating DAG behavior" is **fine-grained scheduling**: a diamond or fork where each downstream task should start the moment *its own* upstreams finish, without waiting for unrelated slow tasks. Consider three producers of different durations and four consumers with different dependencies: - `needs_short` depends on `short` only - `needs_medium` depends on `medium` only - `needs_long` depends on `long` only - `needs_all` depends on all three A single `await asyncio.gather(short, medium, long)` before starting any consumer would make every consumer wait for the slowest producer. To let each consumer start as early as possible, start the producers as [`asyncio.create_task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task) handles, then wrap each consumer in a small helper coroutine that awaits only the handles it needs. Launch all the helpers together with `asyncio.gather`: CODE2 `needs_short` starts about a second in, as soon as `short_producer` returns โ€” it does not wait for the 10-second `long_producer`. Awaiting an `asyncio` task handle more than once is safe: the handle caches its result, so `long_task` can feed both `run_needs_long` and `run_needs_all` without re-running the producer. > [!NOTE] > Reach for helper coroutines that each `await` their specific handles, rather than a manual completion loop that inspects [`asyncio.as_completed`](https://docs.python.org/3/library/asyncio-task.html#asyncio.as_completed) and dispatches downstream tasks by hand. Hand-rolled dispatch loops are easy to get wrong โ€” a mis-tracked "has this fired yet?" check can launch the same downstream task twice. Let the dependency edges fall out of `await` instead. ## When to reach for `as_completed` Use [`asyncio.as_completed`](https://docs.python.org/3/library/asyncio-task.html#asyncio.as_completed) when you want to process results **in completion order** โ€” for example, streaming each result into a running reduction as it lands โ€” rather than to encode a fixed dependency graph: CODE3 For a worked streaming/reduce example, see [Fanout](fanout.md) and [Controlling parallel execution](controlling-parallelism.md). ## Summary - Flyte 2 has no explicit DAG-construction API; dependencies come from the data you `await`. - Sequence tasks by awaiting them in order โ€” a preceding `await` orders even tasks that share no data. - Fan out with `asyncio.gather`; fan in by awaiting several results into one downstream task. - For fine-grained scheduling, keep producer handles from `asyncio.create_task` and have each consumer await only the handles it depends on, so it starts as early as possible. - Prefer letting `await` express the graph over hand-rolled completion-tracking loops. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/conditions === Pause a task until an external signal arrives, such as a human approval or a callback. # External conditions An **external condition** is a first-class action that pauses a running task until an external signal arrives: a human approval, a callback from an external service, or a value supplied at runtime. The condition stays observable and governable like any other action, so you don't need polling loops or side processes to wait on something the workflow can't produce itself. Inside a task, `await flyte.new_condition.aio(...)` registers a condition action and returns a handle; `await handle.wait.aio()` blocks the task until the condition is signaled and returns the typed payload. (`new_condition` and `wait` are sync-by-default; in an `async def` task use their `.aio()` form.) ## Supported types A condition declares a `data_type`, which determines what a signal must supply and what `wait()` returns: | `data_type` | `wait()` returns | A signal value of | |---|---|---| | `bool` (default) | `True` / `False` | `true` / `false` | | `int` | Python `int` | an integer literal | | `float` | Python `float` | a decimal literal | | `str` | Python `str` | any string | ## Example: human approval A typed approval gate with a timeout (the most common use case): ```python from datetime import timedelta import flyte env = flyte.TaskEnvironment("approvals") @env.task async def etl_pipeline(): staged = await transform() approval = await flyte.new_condition.aio( "prod_write_approval", prompt="Approve writing staged data to production?", data_type=bool, timeout=timedelta(hours=24), ) if not await approval.wait.aio(): raise RuntimeError("Pipeline rejected by reviewer") await write_to_prod(staged) ``` The task pauses at `await approval.wait.aio()` until someone signals the condition (see **Tasks > Build tasks > External conditions > Signaling a condition**). If the timeout elapses with no signal, `wait()` raises `flyte.errors.ConditionTimedoutError`. ## Example: string input at runtime A condition can collect a typed value (not just a yes/no) and feed it back into the workflow. Here the task waits for a free-form string before continuing: ```python import flyte env = flyte.TaskEnvironment("conditions") @env.task async def deploy_with_reason(): reason = await flyte.new_condition.aio( "deploy_reason", prompt="Enter a deployment reason to continue:", data_type=str, ) note: str = await reason.wait.aio() # `note` now holds the string a human supplied โ€” use it downstream. await record_audit(note) CODE1python flyte.new_condition( name, prompt="Approve?", prompt_type="text", data_type=bool, description="", timeout=None, webhook=None, ) ``` | Parameter | Type | Default | Description | |---|---|---|---| | `name` | `str` | required | Identifier for the condition within the parent action. Signal it with this name (`flyte signal condition `) or look it up with `flyte.remote.Condition.get("", ...)`. | | `prompt` | `str` | `"Approve?"` | Human-readable text shown in the UI signal form. | | `prompt_type` | `"text"` \| `"markdown"` | `"text"` | How the prompt is rendered. | | `data_type` | `type` | `bool` | Payload type: one of `bool`, `int`, `float`, `str`. Determines what `wait()` returns and what a signal must supply. | | `description` | `str` | `""` | Longer explanation rendered alongside the prompt. | | `timeout` | `timedelta` \| `int` \| `float` \| `None` | `None` | Maximum wait. If it elapses with no signal, `wait()` raises `flyte.errors.ConditionTimedoutError`. | The `webhook` parameter takes a `flyte.ConditionWebhook`. In a local run, the SDK POSTs the payload to its URL when the condition is created, with `{callback_uri}` set to a `local://` URI that only the local run can use. Don't rely on it in a remote run: the SDK passes the webhook to the backend, but the backend doesn't currently POST to the URL. ## Signaling a condition A condition is satisfied by delivering exactly one typed signal of its declared `data_type`. ### From the CLI CODE2 The value is coerced to the condition's declared `data_type` (`true`/`false` for `bool`, integer literals for `int`, decimal literals for `float`, any string for `str`). ### From Python (remote) CODE3 `flyte.remote.Condition.listall(run_name=...)` enumerates the conditions on a run. ## Timeout with a fallback CODE4 ## Resources while waiting `wait()` blocks inside the task's own process. The waiting task's pod keeps running for the whole wait and holds the `Resources` its environment requests. The condition itself is stored on the backend as a separate action. Give the task that waits small resources, and account for one running pod per waiting task when many tasks wait at once. ## Errors | Situation | Raised | |---|---| | Timeout elapses before a signal | `flyte.errors.ConditionTimedoutError` | | Creating a condition whose `name` already exists in the action | `flyte.errors.ConditionAlreadyExistsError` | | Condition fails during execution | `flyte.errors.ConditionFailedError` | | Signal value doesn't match `data_type` | `TypeError` (client-side, before any call) | | `wait()` called outside a task context | `RuntimeError` | === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/unit-testing === Test task logic locally, with and without a running backend. Unit testing is essential for ensuring your Flyte tasks work correctly. Flyte 2.0 provides flexible testing approaches that allow you to test both your business logic and Flyte-specific features like type transformations and caching. ## Understanding task invocation When working with functions decorated with `@env.task`, there are two ways to invoke them, each with different behavior: ### Direct function invocation When you call a task directly like a regular Python function: ```python result = my_task(x=10, y=20) ``` **Flyte features are NOT invoked**, including: - Type transformations and serialization - Caching - Data validation This behaves exactly like calling a regular Python function, making it ideal for testing your business logic. ### Using `flyte.run()` When you invoke a task using `flyte.run()`: ```python run = flyte.run(my_task, x=10, y=20) result = run.outputs() ``` **Flyte features ARE invoked**, including: - Type transformations and serialization - Data validation This allows you to test Flyte-specific behavior like serialization and caching. ## Testing business logic For most unit tests, you want to verify your business logic works correctly. Use **direct function invocation** for this: ```python import flyte env = flyte.TaskEnvironment("my_env") @env.task def add(a: int, b: int) -> int: return a + b def test_add(): result = add(a=3, b=5) assert result == 8 ``` ### Testing async tasks Async tasks work the same way with direct invocation: ```python import pytest @env.task async def subtract(a: int, b: int) -> int: return a - b @pytest.mark.asyncio async def test_subtract(): result = await subtract(a=10, b=4) assert result == 6 ``` ### Testing nested tasks When tasks call other tasks, direct invocation continues to work without any Flyte overhead: ```python @env.task def nested(a: int, b: int) -> int: return add(a, b) # Calls the add task directly def test_nested(): result = nested(3, 5) assert result == 8 ``` ## Testing type transformations and serialization When you need to test how Flyte handles data types, serialization, or caching, use `flyte.run()`: ```python @pytest.mark.asyncio async def test_add_with_flyte_run(): run = flyte.run(add, 3, 5) assert run.outputs() == 8 ``` ### Testing nested tasks with serialization You can also test nested task execution with Flyte's full machinery: ```python @pytest.mark.asyncio async def test_nested_with_run(): run = flyte.run(nested, 3, 5) assert run.outputs() == 8 ``` ## Testing traced functions Functions decorated with `@flyte.trace` can be tested similarly to tasks: ```python @flyte.trace async def traced_multiply(a: int, b: int) -> int: return a * b @pytest.mark.asyncio async def test_traced_multiply(): result = await traced_multiply(a=6, b=7) assert result == 42 ``` ## Best practices 1. **Test logic with direct invocation**: For most unit tests, call tasks directly to test your business logic without Flyte overhead. 2. **Test serialization with `flyte.run()`**: Use `flyte.run()` when you need to verify: - Type transformations work correctly - Data serialization/deserialization - Caching behavior 3. **Use standard testing frameworks**: Flyte tasks work with pytest, unittest, and other Python testing frameworks. 4. **Test async tasks properly**: Use `@pytest.mark.asyncio` for async tasks and await their results. 5. **Mock external dependencies**: Use standard Python mocking techniques for external services, databases, etc. ## Quick reference | Test Scenario | Method | Example | |--------------|--------|---------| | Business logic (sync) | Direct call | `result = task(x=10)` | | Business logic (async) | Direct await | `result = await task(x=10)` | | Type transformations | `flyte.run()` | `r = flyte.run(task, x=10)` | | Data serialization | `flyte.run()` | `r = flyte.run(task, x=10)` | | Caching behavior | `flyte.run()` | `r = flyte.run(task, x=10)` | ## Example test suite Here's a complete example showing different testing approaches: ```python import pytest import flyte import flyte.errors env = flyte.TaskEnvironment("test_env") @env.task def add(a: int, b: int) -> int: return a + b @env.task async def subtract(a: int, b: int) -> int: return a - b # Test business logic directly def test_add_logic(): result = add(a=3, b=5) assert result == 8 @pytest.mark.asyncio async def test_subtract_logic(): result = await subtract(a=10, b=4) assert result == 6 # Test with Flyte serialization @pytest.mark.asyncio async def test_add_serialization(): run = flyte.run(add, 3, 5) assert run.outputs() == 8 @pytest.mark.asyncio async def test_subtract_serialization(): run = flyte.run(subtract, a=10, b=4) assert run.outputs() == 6 ``` ## Future improvements The Flyte SDK team is actively working on improvements for advanced unit testing scenarios, particularly around initialization and setup for complex test cases. Additional utilities and patterns may be introduced in future releases to further simplify unit testing. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/higher-order-functions === Pass tasks to other tasks and return them, since tasks are ordinary Python. # Higher-order functions A *higher-order function* is a function that takes other functions as arguments or returns them. Because Flyte 2 tasks execute as native Python and can be **Tasks > Build tasks > Regular async function (not a task)** like any other callable, you can write higher-order functions that operate on **tasks themselves**: reusable orchestration components that wrap a task with retry, fallback, batching, or fault-tolerance logic, without changing the task's business logic. This is possible because Flyte 2 workflows run as ordinary Python: - **Tasks are callables.** You can accept a task as a parameter and `await` it, `.override(...)` its resources, or hand it to `asyncio`. - **Arbitrary nesting.** A task can invoke other tasks at any depth, so an orchestration wrapper can drive a task from inside another task. - **Native control flow.** Loops, conditionals, and `try`/`except` work directly on task results (task outputs are plain Python objects, not promises), so a wrapper can inspect a result or catch an exception and react. > [!NOTE] Higher-order functions are plain functions, not tasks > The wrappers below are **not** decorated with `@env.task`. They are regular `async` Python functions that orchestrate tasks. You call them from inside a driver task (an `@env.task`), which is where the actual task invocations happen. Keep the reusable orchestration logic in a plain function so it can be applied to any task. The patterns on this page are drawn from the runnable [`higher_order_patterns`](https://github.com/flyteorg/flyte-sdk/tree/main/examples/higher_order_patterns) examples in the Flyte SDK repository. ## Fallback runner Run a primary task and, if it fails with a matching exception, automatically fall back to an alternative task. Useful for degrading to a cheaper model, a different region, or a simpler algorithm when the preferred path fails. ```python from typing import Callable, List, Optional, Type, TypeVar R = TypeVar("R") async def run_with_fallback( primary_task: Callable[..., R], fallback_task: Callable[..., R], *args, fallback_exceptions: Optional[List[Type[Exception]]] = None, **kwargs, ) -> R: try: return await primary_task(*args, **kwargs) except Exception as e: # Fall back only on the exceptions we opted into (None means any). should_fallback = fallback_exceptions is None or any( isinstance(e, exc) for exc in fallback_exceptions ) if not should_fallback: raise return await fallback_task(*args, **kwargs) ``` Call it from a driver task, passing the two tasks as arguments: ```python import flyte import flyte.errors env = flyte.TaskEnvironment("fallback") @env.task async def primary(x: int) -> int: # Business logic that may fail, e.g. raise ValueError(...) on bad input. ... @env.task async def backup(x: int) -> int: ... @env.task async def main(x: int) -> int: return await run_with_fallback(primary, backup, x, fallback_exceptions=[flyte.errors.RuntimeUserError]) ``` Note the `fallback_exceptions` list holds `flyte.errors` types, not bare Python exceptions. An exception raised inside a task does not reach the parent as its original Python type: Flyte wraps it as a `flyte.errors` type (a `ValueError` raised in a task surfaces to the caller as a `flyte.errors.RuntimeUserError` whose `code` is `"ValueError"`). So `isinstance`/type-matching in a wrapper must target the `flyte.errors.*` hierarchy; matching on `ValueError` here would never fire and the fallback would never run. See **Tasks > Build tasks > Error handling** for how failures propagate. ## Retry with increasing memory (OOM retrier) Retry a task with progressively larger memory allocations when it hits an out-of-memory error, so you don't have to hard-code a worst-case memory request. The wrapper uses `.override()` to raise the task's `flyte.Resources` on each attempt and catches `flyte.errors.OOMError`. ```python import flyte import flyte.errors async def retry_with_memory( task_fn, *args, initial_memory_mi: int = 250, increment_mi: int = 200, max_memory_mi: int = 4096, cpu: int = 1, **kwargs, ): current = initial_memory_mi while current <= max_memory_mi: try: return await task_fn.override( resources=flyte.Resources(cpu=cpu, memory=f"{current}Mi") )(*args, **kwargs) except flyte.errors.OOMError: if current >= max_memory_mi: break current = min(current + increment_mi, max_memory_mi) raise RuntimeError(f"Task still OOMing at {max_memory_mi}Mi") ``` Because the wrapper only takes the task and its arguments, it works with any task: ```python @env.task async def process(data: list[int]) -> int: # Business logic that may run out of memory on large inputs. return sum(data) @env.task async def main(data: list[int]) -> int: return await retry_with_memory(process, data, initial_memory_mi=500, max_memory_mi=8192) ``` See **Tasks > Build tasks > Error handling** for more on `flyte.errors.OOMError` and resource-based recovery. ## Circuit breaker Run a task over many items in parallel, but stop early ("open the circuit") once failures exceed a threshold, so a systemic problem doesn't burn resources on every remaining item. It launches all invocations with `asyncio.create_task`, processes them as they complete, and cancels the rest when the limit is crossed. ```python import asyncio from typing import Callable, List, Optional, TypeVar T = TypeVar("T") R = TypeVar("R") class CircuitBreakerError(Exception): """Raised when too many failures occur.""" async def circuit_breaker_execute( task_fn: Callable[[T], R], items: List[T], max_failures: int = 3 ) -> List[Optional[R]]: tasks = [asyncio.create_task(task_fn(item)) for item in items] results: List[Optional[R]] = [None] * len(items) failures = 0 pending = set(tasks) while pending: done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) for task in done: idx = tasks.index(task) if task.exception(): failures += 1 if failures > max_failures: for remaining in pending: remaining.cancel() raise CircuitBreakerError( f"{failures} failures exceed limit of {max_failures}" ) else: results[idx] = task.result() return results ``` Failed items come back as `None`; if the failure threshold is crossed, the remaining tasks are cancelled and `CircuitBreakerError` is raised. See **Tasks > Build tasks > Fanout** for the basics of running tasks in parallel and **Tasks > Build tasks > Controlling parallel execution** for bounding concurrency. ## Auto batcher Split a large input into batches, run a map task over each batch in parallel, then combine the results with a reduce step. This bounds how many invocations are in flight at once while still processing everything. ```python import asyncio from typing import Any, Callable, List, TypeVar T = TypeVar("T") R = TypeVar("R") def create_batches(data: List[T], batch_size: int) -> List[List[T]]: return [data[i : i + batch_size] for i in range(0, len(data), batch_size)] async def batch_map_reduce( map_fn: Callable[[T], R], reduce_fn: Callable[[List[R]], Any], data: List[T], batch_size: int = 10, ) -> Any: all_results: List[R] = [] for batch in create_batches(data, batch_size): coros = [asyncio.create_task(map_fn(item)) for item in batch] all_results.extend(await asyncio.gather(*coros)) return reduce_fn(all_results) ``` The map step is a task; the reduce step can be a task or a plain function: ```python @env.task async def square(x: int) -> int: return x * x @env.task async def main(data: list[int]) -> int: return await batch_map_reduce(square, sum, data, batch_size=25) ``` For a first-class parallel-map primitive, see `flyte.map` in **Tasks > Build tasks > Fanout**. ## Composing the patterns Because each wrapper is just a function that takes a task, you can layer them (for example, wrap a task in the OOM retrier and then hand *that* to the fallback runner) to build orchestration behavior out of small, reusable pieces without touching the underlying task code. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-programming/other-features === Advanced patterns that do not fit the other pages in this section. This section covers advanced programming patterns and techniques for working with Flyte tasks. ## Task forwarding When one task calls another task using the normal invocation syntax (e.g., `await inner_task(x)`), Flyte creates a durable action that's recorded in the UI with data passed through the metadata store. However, if you want to execute a task in the same Python VM without this overhead, use the `.forward()` method. **When to use**: You want to avoid durability overhead and execute task logic directly in the current VM. ```python import flyte env = flyte.TaskEnvironment("my-env") @env.task async def inner_task(x: int) -> int: return x + 1 @env.task async def outer_task(x: int) -> int: # Executes in same VM, no durable action created v = await inner_task.forward(x=10) # Creates a durable action, recorded in UI return await inner_task(v) ``` The `.forward()` method works with both sync and async tasks: ```python @env.task def sync_inner_task(x: int) -> int: return x + 1 @env.task def sync_outer_task(x: int) -> int: # Direct execution, no remote call v = sync_inner_task.forward(x=10) return sync_inner_task(v) ``` ## Passing tasks and functions as arguments You can pass both Flyte tasks and regular Python functions as arguments to other tasks. Flyte handles this through pickling, so the code appears as pickled data in the UI. ```python import typing import flyte env = flyte.TaskEnvironment("udfs") @env.task async def add_one_udf(x: int) -> int: return x + 1 # Regular async function (not a task) async def fn_add_two_udf(x: int) -> int: return x + 2 @env.task async def run_udf(x: int, udf: typing.Callable[[int], typing.Awaitable[int]]) -> int: return await udf(x) @env.task async def main() -> list[int]: # Pass a Flyte task as an argument result_one = await run_udf(5, add_one_udf) # Pass a regular function as an argument result_two = await run_udf(5, fn_add_two_udf) return [result_one, result_two] ``` **Note**: Both tasks and regular functions are serialized via pickling when passed as arguments. ## Custom action names By default, actions in the UI use the task's function name. You can provide custom, user-friendly names using the `short_name` parameter. ### Set at task definition ```python import flyte env = flyte.TaskEnvironment("friendly_names") @env.task(short_name="my_task") async def some_task() -> str: return "Hello, Flyte!" ``` ### Override at call time ```python @env.task(short_name="entrypoint") async def main() -> str: # Uses the default short_name "my_task" s = await some_task() # Overrides to use "my_name" for this specific action return s + await some_task.override(short_name="my_name")() ``` This is useful when the same task is called multiple times with different contexts, making the UI more readable. ## Invoking async functions from sync tasks When migrating from Flyte 1.x to 2.0, you may have legacy sync code that needs to call async functions. Use `nest_asyncio.apply()` to enable `asyncio.run()` within sync tasks. ```python import asyncio import nest_asyncio import flyte env = flyte.TaskEnvironment( "async_in_sync", image=flyte.Image.from_debian_base().with_pip_packages("nest_asyncio"), ) # Apply at module level nest_asyncio.apply() async def async_function() -> str: await asyncio.sleep(1) return "done" @env.task def sync_task() -> str: # Now you can use asyncio.run() in a sync task return asyncio.run(async_function()) ``` **Important**: - Call `nest_asyncio.apply()` at the module level before defining tasks - Add `nest_asyncio` to your image dependencies - This is particularly useful during migration when you have mixed sync/async code ## Async and sync task interoperability When migrating from older sync-based code to async tasks, or when working with mixed codebases, you need to call sync tasks from async parent tasks. Flyte provides the `.aio` method on every task (even sync ones) to enable this. ### Calling sync tasks from async tasks Every sync task automatically has an `.aio` property that returns an async-compatible version: ```python import flyte env = flyte.TaskEnvironment("mixed-tasks") @env.task def sync_task(x: int) -> str: """Legacy sync task""" return f"Processed {x}" @env.task async def async_task(x: int) -> str: """New async task that calls legacy sync task""" # Use .aio to call sync task from async context result = await sync_task.aio(x) return result ``` ### Using with `flyte.map.aio()` When you need to call sync tasks in parallel from an async context, use `flyte.map.aio()`: ```python from typing import List import flyte env = flyte.TaskEnvironment("map-example") @env.task def sync_process(x: int) -> str: """Synchronous processing task""" return f"Task {x}" @env.task async def async_main(n: int) -> List[str]: """Async task that maps over sync task""" results = [] # Map over sync task from async context async for result in flyte.map.aio(sync_process, range(n)): if isinstance(result, Exception): raise result results.append(result) return results ``` **Why this matters**: This pattern is powerful when migrating from Flyte 1.x or integrating legacy sync tasks with new async code. You don't need to rewrite all sync tasks at once; they can be called from async contexts. ## Using AnyIO in async tasks Flyte async tasks support `anyio` for structured concurrency as an alternative to `asyncio.gather()`. ```python import anyio import aioresult import flyte env = flyte.TaskEnvironment( "anyio_example", image=flyte.Image.from_debian_base().with_pip_packages("anyio", "aioresult"), ) @env.task async def process_item(x: int) -> int: return x * 2 @env.task async def batch_process(items: list[int]) -> list[int]: captured_results = [] async with anyio.create_task_group() as tg: # Start multiple tasks concurrently for item in items: captured_results.append( aioresult.ResultCapture.start_soon(tg, process_item, item) ) # Extract results return [r.result() for r in captured_results] ``` **Note**: You can use anyio's task groups, timeouts, and other structured concurrency primitives within Flyte async tasks. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment === Use `flyte run` for iteration or `flyte deploy` to register a stable task version. # Run and deploy tasks You have seen how to configure and build the tasks that compose your project. Now you need to decide how to execute them on your Flyte backend. Flyte offers two distinct approaches for getting your tasks onto the backend: **Use `flyte run` when you're iterating and experimenting:** - Quickly test changes during development - Try different parameters or code modifications - Debug issues without creating permanent artifacts - Prototype new ideas rapidly **Use `flyte deploy` when your project is ready to be formalized:** - Freeze a stable version of your tasks for repeated use - Share tasks with team members or across environments - Move from experimentation to a more structured workflow - Create a permanent reference point (not necessarily production-ready) This section explains both approaches and when to use each one. ## Ephemeral deployment and immediate execution The `flyte run` CLI command and the `flyte.run()` SDK function are used to **ephemerally deploy** and **immediately execute** a task on the backend in a single step. The task can be re-run and its execution and outputs can be observed in the **Runs list** UI, but it is not permanently added to the **Tasks list** on the backend. Let's say you have the following file called `greeting.py`: ```python # greeting.py import flyte env = flyte.TaskEnvironment(name="greeting_env") @env.task async def greet(message: str) -> str: return f"{message}!" ``` ### Programmatic You can run the task programmatically using the `flyte.run()` function: ```python # greeting.py import flyte env = flyte.TaskEnvironment(name="greeting_env") @env.task async def greet(message: str) -> str: return f"{message}!" if __name__ == "__main__": flyte.init_from_config() result = flyte.run(greet, message="Good morning!") print(f"Result: {result}") ``` Here we add a `__main__` block to the `greeting.py` file that initializes the Flyte SDK from the configuration file and then calls `flyte.run()` with the `greet` task and its argument. Now you can run the `greet` task on the backend just by executing the `greeting.py` file locally as a script: ```bash python greeting.py ``` ### CLI The general form of the command for running a task from a local file is: ```bash flyte run ``` So, to run the `greet` task defined in the `greeting.py` file, you would run: ```bash flyte run greeting.py greet --message "Good morning!" ``` This command: 1. **Temporarily deploys** the task environment named `greeting_env` (held by the variable `env`) that contains the `greet` task. 2. **Executes** the `greet` function with argument `message` set to `"Good morning!"`. Note that `message` is the actual parameter name defined in the function signature. 3. **Returns** the execution results and displays them in the terminal. For how to pass inputs of other types (datetimes, durations, enums, files, dataclasses, and more) on the command line, see **Tasks > Run and deploy tasks > Run command options > Task argument passing > Passing inputs by type**. For more details on how `flyte run` and `flyte.run()` work under the hood, see **Tasks > Run and deploy tasks > How task run works**. ## Persistent deployment The `flyte deploy` CLI command and the `flyte.deploy()` SDK function are used to **persistently deploy** a task environment (and all its contained tasks) to the backend. The tasks within the deployed environment will appear in the **Tasks list** UI on the backend and can then be executed multiple times without needing to redeploy them. ### Programmatic You can deploy programmatically using the `flyte.deploy()` function: ```python # greeting.py import flyte env = flyte.TaskEnvironment(name="greeting_env") @env.task async def greet(message: str) -> str: return f"{message}!" if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(env) print(deployments[0].summary_repr()) ``` Now you can deploy the `greeting_env` task environment (and therefore the `greet()` task) just by executing the `greeting.py` file locally as a script. ```bash python greeting.py ``` ### CLI The general form of the command for deploying a task environment from a local file is: ```bash flyte deploy ``` So, using the same `greeting.py` file as before, you can deploy the `greeting_env` task environment like this: ```bash flyte deploy greeting.py env ``` This command deploys the task environment *assigned to the variable `env`* in the `greeting.py` file, which is the `TaskEnvironment` named `greeting_env`. Notice that you must specify the *variable* to which the `TaskEnvironment` is assigned (`env` in this case), not the name of the environment itself (`greeting_env`). Deploying a task environment deploys all tasks defined within it. Here, that means all functions decorated with `@env.task`. In this case there is just one: `greet()`. For more details on how `flyte deploy` and `flyte.deploy()` work under the hood, see **Tasks > Run and deploy tasks > How task deployment works**. ## Running already deployed tasks If you have already deployed your task environment, you can run its tasks without redeploying by using the `flyte run` CLI command or the `flyte.run()` SDK function in a slightly different way. Alternatively, you can always initiate execution of a deployed task from the UI. ### Programmatic You can run already-deployed tasks programmatically using the `flyte.run()` function. For example, to run the previously deployed `greet` task from the `greeting_env` environment: ```python # greeting.py import flyte env = flyte.TaskEnvironment(name="greeting_env") @env.task async def greet(message: str) -> str: return f"{message}!" if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env) task = flyte.remote.Task.get("greeting_env.greet", auto_version="latest") result = flyte.run(task, message="Good morning!") print(f"Result: {result}") ``` When you execute this script locally, it will: - Deploy the `greeting_env` task environment as before. - Retrieve the already-deployed `greet` task using `flyte.remote.Task.get()`, specifying its full task reference as a string: `"greeting_env.greet"`. - Call `flyte.run()` with the retrieved task and its argument. For more details on how running already-deployed tasks works, see **Tasks > Run and deploy tasks > How task run works > Running deployed tasks**. ### CLI To run a permanently deployed task using the `flyte run` CLI command, use the special `deployed-task` keyword followed by the task reference in the format `{environment_name}.{task_name}`. For example, to run the previously deployed `greet` task from the `greeting_env` environment: ```bash flyte run deployed-task greeting_env.greet --message "World" ``` Notice that now that the task environment is deployed, you use its name (`greeting_env`), not by the variable name to which it was assigned in source code (`env`). The task environment name plus the task name (`greet`) are combined with a dot (`.`) to form the full task reference: `greeting_env.greet`. The special `deployed-task` keyword tells the CLI that you are referring to a task that has already been deployed. In effect, it replaces the file path argument used for ephemeral runs. When executed, this command will run the already-deployed `greet` task with argument `message` set to `"World"`. You will see the result printed in the terminal. You can also, of course, observe the execution in the **Runs list** UI. To execute a deployed task in a different project or domain than your configured defaults, use `--run-project` and `--run-domain`: ```bash flyte run --run-project prod-project --run-domain production deployed-task greeting_env.greet --message "World" ``` For all `flyte run` options, see **Tasks > Run and deploy tasks > Run command options**. ## Configuring runs with `flyte.with_runcontext()` Both `flyte run` and `flyte.run()` accept a range of invocation-time parameters that control where the run executes, where outputs are stored, caching behavior, and more. Programmatically, these are set with `flyte.with_runcontext()` before calling `.run()`. Inside a running task, `flyte.ctx()` provides read access to the same context. For the full parameter reference, see **Tasks > Run and deploy tasks > Run context**. {{< subpage-cards >}} ## Subpages - **Tasks > Run and deploy tasks > How task run works** - The three ways flyte run launches a task, and when each applies. - **Tasks > Run and deploy tasks > Interact with runs and actions** - Inspect, wait on, and act against a run and the actions inside it. - **Tasks > Run and deploy tasks > View logs** - Read the logs an action emitted, live or after the fact. - **Tasks > Run and deploy tasks > Work with local data** - Pass local files, directories, and DataFrames into a remote run. - **Tasks > Run and deploy tasks > Run command options** - Every option flyte run accepts, and what each overrides. - **Tasks > Run and deploy tasks > Build a custom CLI** - Build your own command-line front end when the generated flyte run options are not enough. - **Tasks > Run and deploy tasks > How task deployment works** - What flyte deploy and flyte.deploy do under the hood. - **Tasks > Run and deploy tasks > Deploy command options** - Every option flyte deploy accepts, and what each overrides. - **Tasks > Run and deploy tasks > Code packaging for on-cluster execution** - The two ways to get your code into the execution environment. - **Tasks > Run and deploy tasks > Running tasks via webhooks** - Launch deployed tasks over HTTP from an app acting as a webhook. - **Tasks > Run and deploy tasks > Deployment patterns** - Deployment shapes for different project structures and dependency setups. - **Tasks > Run and deploy tasks > Run context** - Set where a run executes, where its outputs go, and how caching behaves. - **Tasks > Run and deploy tasks > Entrypoint tasks** - Mark the tasks meant to be launched directly, so the task list stays readable as a project grows. - **Tasks > Run and deploy tasks > Run a Python script** - Run an arbitrary .py file remotely without wrapping it in a task. - **Tasks > Run and deploy tasks > Run with notifications** - Fire a notification when a run reaches a terminal state. - **Tasks > Run and deploy tasks > Send notifications from your code** - Post a message when a run succeeds or fails, from the run's own driver task, with the destination read from a secret at runtime. - **Tasks > Run and deploy tasks > Rerun a run** - Launch a fresh run from a previous one's recorded task, code, inputs, and configuration. - **Tasks > Run and deploy tasks > Recover a failed run** - Relaunch a failed run so it reuses the actions that already succeeded. - **Tasks > Run and deploy tasks > Fork a run** - Replay a prior run with your current code and inputs, reusing what still holds. - **Tasks > Run and deploy tasks > Debug a run** - Drop into a live session on a running action to inspect its environment, filesystem, and code. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/how-task-run-works === The three ways flyte run launches a task, and when each applies. # How task run works The `flyte run` command and `flyte.run()` SDK function support three ways to launch a task: 1. **Ephemeral deployment + run**: Automatically prepare task environments ephemerally and execute tasks (development shortcut) 2. **Run deployed task**: Execute permanently deployed tasks without redeployment 3. **Local execution**: Run tasks on your local machine for development and testing Additionally, you can run deployed tasks through the Flyte/Union UI for interactive execution and monitoring. This page is about *how* a run is launched. Whether it runs locally in-process or remotely, on a devbox or a deployed cluster, is covered in [Run modes](../../get-started/run-modes/_index). ## Ephemeral deployment + run: The development shortcut The most common development pattern combines ephemeral task preparation and execution in a single command, automatically handling the temporary deployment process when needed. ### Programmatic ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task async def my_task(name: str) -> str: return f"Hello, {name}!" if __name__ == "__main__": flyte.init_from_config() # Deploy and run in one step result = flyte.run(my_task, name="World") print(f"Result: {result}") print(f"Execution URL: {result.url}") ``` ### CLI ```bash flyte run my_example.py my_task --name "World" ``` With explicit project and domain: ```bash flyte run --project my-project --domain development my_example.py my_task --name "World" ``` Bundling every file in the working directory, not only the imported modules: ```bash flyte run --copy-style all my_example.py my_task --name "World" ``` **How it works:** 1. **Environment discovery**: Flyte loads the specified Python file and identifies task environments 2. **Ephemeral preparation**: Temporarily prepares the task environment for execution (similar to deployment but not persistent) 3. **Task execution**: Immediately runs the specified task with provided arguments in the ephemeral environment 4. **Result return**: Returns execution results and monitoring URL 5. **Cleanup**: The ephemeral environment is not stored permanently in the backend **Benefits of ephemeral deployment + run:** - **Development efficiency**: No separate permanent deployment step required - **Always current**: Uses your latest code changes without polluting the backend - **Clean development**: Ephemeral environments don't clutter your task registry - **Integrated workflow**: Single command for complete development cycle ## Running deployed tasks For production workflows or when you want to use stable deployed versions, you can run tasks that have been **permanently deployed** with `flyte deploy` without triggering any deployment process. ### Programmatic ```python import flyte flyte.init_from_config() # Method 1: Using remote task reference deployed_task = flyte.remote.Task.get("my_env.my_task", version="v1.0.0") result = flyte.run(deployed_task, name="World") # Method 2: Get latest version deployed_task = flyte.remote.Task.get("my_env.my_task", auto_version="latest") result = flyte.run(deployed_task, name="World") ``` ### CLI ```bash flyte run deployed-task my_env.my_task --name "World" ``` With a specific project and domain: ```bash flyte run --project prod --domain production deployed-task my_env.my_task --batch_size 1000 ``` **Task reference format:** `{environment_name}.{task_name}` - `environment_name`: The `name` property of your `TaskEnvironment` - `task_name`: The function name of your task >[!NOTE] > When you deploy a task environment with `flyte deploy`, you specify the `TaskEnvironment` by the variable to which it is assigned. > Once deployed, you refer to it by its `name` property. **Benefits of running deployed tasks:** - **Performance**: No deployment overhead, faster execution startup - **Stability**: Uses tested, stable versions of your code - **Production safety**: Isolated from local development changes - **Version control**: Explicit control over which code version runs ## Local execution For development, debugging, and testing, you can run tasks in-process on your local machine. By default, no backend is involved. ### Programmatic ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task async def my_task(name: str) -> str: return f"Hello, {name}!" # Method 1: No client configured (defaults to local) result = flyte.run(my_task, name="World") # Method 2: Explicit local mode flyte.init_from_config() # Client configured result = flyte.with_runcontext(mode="local").run(my_task, name="World") ``` ### CLI ```bash flyte run --local my_example.py my_task --name "World" ``` With development data: ```bash flyte run --local data_pipeline.py process_data --input_path "/local/data" --debug ``` **Benefits of local execution:** - **Rapid development**: Instant feedback without network latency - **Debugging**: Full access to local debugging tools - **Offline development**: Works without backend connectivity - **Resource efficiency**: Uses local compute resources ### Tracking a local run A local run can report its progress to Union.ai, so you can follow it in the console under **Tracked Runs** while it still executes on your machine. From the CLI, use `flyte run --tracked`. From Python, pass `tracked=True` to `flyte.with_runcontext()`: ```python flyte.init_from_config() # needs an endpoint, project and domain run = flyte.with_runcontext(mode="local", tracked=True).run(my_task, name="World") ``` Tracking is local-only: `tracked=True` with `mode="remote"` raises a `ValueError`. If no client is initialized, the run goes ahead locally without reporting and logs a warning. To track every local run, pass `local_tracked=True` to `flyte.init()` or set `local.tracked: true` in your config file. For strict reporting, run naming rules and what is reported, see **Tasks > Run and deploy tasks > Run command options > `--tracked`, `--tracked-strict`**. ## Running tasks through the Union UI If you are running your Flyte code on a Union backend, the UI provides an interactive way to run deployed tasks with form-based input and real-time monitoring. ### Accessing task execution in the Union UI 1. **Navigate to tasks**: Go to your project โ†’ domain โ†’ Tasks section 2. **Select task**: Choose the task environment and specific task 3. **Launch execution**: Click "Launch" to open the execution form 4. **Provide inputs**: Fill in task parameters through the web interface 5. **Monitor progress**: Watch real-time execution progress and logs **UI execution benefits:** - **User-friendly**: No command-line expertise required - **Visual monitoring**: Real-time progress visualization - **Input validation**: Built-in parameter validation and type checking - **Execution history**: Easy access to previous runs and results - **Sharing**: Shareable execution URLs for collaboration Here is a short video demonstrating task execution through the Union UI: ๐Ÿ“บ [Watch on YouTube](https://www.youtube.com/watch?v=id="8jbau9yGoDg) ## Execution flow and architecture ### Fast registration architecture Flyte v2 uses "fast registration" to enable rapid development cycles: #### How it works 1. **Container images** contain the runtime environment and dependencies 2. **Code bundles** contain your Python source code (stored separately) 3. **At runtime**: Code bundles are downloaded and injected into running containers #### Benefits - **Rapid iteration**: Update code without rebuilding images - **Resource efficiency**: Share images across multiple deployments - **Version flexibility**: Run different code versions with same base image - **Caching optimization**: Separate caching for images vs. code #### When code gets injected At task execution time, the fast registration process follows these steps: 1. **Container starts** with the base image containing runtime environment and dependencies 2. **Code bundle download**: The Flyte agent downloads your Python code bundle from storage 3. **Code extraction**: The code bundle is extracted and mounted into the running container 4. **Task execution**: Your task function executes with the injected code ### Ephemeral preparation logic When using ephemeral deploy + run mode, Flyte determines whether temporary preparation is needed: ```mermaid graph TD A[flyte run command] --> B{Need preparation?} B -->|Yes| C[Ephemeral preparation] B -->|No| D[Use cached preparation] C --> E[Execute task] D --> E E --> F[Cleanup ephemeral environment] ``` ### Launch methods compared | Launch method | Deployment | Performance | Use Case | Code Version | |------|------------|-------------|-----------|--------------| | Ephemeral Deploy + Run | Ephemeral (temporary) | Medium | Development, testing | Latest local | | Run Deployed | None (uses permanent deployment) | Fast | Production, stable runs | Deployed version | | Local | None | Variable | Development, debugging | Local | | UI | None | Fast | Interactive, collaboration | Deployed version | A **Tasks > Run and deploy tasks > How task run works > Tracking a local run** local run has the same profile as **Local**. It also appears in the console under **Tracked Runs**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/interacting-with-runs === Inspect, wait on, and act against a run and the actions inside it. # Interact with runs and actions When a task is launched, the resulting execution is called a **run**. Because tasks typically call other tasks, a run will almost always involve multiple sub-task executions. Each such execution is called an **action**. Through the Flyte SDK and CLI, you can interact with the run and its actions to monitor progress, retrieve results, and access data. This section explains how to work with runs and actions programmatically and through the CLI. ## Understanding runs and actions Runs are not declared explicitly in the code of the entry point task. Instead, they are simply a result of the task being invoked in a specific way: * User with `flyte run` * User via the UI * Other code calling `flyte.run()` * [Trigger](../../triggers/_index) When a task is invoked in one of these ways, it creates a run to represent the execution of that task and all its nested tasks, considered together. Each task execution within that run is represented by an **action**. The entry point task execution is represented by the main action (usually called `a0`), and then every nested call of one task from another creates an additional action. ```mermaid graph TD A[Run] --> B[Action a0 - Main task] B --> C[Action a1 - Nested task] B --> D[Action a2 - Nested task] D --> E[Action a3 - Deeply nested task] ``` Because what constitutes a run depends only on how a task is invoked, the same task can execute as a deeply nested action in one run and the main action in another run. Unlike Flyte 1, there is no explicit `@workflow` construct in Flyte 2; instead, "workflows" are defined implicitly by the structure of task composition and the entry point chosen at runtime. > [!NOTE] > Despite there being no explicit `@workflow` decorator, you'll often see the assemblage of tasks referred to as a "workflow" in documentation and discussions. The top-most task in a run is sometimes referred to as the "parent", "driver", or "entry point" task of the "workflow". > In these docs we will sometime use "workflow" informally to refer to the collection of tasks (considered statically) involved in a run. ### Key concepts - **Attempts**: Each action can have multiple attempts due to retries. Retries occur for two reasons: - User-configured retries for handling transient failures - Automatic system retries for infrastructure issues - **Phases**: Both runs and actions progress through phases (e.g., QUEUED, RUNNING, SUCCEEDED, FAILED) until reaching a terminal state - **Durability**: Flyte is a durable execution engine, so every input, output, failure, and attempt is recorded for each action. All data is persisted, allowing you to retrieve information about runs and actions even after completion ## Working with runs Runs are created when you execute tasks using `flyte run` or `flyte.run()`. For details on running tasks, see **Tasks > Run and deploy tasks > How task run works**. To learn about running previously deployed remote tasks, see **Tasks > Build tasks > Remote tasks**. ### Retrieving a run ### Programmatic Use `flyte.remote.Run.get()` to retrieve information about a run: ```python import flyte flyte.init_from_config() # Get a run by name run = flyte.remote.Run.get("my_run_name") # Access basic information print(run.url) # UI URL for the run print(run.action.phase) # Phase of the main action ``` ### CLI Get a specific run: ```bash flyte get run my_run_name ``` List all runs: ```bash flyte get run ``` Use `--project` and `--domain` to scope results to a specific **Get started > Core concepts > Projects and domains**. For all available options, see the **Flyte CLI > flyte get run**. ### Filtering runs by label If runs were launched with **Tasks > Run and deploy tasks > Run context > Configuring a run with `flyte.with_runcontext()` > Identity and resources** โ€” arbitrary `key=value` metadata attached at launch โ€” you can filter the run list by those labels. Multiple label filters combine with **AND** semantics: a run must match every label you specify to be returned. ### CLI Filter by one or more `key=value` labels: ```bash flyte get run --with-label team=ml --with-label env=prod ``` Filter by the presence of a label key, regardless of its value: ```bash flyte get run --with-label-key team ``` ### Programmatic `flyte.remote.Run.listall()` accepts the same filters and returns an iterator of runs: ```python import flyte flyte.init_from_config() # Runs that carry BOTH labels (AND semantics) for run in flyte.remote.Run.listall(with_labels={"team": "ml", "env": "prod"}): print(run.name) # Runs that have the "team" label key set to any value for run in flyte.remote.Run.listall(with_label_keys=["team"]): print(run.name) ``` In async code, use `flyte.remote.Run.listall.aio(...)` with `async for` instead. ### UI In the run list, each run shows its labels as chips in the **Labels** column. Click a label chip to filter the list down to the runs that share that label. To attach labels to a run when you launch it, see **Tasks > Run and deploy tasks > Run context > Configuring a run with `flyte.with_runcontext()` > Identity and resources**. ### Watching run progress Monitor a run as it progresses through phases: ```python # Wait for run to complete run = flyte.run(my_task, input_data="test") run.wait() # Blocks until terminal state # Check if done if run.action.done(): print("Run completed!") ``` ### Getting detailed run information Use `flyte.remote.RunDetails` for comprehensive information including nested actions and metadata: ```python run_details = flyte.remote.RunDetails.get(name="my_run_name") # Access detailed information print(run_details.pb2) # Full protobuf representation ``` ## Working with actions Actions represent individual task executions within a run. Each action has a unique identifier within its parent run. ### Retrieving an action ### Programmatic ```python # Get a specific action by run name and action name action = flyte.remote.Action.get( run_name="my_run_name", name="a0" # Main action ) # Access action information print(action.phase) # Current phase print(action.task_name) # Task being executed print(action.start_time) # Execution start time ``` ### CLI Get a specific action: ```bash flyte get action my_run_name a0 ``` List all actions for a run: ```bash flyte get action my_run_name ``` For all available options, see the **Flyte CLI > flyte get > flyte get action**. ### Nested actions Deeply nested actions are uniquely identified by their path under the run: ```python # Get a nested action nested_action = flyte.remote.Action.get( run_name="my_run_name", name="a1" # Nested action identifier ) ``` ### Getting detailed action information Use `flyte.remote.ActionDetails` for comprehensive action information: ```python action_details = flyte.remote.ActionDetails.get( run_name="my_run_name", name="a0" ) # Access detailed information print(action_details.pb2) # Full protobuf representation ``` ## Accessing logs Each action captures the logs emitted by its task, per attempt. Stream them from the CLI with `flyte get logs`, or view them on the action in the console. For details and all available options, see **Tasks > Run and deploy tasks > View logs**. ```bash # Logs for the run's main action flyte get logs my_run_name # Logs for a specific action flyte get logs my_run_name a1 ``` ## Retrieving inputs and outputs ### Programmatic Both `Run` and `Action` objects provide methods to retrieve inputs and outputs: ```python run = flyte.remote.Run.get("my_run_name") # Get inputs - returns ActionInputs (dict-like) inputs = run.inputs() print(inputs) # {"param_name": value, ...} # Get outputs - returns tuple outputs = run.outputs() print(outputs) # (result1, result2, ...) # Single output single_output = outputs[0] # No outputs are represented as (None,) ``` **Important notes:** - **Inputs**: Returned as `flyte.remote.ActionInputs`, a dictionary with parameter names as keys and values as the actual data passed in - **Outputs**: Always returned as `flyte.remote.ActionOutputs` tuple, even for single outputs or no outputs - **No outputs**: Represented as `(None,)` - **Availability**: Outputs are only available if the action completed successfully - **Type safety**: Flyte's rich type system converts data to an intermediate representation, allowing retrieval even without the original dependencies installed ### CLI Get inputs and outputs for a run: ```bash flyte get io my_run_name ``` Get inputs and outputs for a specific action: ```bash flyte get io my_run_name a1 ``` For all available options, see the **Flyte CLI > flyte get io**. ### Handling failures To raise a finished run's failure as a typed exception, wait on the run and call `flyte.remote.Run.raise_for_status()`. It raises the same exception a parent task gets when a sub-action fails. Requires `flyte` 2.10.3 or later. For details, see **Tasks > Build tasks > Error handling > Handling the failure of a run you launched**. If an action fails, outputs are not available, but you can retrieve error information: ```python action = flyte.remote.Action.get(run_name="my_run_name", name="a0") if action.phase == flyte.models.ActionPhase.FAILED: # Outputs will raise an error try: outputs = action.outputs() except RuntimeError as e: print("Action failed, outputs not available") # Get error details instead action_details = flyte.remote.ActionDetails.get( run_name="my_run_name", name="a0" ) print(action_details.pb2.error_info) ``` ## Understanding data storage Flyte handles different types of data differently, as explained in **Scale your runs > Data flow**: - **Parameterized data** (primitives, small objects): Returned directly in inputs/outputs - **Large data** (files, directories, DataFrames, models): Stored in cloud storage (S3, GCS, Azure Blob Storage) When you retrieve outputs containing large data, Flyte returns references rather than the actual data. To access the actual raw data, you need proper cloud storage permissions and configuration. ## Accessing large data from cloud storage To download and work with files, directories, and DataFrames stored in cloud object storage, you must configure storage access with appropriate credentials. ### S3 storage access To access data stored in Amazon S3: **1. Set environment variables:** ```bash export FLYTE_AWS_ACCESS_KEY_ID="your-access-key-id" export FLYTE_AWS_SECRET_ACCESS_KEY="your-secret-access-key" ``` These are standard AWS credential environment variables that Flyte recognizes. They are your IAM user's access keys. If you don't already have them, follow the AWS guide on [managing access keys for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) to create them. **2. Initialize Flyte with S3 storage configuration:** ```python import flyte import flyte.storage # Auto-configure from environment variables flyte.init_from_config( storage=flyte.storage.S3.auto(region="us-east-2") ) # Or provide credentials explicitly flyte.init_from_config( storage=flyte.storage.S3( access_key_id="your-access-key-id", secret_access_key="your-secret-access-key", region="us-east-2" ) ) ``` **3. Access data from outputs:** ```python run = flyte.remote.Run.get("my_run_name") outputs = run.outputs() # Outputs containing files, dataframes, etc. can now be downloaded dataframe = outputs[0] df = await dataframe.open(pd.DataFrame).all() ``` ### GCS storage access To access data stored in Google Cloud Storage: **1. Set environment variables:** ```bash export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json" ``` This is the standard Google Cloud authentication method using service account credentials. **2. Initialize Flyte with GCS storage configuration:** ```python import flyte import flyte.storage # Auto-configure from environment flyte.init_from_config( storage=flyte.storage.GCS.auto() ) # Or configure explicitly flyte.init_from_config( storage=flyte.storage.GCS() ) ``` **3. Access data from outputs:** ```python run = flyte.remote.Run.get("my_run_name") outputs = run.outputs() # Download data as needed file_output = outputs[0] # Work with file output ``` ### Azure Blob Storage access To access data stored in Azure Blob Storage (ABFS): **1. Set environment variables:** For storage account key authentication: ```bash export AZURE_STORAGE_ACCOUNT_NAME="your-storage-account" export AZURE_STORAGE_ACCOUNT_KEY="your-account-key" ``` For service principal authentication: ```bash export AZURE_TENANT_ID="your-tenant-id" export AZURE_CLIENT_ID="your-client-id" export AZURE_CLIENT_SECRET="your-client-secret" export AZURE_STORAGE_ACCOUNT_NAME="your-storage-account" ``` `flyte.storage.ABFS.auto()` also reads Flyte-prefixed versions of these variables: `FLYTE_AZURE_STORAGE_ACCOUNT_NAME`, `FLYTE_AZURE_STORAGE_ACCOUNT_KEY`, `FLYTE_AZURE_TENANT_ID`, `FLYTE_AZURE_CLIENT_ID`, and `FLYTE_AZURE_CLIENT_SECRET`. If any of them is set, it reads only the prefixed names and ignores the generic `AZURE_*` ones. Use the prefixed names when the generic names are already set for other Azure tools, such as adlfs, deltalake, or the Azure SDKs, and point to a different storage account. Requires `flyte` 2.12.3 or later. **2. Initialize Flyte with Azure storage configuration:** ```python import flyte import flyte.storage # Auto-configure from environment variables flyte.init_from_config( storage=flyte.storage.ABFS.auto() ) # Or provide credentials explicitly flyte.init_from_config( storage=flyte.storage.ABFS( account_name="your-storage-account", account_key="your-account-key" ) ) # Or use service principal flyte.init_from_config( storage=flyte.storage.ABFS( account_name="your-storage-account", tenant_id="your-tenant-id", client_id="your-client-id", client_secret="your-client-secret" ) ) ``` **3. Access data from outputs:** ```python run = flyte.remote.Run.get("my_run_name") outputs = run.outputs() # Download data as needed directory_output = outputs[0] # Work with directory output ``` ## Complete example Here's a complete example showing how to launch a run and interact with it: ```python import flyte import flyte.storage # Initialize with storage access flyte.init_from_config( storage=flyte.storage.S3.auto(region="us-east-2") ) # Define and run a task env = flyte.TaskEnvironment(name="data_processing") @env.task async def process_data(input_value: str) -> str: return f"Processed: {input_value}" # Launch the run run = flyte.run(process_data, input_value="test_data") # Monitor progress print(f"Run URL: {run.url}") run.wait() # Check status if run.action.done(): print(f"Run completed with phase: {run.action.phase}") # Get inputs and outputs inputs = run.inputs() print(f"Inputs: {inputs}") outputs = run.outputs() print(f"Outputs: {outputs}") # Access the result result = outputs[0] print(f"Result: {result}") ``` ## API reference ### Key classes - `flyte.remote.Run` - Represents a run with basic information - `flyte.remote.RunDetails` - Detailed run information including all actions - `flyte.remote.Action` - Represents an action with basic information - `flyte.remote.ActionDetails` - Detailed action information including error details - `flyte.remote.ActionInputs` - Dictionary-like object containing action inputs - `flyte.remote.ActionOutputs` - Tuple containing action outputs ### CLI commands For complete CLI documentation and all available options, see the **Flyte CLI**: - **Flyte CLI > flyte get run** - Get run information - **Flyte CLI > flyte get > flyte get action** - Get action information - **Flyte CLI > flyte get io** - Get inputs and outputs - **Flyte CLI > flyte get logs** - Get action logs ### Storage configuration - `flyte.storage.S3` - Amazon S3 configuration - `flyte.storage.GCS` - Google Cloud Storage configuration - `flyte.storage.ABFS` - Azure Blob Storage configuration For more details on data flow and storage, see **Scale your runs > Data flow**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/view-logs === Read the logs an action emitted, live or after the fact. # View logs Every action in a run captures the logs its task emits while executing. Because Flyte is a durable execution engine, these logs are persisted per action and per attempt, so you can retrieve them while a run is in progress or after it has reached a terminal state. There are two ways to view logs: - **The CLI**: stream logs for a run or a specific action with `flyte get logs`. - **The console**: open the run in the UI and inspect logs on any of its actions. ## Stream logs with the CLI Use `flyte get logs` to stream the logs for a run or action: ```bash flyte get logs [] ``` If you provide only the run name, Flyte streams the logs for the run's parent (main) action: ```bash flyte get logs my_run ``` To see the logs for a specific action within the run, provide the action name as the second argument. Action names such as `a0` (the main action) and `a1`, `a2`, โ€ฆ (nested actions) identify each task execution in the run. See **Tasks > Run and deploy tasks > Interact with runs and actions > Understanding runs and actions**: ```bash flyte get logs my_run a0 ``` ### Raw vs. pretty output By default, logs are shown in raw format and scroll the terminal as they arrive. To instead tail the logs in an auto-scrolling box that shows only the most recent lines, pass `--pretty`. Use `--lines`/`-l` to set how many lines the box keeps in view (default `30`); this limit only applies in pretty mode: ```bash flyte get logs my_run a0 --pretty --lines 50 ``` To prepend a timestamp to each log line, add `--show-ts`: ```bash flyte get logs my_run a0 --show-ts ``` ## View the logs for a specific attempt An action can run more than once: Flyte records a separate attempt for each user-configured retry and for each automatic system retry (see **Tasks > Run and deploy tasks > Interact with runs and actions > Understanding runs and actions > Key concepts**). By default, `flyte get logs` shows the logs for the **latest** attempt. To inspect an earlier attempt, pass its number with `--attempt`/`-a`: ```bash flyte get logs my_run a0 --attempt 1 ``` ## Filter out system logs Alongside your task's own output, the logs include system messages emitted by the Flyte runtime. To hide those and show only the logs produced by your task, pass `--filter-system`: ```bash flyte get logs my_run a0 --filter-system ``` ## Scope to a project and domain Like other `flyte get` commands, `flyte get logs` resolves the run within your configured **Get started > Core concepts > Projects and domains**. Override them for a single invocation with `--project`/`-p` and `--domain`/`-d`: ```bash flyte get logs my_run a0 --project my-project --domain development ``` ## Command options | Option | Type | Default | Description | |--------|------|---------|-------------| | `--lines`, `-l` | integer | `30` | Number of lines to show; only applies with `--pretty`. | | `--show-ts` | boolean | `False` | Show timestamps. | | `--pretty` | boolean | `False` | Show logs in an auto-scrolling box, limited to `--lines` lines. | | `--attempt`, `-a` | integer | latest | Attempt number to show logs for; defaults to the latest attempt. | | `--filter-system` | boolean | `False` | Filter all system logs from the output. | | `--project`, `-p` | text | configured | Project to which this command applies. | | `--domain`, `-d` | text | configured | Domain to which this command applies. | For the full command reference, see **Flyte CLI > flyte get logs**. ## View logs in the console Logs are also available in the Union.ai console. Open the run. The `url` attribute of a `flyte.remote.Run` gives its console link: ```python import flyte flyte.init_from_config() run = flyte.remote.Run.get("my_run") print(run.url) # Console URL for the run ``` From the run view, select an action to see its logs, phases, inputs, and outputs. Each attempt of an action has its own logs, as with the CLI. > [!NOTE] > The exact log-viewing controls in the console depend on your deployment and console version. If the layout differs from what is described here, verify the current behavior in your live console. ## Related - **Tasks > Run and deploy tasks > Interact with runs and actions**: retrieve runs, actions, inputs, and outputs. - **Flyte CLI > flyte get logs**: the complete `flyte get logs` reference. - **Tasks > Run and deploy tasks > Debug a run**: use logs and run information to diagnose failures. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/work-with-local-data === Pass local files, directories, and DataFrames into a remote run. # Work with local data When running Flyte tasks that take inputs like DataFrames, files, or directories, data is passed between actions through the configured blob store. For details on how data flows through your workflows, see **Scale your runs > Data flow**. Flyte provides several built-in types for handling data: - `flyte.io.DataFrame` for tabular data - `flyte.io.File` for individual files - `flyte.io.Dir` for directories You can also create custom type extensions for specialized data types. See **Tasks > Build tasks > Custom types** for details. ## Local execution One of the most powerful features of Flyte is the ability to work with data entirely locally, without creating a remote run. When you run tasks in local mode, all inputs, outputs, and intermediate data stay on your local machine. ```python import flyte env = flyte.TaskEnvironment(name="local_data") @env.task async def process_data(data: str) -> str: return f"Processed: {data}" # Run locally - no remote storage needed run = flyte.with_runcontext(mode="local").run(process_data, data="test") run.wait() print(run.outputs()[0]) ``` For more details on local execution, see **Tasks > Run and deploy tasks > How task run works > Local execution**. ## Uploading local data to remote runs When you want to send local data to a remote task, you need to upload it first. Flyte provides a secure data uploading system that handles this automatically. The same system used for **Tasks > Run and deploy tasks > Code packaging for on-cluster execution** can upload files, DataFrames, and directories. To upload local data, use the Flyte core representation for that type with the `from_local_sync()` method. ### Uploading DataFrames Use `flyte.io.DataFrame.from_local_sync()` to upload a local DataFrame: ```python from typing import Annotated import pandas as pd import flyte import flyte.io img = flyte.Image.from_debian_base() img = img.with_pip_packages("pandas", "pyarrow") env = flyte.TaskEnvironment( "dataframe_usage", image=img, resources=flyte.Resources(cpu="1", memory="2Gi"), ) @env.task async def process_dataframe(df: pd.DataFrame) -> pd.DataFrame: """Process a DataFrame and return the result.""" df["processed"] = True return df if __name__ == "__main__": flyte.init_from_config() # Create a local pandas DataFrame local_df = pd.DataFrame({ "name": ["Alice", "Bob", "Charlie"], "value": [10, 20, 30] }) # Upload the local DataFrame for remote execution uploaded_df = flyte.io.DataFrame.from_local_sync(local_df) # Pass to a remote task run = flyte.run(process_dataframe, df=uploaded_df) print(f"Run URL: {run.url}") run.wait() print(run.outputs()[0]) ``` ### Uploading files Use `flyte.io.File.from_local_sync()` to upload a local file: ```python import tempfile import flyte from flyte.io import File env = flyte.TaskEnvironment(name="file-local") @env.task async def process_file(file: File) -> str: """Read and process a file.""" async with file.open("rb") as f: content = bytes(await f.read()) return content.decode("utf-8") if __name__ == "__main__": flyte.init_from_config() # Create a temporary local file with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as temp: temp.write("Hello, Flyte!") temp_path = temp.name # Upload the local file for remote execution file = File.from_local_sync(temp_path) # Pass to a remote task run = flyte.run(process_file, file=file) print(f"Run URL: {run.url}") run.wait() print(run.outputs()[0]) ``` ### Uploading directories Use `flyte.io.Dir.from_local_sync()` to upload a local directory: ```python import os import tempfile import flyte from flyte.io import Dir env = flyte.TaskEnvironment(name="dir-local") @env.task async def process_dir(dir: Dir) -> dict[str, str]: """Process a directory and return file contents.""" file_contents = {} async for file in dir.walk(recursive=False): if file.name.endswith(".py"): async with file.open("rb") as f: content = bytes(await f.read()) file_contents[file.name] = content.decode("utf-8")[:100] return file_contents if __name__ == "__main__": flyte.init_from_config() # Create a temporary directory with test files with tempfile.TemporaryDirectory() as temp_dir: for i in range(3): with open(os.path.join(temp_dir, f"file{i}.py"), "w") as f: f.write(f"print('Hello from file {i}!')") # Upload the local directory for remote execution dir = Dir.from_local_sync(temp_dir) # Pass to a remote task run = flyte.run(process_dir, dir=dir) print(f"Run URL: {run.url}") run.wait() print(run.outputs()[0]) ``` ## Passing outputs between runs If you're passing outputs from a previous run to a new run, no upload is needed. Flyte's data is represented using native references that point to storage locations, so passing them between runs works automatically: ```python import flyte flyte.init_from_config() # Get outputs from a previous run previous_run = flyte.remote.Run.get("my_previous_run") previous_output = previous_run.outputs()[0] # Already a Flyte reference # Pass directly to a new run - no upload needed new_run = flyte.run(my_task, data=previous_output) ``` ## Performance considerations The `from_local_sync()` method uses HTTP to upload data. This is convenient but not the most performant option for large datasets. **Best suited for:** - Small to medium test datasets - Development and debugging - Quick prototyping **For larger data uploads**, configure cloud storage access and use `flyte.storage` directly: ```python import flyte import flyte.storage # Configure storage access flyte.init_from_config( storage=flyte.storage.S3.auto(region="us-east-2") ) ``` For details on configuring storage access, see **Tasks > Run and deploy tasks > Interact with runs and actions > Accessing large data from cloud storage**. ## Summary | Scenario | Approach | |----------|----------| | Local development and testing | Use local execution mode | | Small test data to remote tasks | Use `from_local_sync()` | | Passing data between runs | Pass outputs directly (automatic) | | Large datasets | Configure `flyte.storage` for direct cloud access | === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/run-command-options === Every option flyte run accepts, and what each overrides. # Run command options The `flyte run` command provides the following options: **`flyte run [OPTIONS] |deployed-task `** | Option | Short | Type | Default | Description | |-----------------------------|-------|--------|---------------------------|--------------------------------------------------------| | `--project` | `-p` | text | *from config* | Project to run tasks in | | `--domain` | `-d` | text | *from config* | Domain to run tasks in | | `--local` | | flag | `false` | Run the task locally | | `--copy-style` | | choice | `loaded_modules\|all\|none` | Code bundling strategy | | `--root-dir` | | path | *current dir* | Override source root directory | | `--raw-data-path` | | text | | Override the output location for offloaded data types. | | `--service-account` | | text | | Kubernetes service account. | | `--name` | | text | | Name of the run. | | `--label` | | text | | User-defined `key=value` label on the run. Repeatable. | | `--follow` | `-f` | flag | `false` | Wait and watch logs for the parent action. | | `--image` | | text | | Image to be used in the run (format: `name=uri`). | | `--no-sync-local-sys-paths` | | flag | `false` | Disable synchronization of local sys.path entries. | | `--run-project` | | text | *from config* | Execute deployed task in this project (`deployed-task` only). | | `--run-domain` | | text | *from config* | Execute deployed task in this domain (`deployed-task` only). | These additional options are available on Union.ai: | Option | Short | Type | Default | Description | |--------------------|-------|------|---------|--------------------------------------------------------------------------| | `--tracked` | | flag | `false` | Run the task locally while reporting run state to the control plane. | | `--tracked-strict` | | flag | `false` | Fail the run if reporting fails. Requires `--tracked`. | ## `--project`, `--domain` **`flyte run --domain --project |deployed-task `** You can specify `--project` and `--domain` which will override any defaults defined in your `config.yaml`: ```bash flyte run my_example.py my_task ``` Specify a target project and domain: ```bash flyte run --project my-project --domain development my_example.py my_task ``` ## `--run-project`, `--run-domain` **`flyte run --run-project --run-domain deployed-task `** When using the `deployed-task` subcommand, `--run-project` and `--run-domain` specify the **Get started > Core concepts > Projects and domains** in which to *execute* the task. This lets you run a deployed task in a different project or domain than the one configured in your `config.yaml`: ```bash flyte run --run-project prod-project --run-domain production deployed-task my_env.my_task ``` If not provided, these default to the `task.project` and `task.domain` values in your configuration file. These options only apply to the `deployed-task` subcommand and are ignored for file-based runs. ## `--local` **`flyte run --local `** The `--local` option runs tasks locally, in-process, instead of submitting them to the remote Flyte backend (a devbox or a deployed cluster, whichever your configuration points at): ```bash flyte run --local my_example.py my_task --input "test_data" ``` Compare with on-cluster execution: ```bash flyte run my_example.py my_task --input "test_data" ``` ### When to use local execution - **Development and testing**: Quick iteration without deployment overhead - **Debugging**: Full access to local debugging tools and environment - **Resource constraints**: When remote resources are unavailable or expensive - **Data locality**: When working with large local datasets ## `--tracked`, `--tracked-strict` **`flyte run --tracked `** The `--tracked` option runs the task on your machine, exactly as `--local` does, while reporting the run's progress to the control plane so that you can follow it in the Union.ai console. It implies `--local`, so you do not need to pass both: ```bash flyte run --tracked my_example.py my_task --input "test_data" ``` The run appears under **Tracked Runs** in the project sidebar, a separate section from **Runs**. To try it without writing a file first, use the built-in example: ```bash flyte run --tracked hello ``` Because the run is reported to the control plane, `--tracked` needs an endpoint, project and domain in your configuration, and it cannot be combined with a remote run. Tracking reports the run's actions and attempts, their phases, and their inputs, outputs, reports and cache status. Logs are not reported: your task's output stays in the terminal where you launched the run. You can abort a tracked run from the console, but this cannot stop the process running on your machine. Per-organization limits apply to tracked runs: concurrent runs and actions, actions per run, and run creations per month. Reporting is best-effort by design. If the control plane is slow or unreachable, the failure is logged and the local run continues to completion, so tracking never blocks or fails work that would otherwise have succeeded. To debug reporting itself, add `--tracked-strict`, which turns any reporting failure into a loud run failure: ```bash flyte run --tracked --tracked-strict my_example.py my_task ``` `--tracked-strict` is only meaningful together with `--tracked`; enabling it on its own raises an error. ### Naming a tracked run Tracked runs are named `local-` unless you pass `--name`. Tracking adds two rules on top of the usual `--name` behavior: the name must be at most 30 characters, and it must not begin with `u` or `r`, both of which are reserved for runs the platform names itself. A name that breaks either rule fails before the run starts. ### Tracking every local run To track local runs without passing the flag each time, write the setting into your config file: ```bash flyte create config --local-tracked ``` This sets the `local.tracked` key, after which `flyte run --local` reports to the control plane on its own. The matching key for strict mode is `local.tracked_strict`. To track a run you start from Python, use `flyte.with_runcontext(mode="local", tracked=True)`, or pass `local_tracked=True` to `flyte.init()`. See **Tasks > Run and deploy tasks > How task run works > Tracking a local run**. ## `--copy-style` **`flyte run --copy-style [loaded_modules|all|none] `** The `--copy-style` option controls code bundling for on-cluster execution. This applies to the ephemeral preparation step of the `flyte run` command and works similarly to `flyte deploy`: Smart bundling (default) includes only imported project modules: ```bash flyte run --copy-style loaded_modules my_example.py my_task ``` Include all project files: ```bash flyte run --copy-style all my_example.py my_task ``` No code bundling (the task's code must be in the container image, and `--version` is required): ```bash flyte run --copy-style none --version v1 my_example.py my_task ``` ### Copy style options - **`loaded_modules` (default)**: Bundles only imported Python modules from your project - **`all`**: Includes all files in the project directory - **`none`**: No bundling; the task's code must be in the container image. Requires `--version`. Use `Image.with_code_bundle()` to bake your source into the image (see **Project patterns > Bring your own image**) ## `--root-dir` **`flyte run --root-dir `** Override the source directory for code bundling and import resolution: Run from a monorepo root with a specific root directory: ```bash flyte run --root-dir ./services/ml ./services/ml/my_example.py my_task ``` Handle cross-directory imports: ```bash flyte run --root-dir .. my_example.py my_workflow ``` This applies to the ephemeral preparation step of the `flyte run` command. It works identically to the `flyte deploy` command's `--root-dir` option. ## `--raw-data-path` **`flyte run --raw-data-path `** Override the default output location for offloaded data types (large objects, DataFrames, etc.): Use a custom S3 location for large outputs: ```bash flyte run --raw-data-path s3://my-bucket/custom-path/ my_example.py process_large_data ``` Use a local directory for development: ```bash flyte run --local --raw-data-path ./output/ my_example.py my_task ``` ### Use cases - **Custom storage locations**: Direct outputs to specific S3 buckets or paths - **Cost optimization**: Use cheaper storage tiers for temporary data - **Access control**: Ensure outputs go to locations with appropriate permissions - **Local development**: Store large outputs locally when testing ## `--service-account` **`flyte run --service-account `** Specify a Kubernetes service account for task execution: ```bash flyte run --service-account ml-service-account my_example.py train_model flyte run --service-account data-reader-sa my_example.py load_data ``` ### Use cases - **Cloud resource access**: Service accounts with permissions for S3, GCS, etc. - **Security isolation**: Different service accounts for different workload types - **Compliance requirements**: Enforcing specific identity and access policies ## `--name` **`flyte run --name `** Provide a custom name for the execution run: ```bash flyte run --name "daily-training-run-2024-12-02" my_example.py train_model flyte run --name "experiment-lr-0.01-batch-32" my_example.py hyperparameter_sweep ``` ### Benefits of custom names - **Easy identification**: Find specific runs in the Flyte console - **Experiment tracking**: Include key parameters or dates in names - **Automation**: Programmatically generate meaningful names for scheduled runs ## `--label` **`flyte run --label = `** Attach one or more user-defined `key=value` labels to the run for filtering and organizing runs. The flag is repeatable: ```bash flyte run --label team=ml --label env=prod my_example.py train_model ``` Later, list or filter runs by these labels with `flyte get run --with-label team=ml` (see **Tasks > Run and deploy tasks > Interact with runs and actions > Filtering runs by label**). ## `--follow` **`flyte run --follow `** Wait and watch logs for the execution in real-time: ```bash flyte run --follow my_example.py long_running_task ``` Combine with other options: ```bash flyte run --follow --name "training-session" my_example.py train_model ``` ### Behavior - **Log streaming**: Real-time output from task execution - **Blocking execution**: Command waits until task completes - **Exit codes**: Once the run is submitted, the command exits with code 0 whether the task succeeds or fails. Check the run's status separately ## `--image` **`flyte run --image `** Override container images during ephemeral preparation, same as the equivalent `flyte deploy` option: Override a specific named image: ```bash flyte run --image gpu=ghcr.io/org/gpu:v2.1 my_example.py gpu_task ``` Override the default image: ```bash flyte run --image ghcr.io/org/custom:latest my_example.py my_task ``` Multiple image overrides: ```bash flyte run \ --image base=ghcr.io/org/base:v1.0 \ --image gpu=ghcr.io/org/gpu:v2.0 \ my_example.py multi_env_workflow ``` ### Image mapping formats - **Named mapping**: `name=uri` overrides images created with `Image.from_ref_name("name")` - **Default mapping**: `uri` overrides the default "auto" image - **Multiple mappings**: Use multiple `--image` flags for different image references ## `--no-sync-local-sys-paths` **`flyte run --no-sync-local-sys-paths `** Disable synchronization of local `sys.path` entries to the on-cluster execution environment during ephemeral preparation. Identical to the `flyte deploy` command's `--no-sync-local-sys-paths` option: ```bash flyte run --no-sync-local-sys-paths my_example.py my_task ``` This advanced option works identically to the deploy command equivalent, useful for: - **Container isolation**: Prevent local development paths from affecting on-cluster execution - **Custom environments**: When containers have pre-configured Python paths - **Security**: Avoiding exposure of local directory structures ## Task argument passing A task's inputs are passed **after** the task name. On the CLI every input is a **named option**, `--`, followed by a value when the type requires one, where `` is the exact parameter name in the task's function signature: ```bash flyte run my_file.py my_task --name "World" --count 5 --verbose ``` The equivalent SDK call passes the same inputs as keyword arguments: ```python result = flyte.run(my_task, name="World", count=5, verbose=True) ``` A few rules apply to every input: - **The option name matches the parameter name exactly, including underscores.** A parameter `event_time` is passed as `--event_time` (not `--event-time`). - **Quote any value that contains spaces**, for example `--name "Ada Lovelace"`. - **An input with a default is optional**; an input with no default is required. ### Passing inputs by type Flyte parses each value according to the parameter's Python type. The type-specific syntax is summarized below and detailed in the following sections. | Python type | CLI syntax | Example | |---|---|---| | `str` | Plain text (quote if it contains spaces) | `--name "Ada"` | | `int` | Integer literal | `--count 5` | | `float` | Decimal literal | `--rate 0.01` | | `bool` | A flag (see **Tasks > Run and deploy tasks > Run command options > Task argument passing > Boolean inputs**) | `--verbose` | | `datetime.datetime` / `datetime.date` | ISO 8601, `now`, `today`, or a relative expression | `--start 2024-01-15` | | `datetime.timedelta` | ISO 8601 duration or a human-readable duration | `--timeout PT2H30M` | | `enum.Enum` | The **member name** (case-sensitive) | `--color RED` | | `list` / `dict` | A JSON literal (or a path to a `.json`/`.yaml` file) | `--nums '[1, 2, 3]'` | | dataclass / Pydantic model / `TypedDict` / `NamedTuple` | A JSON literal (or a path to a `.json`/`.yaml` file) | `--config '{"lr": 0.01}'` | | `flyte.io.File` / `flyte.io.Dir` | A local path or a remote URI | `--data ./input.csv` | | `flyte.io.DataFrame` | A path to a `.parquet` or `.csv` file (local or remote) | `--df ./data.parquet` | The `now`/`today`, relative-datetime, human-duration, and JSON-string forms are **CLI conveniences**. When you call `flyte.run()` programmatically, pass the corresponding native Python objects instead (a `datetime.datetime`, a `datetime.timedelta`, a dataclass instance, and so on). ### Boolean inputs A `bool` input is a **flag**, not a value-taking option. Do not write `--debug true`. - If the parameter defaults to `False` (or has no default), pass the bare flag to set it `True`, and omit it to leave it `False`: ```bash flyte run my_file.py my_task --verbose # verbose=True flyte run my_file.py my_task # verbose=False ``` - If the parameter defaults to `True`, Flyte also registers a `--no-` form so you can turn it off: ```bash flyte run my_file.py my_task --no-cache # cache=False ``` ### Datetime and duration inputs A `datetime.datetime` (or `datetime.date`) input accepts an ISO 8601 timestamp, the keywords `now` or `today`, or a **relative expression** of the form ` <+|-> ` (the spaces around the sign are required, so quote the value): ```bash flyte run my_file.py my_task --start 2024-01-15 flyte run my_file.py my_task --start "2024-01-15T13:30:00" flyte run my_file.py my_task --start now flyte run my_file.py my_task --start "now - P1D" # 24 hours ago flyte run my_file.py my_task --start "today + P1DT2H" # tomorrow, 02:00 ``` A `datetime.timedelta` input accepts an ISO 8601 duration or a human-readable duration (`:`, or a value with a unit such as `days`, `hours`, `minutes`, `seconds`): ```bash flyte run my_file.py my_task --timeout P1DT2H30M # 1 day, 2 hours, 30 minutes flyte run my_file.py my_task --timeout "10 days" flyte run my_file.py my_task --timeout "1 minute" flyte run my_file.py my_task --timeout 1:24 # 1 minute, 24 seconds ``` ### Enum inputs For an `enum.Enum` input, pass the **name** of the member (case-sensitive), not its value: ```python # my_file.py import enum class Color(enum.Enum): RED = "red" GREEN = "green" ``` ```bash flyte run my_file.py my_task --color RED ``` ### List, dict, dataclass, and other structured inputs Collections (`list`, `dict`) and structured types (dataclasses, Pydantic models, `TypedDict`, `NamedTuple`) are passed as a **JSON literal**: ```bash flyte run my_file.py my_task --nums '[1, 2, 3]' flyte run my_file.py my_task --mapping '{"a": 1, "b": 2}' flyte run my_file.py my_task --config '{"lr": 0.01, "epochs": 5}' ``` For anything larger than a one-liner, pass a **path to a `.json` or `.yaml` file** instead. Flyte reads and parses the file: ```bash flyte run my_file.py my_task --config ./config.yaml ``` ### File, directory, and dataframe inputs A `flyte.io.File`, `flyte.io.Dir`, or `flyte.io.DataFrame` input accepts either a **local path** or a **remote URI**. A local path is uploaded to the run's data store before execution; a remote URI (for example `s3://โ€ฆ` or `gs://โ€ฆ`) is used as-is. Under `--local`, the local path is used directly without uploading: ```bash flyte run my_file.py my_task --data ./input.csv flyte run my_file.py my_task --data s3://my-bucket/input.csv flyte run my_file.py my_task --df ./data.parquet ``` ### Optional inputs An `Optional[...]` input (or any input with a default) is not required. Omit the option to leave it at its default: ```bash flyte run my_file.py my_task --count 5 # `name` omitted, uses its default ``` ## Positional arguments **The CLI has no positional form for task inputs.** `flyte run` always passes inputs as named options (`--`), as shown above. There is no `flyte run my_file.py my_task "World" 5` form. Positional arguments apply only when you invoke a task **programmatically**. `flyte.run()`, and a direct (native) call to one task from inside another, accept positional arguments and map them to the task's parameters in signature order: CODE36 Two caveats apply: - **Pass a deployed task's inputs by keyword to `flyte.run()`.** For a task retrieved with `flyte.remote.Task.get()`, `flyte.run()` assigns positional arguments to the inputs in alphabetical order of their names, not in signature order. Inside a task, calling the retrieved task directly maps positional arguments in signature order. This requires the task to have been deployed with `flyte` 2.12.3 or later. A task deployed earlier takes keyword arguments only (see [Remote tasks](../task-programming/remote-tasks.md)). - **Don't provide the same input both positionally and by keyword.** ## SDK options The core `flyte run` functionality is also available programmatically through the `flyte.run()` function. For SDK-level configuration of all run parameters (storage, caching, identity, logging, and more), see **Tasks > Run and deploy tasks > Run context**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/custom-cli === Build your own command-line front end when the generated flyte run options are not enough. # Build a custom CLI The built-in `flyte run` command (see **Tasks > Run and deploy tasks > Run command options**) turns your task's parameters into `--` options automatically. That's the fastest way to run a task from the command line, but it gives you the CLI that Flyte generates. When you want your **own** command-line interface (custom argument names, grouped options, subcommands, config files, `--help` text you control), build it with an argument-parsing library of your choice and hand the parsed values to `flyte.run()`. Because `flyte.run()` is an ordinary Python function, any parser works: [`tyro`](https://brentyi.github.io/tyro/), `argparse`, `click`, or `hydra`. ## The pattern A custom CLI wrapper is three steps: 1. **Parse the command line** into a config object (a dataclass, a Pydantic model, or plain arguments) with the parser of your choice. 2. **Initialize Flyte** with `flyte.init_from_config()`. 3. **Run the task** with `flyte.run()`, passing the parsed config as the task's input. ## Example: a typed CLI with `tyro` [`tyro`](https://brentyi.github.io/tyro/) generates a fully-typed CLI directly from a dataclass, so you describe your parameters once and get parsing, validation, and `--help` for free. ```python # /// script # dependencies = [ # "tyro", # "flyte", # ] # /// from dataclasses import dataclass import tyro import flyte env = flyte.TaskEnvironment( name="custom_cli", image=flyte.Image.from_uv_script(__file__, name="flyte"), ) @dataclass class Config: foo: int bar: str = "default" @env.task async def main(config: Config): print(f"foo: {config.foo}, bar: {config.bar}") if __name__ == "__main__": # Generate a CLI and instantiate `Config` with its two arguments: `foo` and `bar`. config = tyro.cli(Config) flyte.init_from_config() run = flyte.run(main, config) print(run.url) ``` Run it like any script, and `tyro` exposes `foo` and `bar` as CLI options and prints `--help` for you: CODE0 Here `tyro.cli(Config)` does the parsing, `flyte.init_from_config()` loads your `config.yaml` (endpoint, project, domain, and so on), and `flyte.run(main, config)` deploys and runs the task with the parsed config as its input. The `config` object is passed **positionally** to `main`, mapping to its `config` parameter. These are ordinary Python positional arguments. ## Using a different parser The pattern is identical whichever library you reach for: only step 1 changes. With the standard library's `argparse`: CODE1 Swap `argparse` for `click` or `hydra` the same way: parse however you like, then call `flyte.run()` with the resulting values (positionally or by keyword). This is also the entry point for richer CLIs: subcommands that each run a different task, `hydra` config composition, environment-driven defaults, and so on. ## When to use which - **Reach for the built-in `flyte run`** when you just need to run a task from the command line and Flyte's generated `--` options are enough. See **Tasks > Run and deploy tasks > Run command options**. - **Build a custom CLI** when you need control over the interface itself (your own option names, subcommands, config-file loading, or help text), or when the CLI is a first-class part of a tool you're shipping. For configuring the run itself (storage, caching, identity, logging) rather than the task's inputs, see **Tasks > Run and deploy tasks > Run context**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/how-task-deployment-works === What flyte deploy and flyte.deploy do under the hood. # How task deployment works This section explains how the `flyte deploy` command and the `flyte.deploy()` SDK function work under the hood to deploy tasks to your Flyte backend. When you perform a deployment, here's what happens: ## 1. Module loading and task environment discovery In the first step, Flyte determines which files to load in order to search for task environments, based on the command-line options provided: ### Single file (default) ```bash flyte deploy my_example.py env ``` - The file `my_example.py` is executed, - All declared `TaskEnvironment` objects in the file are instantiated, but only the one assigned to the variable `env` is selected for deployment. ### `--all` option ```bash flyte deploy --all my_example.py ``` - The file `my_example.py` is executed, - All declared `TaskEnvironment` objects in the file are instantiated and selected for deployment. - No specific variable name is required. ### `--recursive` option ```bash flyte deploy --recursive ./directory ``` - The directory is recursively traversed and all Python files are executed and all `TaskEnvironment` objects are instantiated. - All `TaskEnvironment` objects across all files are selected for deployment. ## 2. Task analysis and serialization - For every task environment selected for deployment, all of its tasks are identified. - Task metadata is extracted: parameter types, return types, and resource requirements. - Each task is serialized into a Flyte `TaskTemplate`. - Dependency graphs between environments are built (see below). ## 3. Task environment dependency resolution In many cases, a task in one environment may invoke a task in another environment, establishing a dependency between the two environments. For example, if `env_a` has a task that calls a task in `env_b`, then `env_a` depends on `env_b`. This means that when deploying `env_a`, `env_b` must also be deployed to ensure that all tasks can be executed correctly. To handle this, `TaskEnvironment`s can declare dependencies on other `TaskEnvironment`s using the `depends_on` parameter. During deployment, the system performs the following steps to resolve these dependencies: 1. Starting with specified environment(s) 2. Recursively discovering all transitive dependencies 3. Including all dependencies in the deployment plan 4. Processing dependencies depth-first to ensure correct order ```python # Define environments with dependencies prep_env = flyte.TaskEnvironment(name="preprocessing") ml_env = flyte.TaskEnvironment(name="ml_training", depends_on=[prep_env]) viz_env = flyte.TaskEnvironment(name="visualization", depends_on=[ml_env]) # Deploy only viz_env - automatically includes ml_env and prep_env deployment = flyte.deploy(viz_env, version="v2.0.0") # Or deploy multiple environments explicitly deployment = flyte.deploy(data_env, ml_env, viz_env, version="v2.0.0") ``` For detailed information about working with multiple environments, see **Tasks > Configure tasks > Multiple environments**. ## 4. Code bundle creation and upload Once the task environments and their dependencies are resolved, Flyte proceeds to package your code into a bundle based on the `copy_style` option: ### `--copy_style loaded_modules` (default) This is the smart bundling approach that analyzes which Python modules were actually imported during the task environment discovery phase. It examines the runtime module registry (`sys.modules`) and includes only those modules that meet specific criteria: they must have source files located within your project directory (not in system locations like `site-packages`), and they must not be part of the Flyte SDK itself. This selective approach results in smaller, faster-to-upload bundles that contain exactly the code needed to run your tasks, making it ideal for most development and production scenarios. ### `--copy_style all` This bundling strategy takes a directory-walking approach, recursively traversing your entire project directory and including every file it encounters. Unlike the smart bundling that only includes imported Python modules, this method captures all project files regardless of whether they were imported during discovery. This is particularly useful for projects that use dynamic imports, load configuration files or data assets at runtime, or have dependencies that aren't captured through normal Python import mechanisms. ### `--copy_style none` This option completely skips code bundle creation, meaning no source code is packaged or uploaded to cloud storage. When using this approach, you must provide an explicit version parameter since there's no code bundle to generate a version from. This strategy is designed for scenarios where your code is already baked into custom container images, eliminating the need for separate code injection during task execution. It results in the fastest deployment times but requires more complex image management workflows. ### `--root-dir` option By default, Flyte uses your current working directory as the root for code bundling. You can override this with `--root-dir` to specify a different base directory - particularly useful for monorepos or when deploying from subdirectories. This affects all copy styles: `loaded_modules` will look for imported modules relative to the root directory, `all` will walk the directory tree starting from the root, and the root directory setting works with any copy style. See the **Tasks > Run and deploy tasks > Deploy command options > `--root-dir`** for detailed usage examples. After the code bundle is created (if applicable), it is uploaded to a cloud storage location (like S3 or GCS) accessible by your Flyte backend. It is now ready to be run. ## 5. Image building If your `TaskEnvironment` specifies **Tasks > Configure tasks > Container images**, Flyte builds and pushes container images before deploying tasks. The build process varies based on your configuration and backend type: ### Local image building When `image.builder` is set to `local` in **Get started > Run modes > Run on a deployed cluster**, images are built on your local machine using Docker. This approach: - Requires Docker to be installed and running on your development machine - Uses Docker BuildKit to build images from generated Dockerfiles or your custom Dockerfile - Pushes built images to the container registry specified in your `Image` configuration - Is one of the two options available for Flyte OSS instances (the other is `local-podman`, below) When `image.builder` is set to `local-podman` (requires flyte 2.10.6 or later), images are built and pushed on your local machine with Podman instead of Docker. Podman must be on your `PATH`. See **Tasks > Configure tasks > Container images > Image building > Local image building**. ### Remote image building When `image.builder` is set to `remote` in **Get started > Run modes > Run on a deployed cluster**, images are built on cloud infrastructure. This approach: - Builds images using Union's ImageBuilder service (currently only available for Union backends, not OSS Flyte) - Requires no local Docker installation or configuration - Can push to Union's internal registry or external registries you specify - Provides faster, more consistent builds by leveraging cloud resources > [!NOTE] > Remote building is currently exclusive to Union backends. OSS Flyte installations must use `local` or `local-podman`. ## 6. Source-code link discovery While each task is being serialized in step 2, Flyte attempts to attach a link from the task back to the source line of its Python function. The link is rendered next to the task description in the UI, so anyone viewing a deployed task can jump directly to the code that defines it. This is fully automatic. There is no decorator argument, no config flag, and no opt-in step. If the conditions below are met, the link appears. ### How the link is built Flyte inspects the local repository at deploy time using the standard `git` CLI: - The repository root, current commit SHA, working-tree-clean status, and remote push URL are read via `git rev-parse` and `git remote get-url --push origin`. - The file path is taken from the task function's `__code__.co_filename`, made relative to the repo root. - The line number is the line of the function definition (the line just after the `@env.task` decorator). - For a GitHub remote, the URL takes the form `https://github.com///blob//#L`. GitLab uses the equivalent `/-/blob/` form. The `#L` anchor is only included when the working tree is clean. A dirty tree still produces a valid blob URL, but without the line jump, because the local file may no longer match the committed file. ### Conditions For the link to appear, all of the following must hold: - The `git` CLI is installed and the directory you deploy from is inside a git repository. - The repository has a remote. The push URL of `origin` is preferred; otherwise the first remote, alphabetically, is used. - The remote host is `github.com` or `gitlab.com`. Other hosts (Bitbucket, self-hosted Gitea, GitHub Enterprise on a custom domain, etc.) currently produce no link. - The task's source file lives under the repository root. If any condition fails, the deploy still succeeds: only the source-code link is omitted. > [!NOTE] > Flyte does not check whether the current commit has been pushed. > If you deploy from a clean local commit that is not yet on the remote, the URL will resolve to a missing SHA on GitHub or GitLab. > Push your commit before deploying if you want the link to be followable. For private repositories, the link is still generated; viewers need to be authenticated to the host to follow it. See `flyte.git.GitStatus` for the underlying API. ## Understanding option relationships It's important to understand how the various deployment options work together. The **discovery options** (`--recursive` and `--all`) operate independently of the **bundling options** (`--copy-style`), giving you flexibility in how you structure your deployments. Environment discovery determines which files Flyte will examine to find `TaskEnvironment` objects, while code bundling controls what gets packaged and uploaded for execution. You can freely combine these approaches. For example, discovering environments recursively across your entire project while using smart bundling to include only the necessary code modules. When multiple environments are discovered, they all share the same code bundle, which is efficient for related services or components that use common dependencies: ```bash flyte deploy --recursive --copy-style loaded_modules ./project ``` > [!NOTE] > All discovered environments share the same code bundle. For a full overview of all deployment options, see **Flyte CLI > flyte deploy**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/deploy-command-options === Every option flyte deploy accepts, and what each overrides. # Deploy command options The `flyte deploy` command provides extensive configuration options: **`flyte deploy [OPTIONS] [TASK_ENV_VARIABLE]`** | Option | Short | Type | Default | Description | |-----------------------------|-------|--------|---------------------------|---------------------------------------------------| | `--project` | `-p` | text | *from config* | Project to deploy to | | `--domain` | `-d` | text | *from config* | Domain to deploy to | | `--version` | | text | *auto-generated* | Explicit version tag for deployment | | `--dry-run`/`--dryrun` | | flag | `false` | Preview deployment without executing | | `--all` | | flag | `false` | Deploy all environments in specified path | | `--recursive` | `-r` | flag | `false` | Deploy environments recursively in subdirectories | | `--copy-style` | | choice | `loaded_modules\|all\|none` | Code bundling strategy | | `--root-dir` | | path | *current dir* | Override source root directory | | `--image` | | text | | Image URI mappings (format: `name=uri`) | | `--ignore-load-errors` | `-i` | flag | `false` | Continue deployment despite module load failures | | `--no-sync-local-sys-paths` | | flag | `false` | Disable local `sys.path` synchronization | ## `--project`, `--domain` **`flyte deploy --domain --project `** You can specify `--project` and `--domain` which will override any defaults defined in your `config.yaml`: ```bash flyte deploy my_example.py env ``` Specify a target project and domain: ```bash flyte deploy --project my-project --domain development my_example.py env ``` ## `--version` **`flyte deploy --version `** The `--version` option controls how deployed tasks are tagged and identified in the Flyte backend: Auto-generated version (default): ```bash flyte deploy my_example.py env ``` Explicit version: ```bash flyte deploy --version v1.0.0 my_example.py env ``` > [!NOTE] > An explicit version is required when using `--copy-style none`, since there is no code bundle to generate a hash from. ```bash flyte deploy --copy-style none --version v1.0.0 my_example.py env ``` ### When versions are used - **Explicit versioning**: Provides human-readable task identification (e.g., `v1.0.0`, `prod-2024-12-01`) - **Auto-generated versions**: When no version is specified, Flyte creates an MD5 hash from the code bundle, environment configuration, and image cache - **Version requirement**: `copy-style none` mandates explicit versions since there's no code bundle to hash - **Task referencing**: Versions enable precise task references in `flyte run deployed-task` and workflow invocations ## `--dry-run` **`flyte deploy --dry-run `** The `--dry-run` option allows you to preview what would be deployed without actually performing the deployment: ```bash flyte deploy --dry-run my_example.py env ``` ## `--all` and `--recursive` **`flyte deploy --all `** **`flyte deploy --recursive `** Control which environments get discovered and deployed: **Single environment (default):** ```bash flyte deploy my_example.py env ``` **All environments in file:** ```bash flyte deploy --all my_example.py ``` **Recursive directory deployment:** ```bash flyte deploy --recursive ./src ``` Combine with comprehensive bundling: ```bash flyte deploy --recursive --copy-style all ./project ``` ## `--copy-style` **`flyte deploy --copy_style [loaded_modules|all|none] `** The `--copy-style` option controls what gets packaged: ### `--copy-style loaded_modules` (default) ```bash flyte deploy --copy-style loaded_modules my_example.py env ``` - **Includes**: Only imported Python modules from your project - **Excludes**: Site-packages, system modules, Flyte SDK - **Best for**: Most projects (optimal size and speed) ### `--copy-style all` ```bash flyte deploy --copy-style all my_example.py env ``` - **Includes**: All files in project directory - **Best for**: Projects with dynamic imports or data files ### `--copy-style none` ```bash flyte deploy --copy-style none --version v1.0.0 my_example.py env ``` - **Requires**: Explicit version parameter - **Best for**: Pre-built container images with baked-in code ## `--root-dir` **`flyte deploy --root-dir `** The `--root-dir` option overrides the default source directory that Flyte uses as the base for code bundling and import resolution. This is particularly useful for monorepos and projects with complex directory structures. ### Default behavior (without `--root-dir`) - Flyte uses the current working directory as the root - Code bundling starts from this directory - Import paths are resolved relative to this location ### Common use cases **Monorepos:** Deploy a service from the monorepo root: ```bash flyte deploy --root-dir ./services/ml ./services/ml/my_example.py env ``` Deploy from anywhere in the monorepo: ```bash cd ./docs/ flyte deploy --root-dir ../services/ml ../services/ml/my_example.py env ``` **Cross-directory imports:** When a workflow imports modules from sibling directories (e.g., `project/workflows/my_example.py` imports `project/src/utils.py`): ```bash cd project/workflows/ flyte deploy --root-dir .. my_example.py env ``` **Working directory independence:** ```bash flyte deploy --root-dir /path/to/project /path/to/project/my_example.py env ``` ### How it works 1. **Code bundling**: Files are collected starting from `--root-dir` instead of the current working directory 2. **Import resolution**: Python imports are resolved relative to the specified root directory 3. **Path consistency**: Ensures the same directory structure in local and on-cluster execution environments 4. **Dependency packaging**: Captures all necessary modules that may be located outside the workflow file's immediate directory ### Example with complex project structure ``` my-project/ โ”œโ”€โ”€ services/ โ”‚ โ”œโ”€โ”€ ml/ โ”‚ โ”‚ โ””โ”€โ”€ my_example.py # imports shared.utils โ”‚ โ””โ”€โ”€ api/ โ””โ”€โ”€ shared/ โ””โ”€โ”€ utils.py ``` ```bash flyte deploy --root-dir ./my-project ./my-project/services/ml/my_example.py env ``` This ensures that both `services/ml/` and `shared/` directories are included in the code bundle, allowing the workflow to successfully import `shared.utils` during on-cluster execution. ## `--image` **`flyte deploy --image `** The `--image` option allows you to override image URIs at deployment time without modifying your code. Format: `imagename=imageuri` ### Named image mappings ```bash flyte deploy --image base=ghcr.io/org/base:v1.0 my_example.py env ``` Multiple named image mappings: ```bash flyte deploy \ --image base=ghcr.io/org/base:v1.0 \ --image gpu=ghcr.io/org/gpu:v2.0 \ my_example.py env ``` ### Default image mapping ```bash flyte deploy --image ghcr.io/org/default:latest my_example.py env ``` ### How it works - Named mappings (e.g., `base=URI`) override images created with `Image.from_ref_name("base")`. - Unnamed mappings (e.g., just `URI`) override the default "auto" image. - Multiple `--image` flags can be specified. - Mappings are resolved during the image building phase of deployment. ## `--ignore-load-errors` **`flyte deploy --ignore-load-errors `** The `--ignore-load-errors` option allows the deployment process to continue even if some modules fail to load during the environment discovery phase. This is particularly useful for large projects or monorepos where certain modules may have missing dependencies or other issues that prevent them from being imported successfully. ```bash flyte deploy --recursive --ignore-load-errors ./large-project ``` ## `--no-sync-local-sys-paths` **`flyte deploy --no-sync-local-sys-paths `** The `--no-sync-local-sys-paths` option disables the automatic synchronization of local `sys.path` entries to the remote container environment. This is an advanced option for specific deployment scenarios. ### Default behavior (path synchronization enabled) - Flyte captures local `sys.path` entries that are under the root directory - These paths are passed to the remote container via the `_F_SYS_PATH` environment variable - At runtime, the remote container adds these paths to its `sys.path`, maintaining the same import environment ### When to disable path synchronization ```bash flyte deploy --no-sync-local-sys-paths my_example.py env ``` ### Use cases for disabling - **Custom container images**: When your container already has the correct `sys.path` configuration - **Conflicting path structures**: When local development paths would interfere with container paths - **Security concerns**: When you don't want to expose local development directory structures - **Minimal environments**: When you want precise control over what gets added to the container's Python path ### How it works - **Enabled (default)**: Local paths like `./my_project/utils` get synchronized and added to remote `sys.path` - **Disabled**: Only the container's native `sys.path` is used, along with the deployed code bundle Most users should leave path synchronization enabled unless they have specific requirements for container path isolation or are using pre-configured container environments. ## SDK deployment options The core deployment functionality is available programmatically through the `flyte.deploy()` function, though some CLI-specific options are not applicable: ```python import flyte env = flyte.TaskEnvironment(name="my_env") @env.task async def process_data(data: str) -> str: return f"Processed: {data}" if __name__ == "__main__": flyte.init_from_config() # Comprehensive deployment configuration deployment = flyte.deploy( env, # Environment to deploy dry_run=False, # Set to True for a dry run version="v1.2.0", # Explicit version tag copy_style="loaded_modules" # Code bundling strategy ) print(f"Deployment successful: {deployment[0].summary_repr()}") ``` `dry_run` requires `flyte` 2.8.0 or later; earlier versions take `dryrun`. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/packaging === The two ways to get your code into the execution environment. # Code packaging for on-cluster execution When you run Flyte tasks on-cluster, your code needs to be available in the execution environment. Flyte SDK provides two main approaches for packaging your code: 1. **Code bundling** - Bundle code dynamically at runtime 2. **Container-based deployment** - Embed code directly in container images ## Quick comparison | Aspect | Code bundling | Container-based | |--------|---------------|-----------------| | **Speed** | Fast (no image rebuild) | Slower (requires image build) | | **Best for** | Rapid development, iteration | Production, immutable deployments | | **Code changes** | Immediate effect | Requires image rebuild | | **Setup** | Automatic by default | Manual configuration needed | | **Reproducibility** | Excellent (hash-based versioning) | Excellent (immutable images) | | **Rollback** | Requires version control | Tag-based, straightforward | --- ## Code bundling **Default approach** - Automatically bundles and uploads your code to remote storage at runtime. ### How it works When you run `flyte run` or call `flyte.run()`, Flyte automatically: 1. **Scans loaded modules** from your codebase 2. **Creates a tarball** (gzipped, without timestamps for consistent hashing) 3. **Uploads to blob storage** (S3, GCS, Azure Blob) 4. **Deduplicates** based on content hashes 5. **Downloads in containers** at runtime This process happens transparently - every container downloads and extracts the code bundle before execution. > [!NOTE] > Code bundling is optimized for speed: > > - Bundles are created without timestamps for consistent hashing > - Identical code produces identical hashes, enabling deduplication > - Only modified code triggers new uploads > - Containers cache downloaded bundles > > **Reproducibility:** Flyte automatically versions code bundles based on content hash. The same code always produces the same hash, guaranteeing reproducibility without manual versioning. However, version control is still recommended for rollback capabilities. ### Automatic code bundling **Default behavior** - Bundles all loaded modules automatically. #### What gets bundled Flyte includes modules that are: - โœ… **Loaded when environment is parsed** (imported at module level) - โœ… **Part of your codebase** (not system packages) - โœ… **Within your project directory** - โŒ **NOT lazily loaded** (imported inside functions) - โŒ **NOT system-installed packages** (e.g., from site-packages) #### Example: Basic automatic bundling ```python # app.py import flyte from my_module import helper # โœ… Bundled automatically env = flyte.TaskEnvironment( name="default", image=flyte.Image.from_debian_base().with_pip_packages("pandas", "numpy") ) @env.task def process_data(x: int) -> int: # This import won't be bundled (lazy load) from another_module import util # โŒ Not bundled automatically return helper.transform(x) if __name__ == "__main__": flyte.init_from_config() run = flyte.run(process_data, x=42) print(run.url) ``` When you run this: ```bash flyte run app.py process_data --x 42 ``` Flyte automatically: 1. Bundles `app.py` and `my_module.py` 2. Preserves the directory structure 3. Uploads to blob storage 4. Makes it available in the remote container #### Project structure example ``` my_project/ โ”œโ”€โ”€ app.py # Main entry point โ”œโ”€โ”€ tasks/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ”œโ”€โ”€ data_tasks.py # Flyte tasks โ”‚ โ””โ”€โ”€ ml_tasks.py โ””โ”€โ”€ utils/ โ”œโ”€โ”€ __init__.py โ”œโ”€โ”€ preprocessing.py # Business logic โ””โ”€โ”€ models.py ``` ```python # app.py import flyte from tasks.data_tasks import load_data # โœ… Bundled from tasks.ml_tasks import train_model # โœ… Bundled # utils modules imported in tasks are also bundled @flyte.task def pipeline(dataset: str) -> float: data = load_data(dataset) accuracy = train_model(data) return accuracy if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline, dataset="train.csv") ``` **All modules are bundled with their directory structure preserved.** ### Manual code bundling Control exactly what gets bundled by configuring the copy style. #### Copy styles Four values are accepted: 1. **`"loaded_modules"`** (default) - Bundle only the Python modules from your project that the process has imported 2. **`"all"`** - Bundle everything in the working directory 3. **`"none"`** - Skip bundling entirely (requires code in container) 4. **`"custom"`** - Used by the CLI to bundle a file list it has already worked out. `flyte.with_runcontext()` rejects it > [!NOTE] > Earlier versions of this page gave the default as `"auto"`. That is not a valid value, but the SDK accepts it without complaint and bundles every file, exactly as `"all"` does. If your code sets `copy_style="auto"`, change it to `"loaded_modules"`. #### Using `copy_style="all"` Bundle all files under your project directory: ```python import flyte flyte.init_from_config() # Bundle everything in current directory run = flyte.with_runcontext(copy_style="all").run( my_task, input_data="sample.csv" ) ``` Or via CLI: ```bash flyte run --copy-style=all app.py my_task --input-data sample.csv ``` **Use when:** - You have data files or configuration that tasks need - You use dynamic imports or lazy loading - You want to ensure all project files are available #### Using `copy_style="none"` Skip code bundling (see **Tasks > Run and deploy tasks > Code packaging for on-cluster execution > Container-based deployment**): ```python run = flyte.with_runcontext(copy_style="none").run(my_task, x=10) ``` ### Including additional files with `include` Code bundling discovers Python modules by following imports. That's the right behavior for source code, but it won't pick up non-Python assets like HTML templates, SQL files, small reference datasets, prompt files, or configuration files. Your task imports Python, not an `.html` file, so those assets never show up in the bundle. The `include` parameter on `TaskEnvironment` lets you attach these extra files to the environment's bundle explicitly: ```python import flyte env = flyte.TaskEnvironment( name="html_template_report", image=flyte.Image.from_debian_base(python_version=(3, 12)), include=("report_template.html",), ) ``` At bundling time, Flyte resolves each entry, unions it with whatever the `copy_style` discovered, and ships everything in the same tarball. The files land in the container at the same path they occupy in your project, so the task can read them with a normal relative path: ```python from datetime import datetime, timezone from pathlib import Path import flyte import flyte.report env = flyte.TaskEnvironment( name="html_template_report", image=flyte.Image.from_debian_base(python_version=(3, 12)), include=("report_template.html",), ) @env.task(report=True) async def generate_template_report() -> str: template_path = Path(__file__).parent / "report_template.html" template = template_path.read_text() body = template.format( title="Hello", generated_at=datetime.now(timezone.utc).isoformat(timespec="seconds"), ) flyte.report.get_tab("Main").log(body) await flyte.report.flush.aio() return "ok" ``` #### How paths are resolved - **Relative paths** are anchored at the directory of the file where the `TaskEnvironment` is instantiated, not at `root_dir` or the current working directory. `include=("report_template.html",)` looks for `report_template.html` next to the Python file that declared the env. - **Absolute paths** are used as-is. - **Directories** are included recursively. - **Glob patterns** are expanded against the declaring file's directory. `include` supplements the `copy_style` discovery; it does not replace it. Files listed here are bundled *in addition to* the Python modules that `copy_style` picks up. It also works alongside `copy_style="none"`. In that case, only the include entries are bundled. #### When to use `include` Good fits: - **HTML templates** rendered into reports (see the [reports examples](https://github.com/flyteorg/flyte-sdk/tree/main/examples/reports) in the SDK). - **Small configuration files** (YAML, JSON, TOML) that the task reads at runtime. - **SQL files, prompt templates, or other text assets** versioned alongside the task. - **Small reference data files** (a few MB of lookup tables, fixtures, etc.). - **Small model files** that you want versioned with the task code. > [!WARNING] > **Don't bundle large files with `include`.** Every container that runs the task downloads the full bundle before it starts, so large includes directly inflate cold-start latency and eat network bandwidth on every execution. As a rule of thumb, if a file is more than a few MB, or if it changes independently of your code, it doesn't belong in `include`. > > For larger assets, prefer one of these instead: > > 1. **Store in object storage (most recommended)**: keep the file in S3, GCS, or Azure Blob and read it with `flyte.io.File("s3://...")` or the cloud SDK of your choice. The file is fetched only when needed, cached independently of the code bundle, and can be updated without redeploying. > 2. **Bake into the container image**: use **Tasks > Run and deploy tasks > Code packaging for on-cluster execution > Container-based deployment > Image source copying methods** when the asset is stable and tied to a specific image version. The file is downloaded once when the image is pulled, not on every run. ### Controlling the root directory The `root_dir` parameter controls which directory serves as the bundling root. #### Why root directory matters 1. **Determines what gets bundled** - All code paths are relative to root_dir 2. **Preserves import structure** - Python imports must match the bundle structure 3. **Affects path resolution** - Files and modules are located relative to root_dir #### Setting root directory ##### Via CLI ```bash flyte run --root-dir /path/to/project app.py my_task ``` ##### Programmatically ```python import pathlib import flyte flyte.init_from_config( root_dir=pathlib.Path(__file__).parent ) ``` #### Root directory use cases ##### Use case 1: Multi-module project ``` project/ โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ workflows/ โ”‚ โ”‚ โ””โ”€โ”€ pipeline.py โ”‚ โ””โ”€โ”€ utils/ โ”‚ โ””โ”€โ”€ helpers.py โ””โ”€โ”€ config.yaml ``` ```python # src/workflows/pipeline.py import pathlib import flyte from utils.helpers import process # Relative import from project root # Set root to project root (not src/) flyte.init_from_config( root_dir=pathlib.Path(__file__).parent.parent.parent ) @flyte.task def my_task(): return process() ``` **Root set to `project/` so imports like `from utils.helpers` work correctly.** ##### Use case 2: Shared utilities ``` workspace/ โ”œโ”€โ”€ shared/ โ”‚ โ””โ”€โ”€ common.py โ””โ”€โ”€ project/ โ””โ”€โ”€ app.py ``` ```python # project/app.py import flyte import pathlib from shared.common import shared_function # Import from parent directory # Set root to workspace/ to include shared/ flyte.init_from_config( root_dir=pathlib.Path(__file__).parent.parent ) ``` ##### Use case 3: Monorepo ``` monorepo/ โ”œโ”€โ”€ libs/ โ”‚ โ”œโ”€โ”€ data/ โ”‚ โ””โ”€โ”€ models/ โ””โ”€โ”€ services/ โ””โ”€โ”€ ml_service/ โ””โ”€โ”€ workflows.py ``` ```python # services/ml_service/workflows.py import flyte import pathlib from libs.data import loader # Import from monorepo root from libs.models import predictor # Set root to monorepo/ to include libs/ flyte.init_from_config( root_dir=pathlib.Path(__file__).parent.parent.parent ) ``` #### Root directory best practices 1. **Set root_dir at project initialization** before importing any task modules 2. **Use absolute paths** with `pathlib.Path(__file__).parent` navigation 3. **Match your import structure** - if imports are relative to project root, set root_dir to project root 4. **Keep consistent** - use the same root_dir for both `flyte run` and `flyte.init()` ### Code bundling examples #### Example: Standard Python package ``` my_package/ โ”œโ”€โ”€ pyproject.toml โ”œโ”€โ”€ src/ โ”‚ โ””โ”€โ”€ my_package/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ”œโ”€โ”€ main.py โ”‚ โ”œโ”€โ”€ data/ โ”‚ โ”‚ โ”œโ”€โ”€ loader.py โ”‚ โ”‚ โ””โ”€โ”€ processor.py โ”‚ โ””โ”€โ”€ models/ โ”‚ โ””โ”€โ”€ analyzer.py ``` ```python # src/my_package/main.py import flyte import pathlib from my_package.data.loader import fetch_data from my_package.data.processor import clean_data from my_package.models.analyzer import analyze env = flyte.TaskEnvironment( name="pipeline", image=flyte.Image.from_debian_base().with_uv_project( pyproject_file=pathlib.Path(__file__).parent.parent.parent / "pyproject.toml" ) ) @env.task async def fetch_task(url: str) -> dict: return await fetch_data(url) @env.task def process_task(raw_data: dict) -> list[dict]: return clean_data(raw_data) @env.task def analyze_task(data: list[dict]) -> str: return analyze(data) if __name__ == "__main__": import flyte.git # Set root to project root for proper imports flyte.init_from_config( flyte.git.config_from_root(), root_dir=pathlib.Path(__file__).parent.parent.parent ) # All modules bundled automatically run = flyte.run(analyze_task, data=[{"value": 1}, {"value": 2}]) print(f"Run URL: {run.url}") ``` **Run with:** ```bash cd my_package flyte run src/my_package/main.py analyze_task --data '[{"value": 1}]' ``` #### Example: Dynamic environment based on domain ```python # environment_picker.py import flyte def create_env(): """Create different environments based on domain.""" if flyte.current_domain() == "development": return flyte.TaskEnvironment( name="dev", image=flyte.Image.from_debian_base(), env_vars={"ENV": "dev", "DEBUG": "true"} ) elif flyte.current_domain() == "staging": return flyte.TaskEnvironment( name="staging", image=flyte.Image.from_debian_base(), env_vars={"ENV": "staging", "DEBUG": "false"} ) else: # production return flyte.TaskEnvironment( name="prod", image=flyte.Image.from_debian_base(), env_vars={"ENV": "production", "DEBUG": "false"}, resources=flyte.Resources(cpu="2", memory="4Gi") ) env = create_env() @env.task async def process(n: int) -> int: import os print(f"Running in {os.getenv('ENV')} environment") return n * 2 if __name__ == "__main__": flyte.init_from_config() run = flyte.run(process, n=5) print(run.url) ``` **Why this works:** - `flyte.current_domain()` is set correctly when Flyte re-instantiates modules remotely - Environment configuration is deterministic and reproducible - Code automatically bundled with domain-specific settings > [!NOTE] > `flyte.current_domain()` only works after `flyte.init()` is called: > > - โœ… Works with `flyte run` and `flyte deploy` (auto-initialize) > - โœ… Works in `if __name__ == "__main__"` after explicit `flyte.init()` > - โŒ Does NOT work at module level without initialization ### When to use code bundling โœ… **Use code bundling when:** - Rapid development and iteration - Frequently changing code - Multiple developers testing changes - Jupyter notebook workflows - Quick prototyping and experimentation โŒ **Consider container-based instead when:** - Need easy rollback to previous versions (container tags are simpler than finding git commits) - Working with air-gapped environments (no blob storage access) - Code changes require coordinated dependency updates --- ## Container-based deployment **Advanced approach** - Embed code directly in container images for immutable deployments. ### How it works Instead of bundling code at runtime: 1. **Build container image** with code copied inside 2. **Disable code bundling** with `copy_style="none"` 3. **Container has everything** needed at runtime **Trade-off:** Every code change requires a new image build (slower), but provides complete reproducibility. ### Configuration Three key steps: #### 1. Set `copy_style="none"` Disable runtime code bundling: ```python flyte.with_runcontext(copy_style="none").run(my_task, n=10) ``` Or via CLI: ```bash flyte run --copy-style=none app.py my_task --n 10 ``` #### 2. Copy code into image Use `Image.with_source_file()` or `Image.with_source_folder()`: ```python import pathlib import flyte env = flyte.TaskEnvironment( name="embedded", image=flyte.Image.from_debian_base().with_source_folder( src=pathlib.Path(__file__).parent, copy_contents_only=True ) ) ``` #### 3. Set correct `root_dir` Match your image copy configuration: ```python flyte.init_from_config( root_dir=pathlib.Path(__file__).parent ) ``` ### Image source copying methods #### `with_source_file()` - copy individual files Copy a single file into the container: ```python image = flyte.Image.from_debian_base().with_source_file( src=pathlib.Path(__file__), dst="/app/main.py" ) ``` **Use for:** - Single-file workflows - Copying configuration files - Adding scripts to existing images #### `with_source_folder()` - copy directories Copy entire directories into the container: ```python image = flyte.Image.from_debian_base().with_source_folder( src=pathlib.Path(__file__).parent, copy_contents_only=False # Copy folder itself ) ``` **Parameters:** - `src`: Source directory path - `dst`: Destination path in container (optional, defaults to workdir) - `copy_contents_only`: If `True`, copies folder contents; if `False` and `dst` is left out, copies the folder itself. With any other `dst`, the folder's contents are copied into `dst` either way ##### `copy_contents_only=True` (Recommended) Copies only the contents of the source folder: ```python # Project structure: # my_project/ # โ”œโ”€โ”€ app.py # โ””โ”€โ”€ utils.py image = flyte.Image.from_debian_base().with_source_folder( src=pathlib.Path(__file__).parent, copy_contents_only=True ) # Container will have (in the image's working directory, /home/flyte for from_debian_base()): # /home/flyte/app.py # /home/flyte/utils.py # Set root_dir to match: flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) ``` ##### `copy_contents_only=False` When `dst` is left out, copies the folder itself, with its name, into the image's working directory: ```python # Project structure: # workspace/ # โ””โ”€โ”€ my_project/ # โ”œโ”€โ”€ app.py # โ””โ”€โ”€ utils.py image = flyte.Image.from_debian_base().with_source_folder( src=pathlib.Path(__file__).parent, # Points to my_project/ copy_contents_only=False ) # Container will have (in the image's working directory, /home/flyte for from_debian_base()): # /home/flyte/my_project/app.py # /home/flyte/my_project/utils.py # Set root_dir to parent to match: flyte.init_from_config(root_dir=pathlib.Path(__file__).parent.parent) ``` ### Complete container-based example ```python # full_build.py import pathlib import flyte from dep import helper # Local module # Configure environment with source copying env = flyte.TaskEnvironment( name="full_build", image=flyte.Image.from_debian_base() .with_pip_packages("numpy", "pandas") .with_source_folder( src=pathlib.Path(__file__).parent, copy_contents_only=True ) ) @env.task def square(x: int) -> int: return x ** helper.get_exponent() @env.task def main(n: int) -> list[int]: return list(flyte.map(square, range(n))) if __name__ == "__main__": import flyte.git # Initialize with matching root_dir flyte.init_from_config( flyte.git.config_from_root(), root_dir=pathlib.Path(__file__).parent ) # Run with copy_style="none" and explicit version run = flyte.with_runcontext( copy_style="none", version="v1.0.0" # Explicit task version ).run(main, n=10) print(f"Run URL: {run.url}") run.wait() ``` **Project structure:** ``` project/ โ”œโ”€โ”€ full_build.py โ”œโ”€โ”€ dep.py # Local dependency โ””โ”€โ”€ .flyte/ โ””โ”€โ”€ config.yaml ``` **Run with:** ```bash python full_build.py ``` This will: 1. Build a container image with `full_build.py` and `dep.py` embedded 2. Tag it with a hash of the image's contents, including the copied source 3. Push to registry 4. Execute remotely without code bundling ### Using externally built images When containers are built outside of Flyte (e.g., in CI/CD), use `Image.from_ref_name()`: #### Step 1: Build your image externally ```dockerfile # Dockerfile FROM python:3.11-slim WORKDIR /app # Copy your code COPY src/ /app/ # Install dependencies RUN pip install flyte pandas numpy # Ensure flyte executable is available RUN flyte --help ``` Build and push the image: ```bash docker build -t myregistry.com/my-app:v1.2.3 . docker push myregistry.com/my-app:v1.2.3 ``` #### Step 2: Reference image by name ```python # app.py import flyte env = flyte.TaskEnvironment( name="external", image=flyte.Image.from_ref_name("my-app-image") # Reference name ) @env.task def process(x: int) -> int: return x * 2 if __name__ == "__main__": # Map the reference name to the actual image URI flyte.init_from_config(images=("my-app-image=myregistry.com/my-app:v1.2.3",)) # copy_style="none" requires an explicit version run = flyte.with_runcontext(copy_style="none", version="v1.2.3").run(process, x=10) ``` Or via CLI: ```bash flyte run \ --copy-style=none \ --image my-app-image=myregistry.com/my-app:v1.2.3 \ app.py process --x 10 ``` **For deployment:** ```bash flyte deploy \ --image my-app-image=myregistry.com/my-app:v1.2.3 \ app.py ``` #### Why use reference names? 1. **Decouples code from image URIs** - Change images without modifying code 2. **Supports multiple environments** - Different images for dev/staging/prod 3. **Integrates with CI/CD** - Build images in pipelines, reference in code 4. **Enables image reuse** - Multiple tasks can reference the same image #### Example: Multi-environment deployment ```python import flyte import os # Code references image by name env = flyte.TaskEnvironment( name="api", image=flyte.Image.from_ref_name("api-service") ) @env.task def api_call(endpoint: str) -> dict: # Implementation return {"status": "success"} if __name__ == "__main__": # Determine image based on environment environment = os.getenv("ENV", "dev") image_uri = { "dev": "myregistry.com/api-service:dev", "staging": "myregistry.com/api-service:staging", "prod": "myregistry.com/api-service:v1.2.3" }[environment] # Map the reference name to that image before anything runs flyte.init_from_config(images=(f"api-service={image_uri}",)) # copy_style="none" requires an explicit version; the image tag serves as one run = flyte.with_runcontext( copy_style="none", version=image_uri.rsplit(":", 1)[-1], ).run(api_call, endpoint="/health") ``` ### Container-based best practices 1. **Always set explicit versions** when using `copy_style="none"`: ```python flyte.with_runcontext(copy_style="none", version="v1.0.0") ``` 2. **Match `root_dir` to `copy_contents_only`**: - `copy_contents_only=True` โ†’ `root_dir=Path(__file__).parent` - `copy_contents_only=False` โ†’ `root_dir=Path(__file__).parent.parent` 3. **Ensure `flyte` executable is in container** - Add to PATH or install flyte package 4. **Use `.dockerignore`** to exclude unnecessary files: ``` # .dockerignore __pycache__/ *.pyc .git/ .venv/ *.egg-info/ ``` 5. **Test containers locally** before deploying: ```bash docker run -it myimage:latest /bin/bash python -c "import mymodule" # Verify imports work ``` ### When to use container-based deployment โœ… **Use container-based when:** - Deploying to production - Need immutable, reproducible environments - Working with complex system dependencies - Deploying to air-gapped or restricted environments - CI/CD pipelines with automated builds - Code changes are infrequent โŒ **Don't use container-based when:** - Rapid development and frequent code changes - Quick prototyping - Interactive development (Jupyter notebooks) - Learning and experimentation --- ## Choosing the right approach ### Decision tree ``` Are you iterating quickly on code? โ”œโ”€ Yes โ†’ Use Code Bundling (Default) โ”‚ (Development, prototyping, notebooks) โ”‚ Both approaches are fully reproducible via hash/tag โ””โ”€ No โ†’ Do you need easy version rollback? โ”œโ”€ Yes โ†’ Use Container-based โ”‚ (Production, CI/CD, straightforward tag-based rollback) โ””โ”€ No โ†’ Either works (Code bundling is simpler, container-based for air-gapped) ``` ### Hybrid approach You can use different approaches for different tasks: ```python import flyte import pathlib # Fast iteration for development tasks dev_env = flyte.TaskEnvironment( name="dev", image=flyte.Image.from_debian_base().with_pip_packages("pandas") # Code bundling (default) ) # Immutable containers for production tasks prod_env = flyte.TaskEnvironment( name="prod", image=flyte.Image.from_debian_base() .with_pip_packages("pandas") .with_source_folder(pathlib.Path(__file__).parent, copy_contents_only=True) # Requires copy_style="none" ) @dev_env.task def experimental_task(x: int) -> int: # Rapid development with code bundling return x * 2 @prod_env.task def stable_task(x: int) -> int: # Production with embedded code return x ** 2 if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) # Use code bundling for dev task dev_run = flyte.run(experimental_task, x=5) # Use container-based for prod task prod_run = flyte.with_runcontext( copy_style="none", version="v1.0.0" ).run(stable_task, x=5) ``` --- ## Troubleshooting ### Import errors **Problem:** `ModuleNotFoundError` when task executes remotely **Solutions:** 1. **Check loaded modules** - Ensure modules are imported at module level: ```python # โœ… Good - bundled automatically from mymodule import helper @flyte.task def my_task(): return helper.process() ``` ```python # โŒ Bad - not bundled (lazy load) @flyte.task def my_task(): from mymodule import helper return helper.process() ``` 2. **Verify `root_dir`** matches your import structure: ```python # If imports are: from mypackage.utils import foo # Then root_dir should be parent of mypackage/ flyte.init_from_config(root_dir=pathlib.Path(__file__).parent.parent) ``` 3. **Use `copy_style="all"`** to bundle everything: ```bash flyte run --copy-style=all app.py my_task ``` ### Code changes not reflected **Problem:** On-cluster execution uses old code despite local changes > [!NOTE] > This is rare with code bundling - Flyte automatically versions based on content hash, so code changes should be detected automatically. This issue typically occurs with caching problems, or with `copy_style="none"` when the task's image isn't rebuilt from your source: for example, an image built outside Flyte and referenced with `Image.from_base()` or `Image.from_ref_name()`. **Solutions:** 1. **Use explicit version bump** (with code bundling): ```python run = flyte.with_runcontext(version="v2").run(my_task) ``` 2. **Check if `copy_style="none"`** is set - the code then comes from the image. Source copied into the image is part of the image's content hash, so changing it produces a new image tag and a new build. Changing `version` alone doesn't rebuild the image. If the code was baked into an image built outside Flyte, rebuild that image with the new code, push it under a new tag, and point the task at that tag. ### Files missing in container **Problem:** Task can't find data files or configs **Solutions:** 1. **Use `copy_style="all"`** to bundle all files: ```bash flyte run --copy-style=all app.py my_task ``` 2. **Copy files explicitly in image**: ```python image = flyte.Image.from_debian_base().with_source_file( src=pathlib.Path("config.yaml"), dst="/app/config.yaml" ) ``` 3. **Store data in remote storage** instead of bundling: ```python @flyte.task def my_task(): # Read from S3/GCS instead of local files import flyte.io data = flyte.io.File("s3://bucket/data.csv").open().read() ``` ### Container build failures **Problem:** Image build fails with `copy_style="none"` **Solutions:** 1. **Check `root_dir` matches `copy_contents_only`**: ```python # copy_contents_only=True image = Image.from_debian_base().with_source_folder( src=Path(__file__).parent, copy_contents_only=True ) flyte.init(root_dir=Path(__file__).parent) # Match! ``` 2. **Ensure `flyte` executable available**: ```python image = Image.from_debian_base() # Has flyte pre-installed ``` 3. **Check file permissions** in source directory: ```bash chmod -R +r project/ ``` ### Version conflicts **Problem:** Multiple versions of same image causing confusion **Solutions:** 1. **Use explicit versions**: ```python run = flyte.with_runcontext( copy_style="none", version="v1.2.3" # Explicit, not auto-generated ).run(my_task) ``` 2. **Clean old images**: ```bash docker image prune -a ``` 3. **Use semantic versioning** for clarity: ```python version = "v1.0.0" # Major.Minor.Patch ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/invoke-webhook === Launch deployed tasks over HTTP from an app acting as a webhook. # Running tasks via webhooks On Union, you can deploy apps (see [Apps documentation](../../apps/build-apps/_index)) that can run any deployed Flyte tasks. These apps can be REST API services, like FastAPI, that accept HTTP requests and run tasks on behalf of the caller. A key feature of this approach is **passthrough authentication** - the app can carry forward the identity of the caller and use their credentials to run the task. This ensures proper authorization and audit trails, as tasks are executed with the permissions of the actual user making the request. ## How passthrough authentication works When you deploy a webhook service on Union: 1. The caller sends an HTTP request with their authentication token (typically in the `Authorization` header) 2. Your webhook app extracts the authentication headers from the request 3. The app forwards these headers to the Flyte control plane when running the task 4. The task executes with the caller's identity and permissions This is different from using a service API key, where all tasks would run with the same service account permissions regardless of who made the request. ## Setting up passthrough authentication ### Initialize with `flyte.init_passthrough()` To enable passthrough authentication, initialize your app using `flyte.init_passthrough()`: ```python import flyte # Initialize Flyte with passthrough authentication await flyte.init_passthrough.aio( endpoint="dns:///your-endpoint.hosted.unionai.cloud", project="my-project", # Optional: default project domain="development", # Optional: default domain ) ``` The `init_passthrough()` function configures the Flyte SDK to accept authentication metadata from the request context rather than using a static token or interactive authentication flow. **Parameters:** - `endpoint`: Optional. The Flyte control plane endpoint URL. When running inside a Flyte cluster, it is auto-configured from the injected environment, so you can omit it. Pass it explicitly when running outside a cluster (for example, a locally run webhook app), where it cannot be inferred. - `project`: Optional. Default project to use if not specified per request - `domain`: Optional. Default domain to use if not specified per request - `org`: Optional. Organization name - `insecure`: Optional. Whether to use an insecure connection (default: `False`) > [!NOTE] > When your app runs inside a Flyte cluster, `init_passthrough()` reads the endpoint from the injected environment automatically, so passing `endpoint` is not required. Provide it explicitly only when running outside a cluster, where the endpoint cannot be inferred. ### Passing authentication metadata Once initialized, you need to provide the caller's authentication headers when making requests to the Flyte control plane. There are two approaches: #### Option 1: Using FastAPI middleware (recommended if using fastapi) For FastAPI applications, Flyte provides a convenient middleware that automatically extracts authentication headers from incoming requests and sets them in the Flyte context: ```python from fastapi import FastAPI from flyte.app.extras import FastAPIPassthroughAuthMiddleware app = FastAPI() # Add the middleware - automatically handles auth for all endpoints app.add_middleware( FastAPIPassthroughAuthMiddleware, excluded_paths={"/health"} # Optional: skip auth for specific paths ) @app.post("/run-task") async def run_task(): # No need to manually extract headers! # The middleware automatically sets auth context task = remote.Task.get(project="my-project", domain="development", name="my_task") run = await flyte.run.aio(task, x=42) return {"run_url": run.url} ``` **Middleware features:** - **Automatic header extraction**: Extracts `Authorization` and `Cookie` headers by default - **Path exclusions**: Skip auth for specific endpoints like `/health` or `/metrics` - **Custom extractors**: Add custom header extraction logic - **Thread-safe**: Properly isolates authentication per request using context variables **Middleware parameters:** - `excluded_paths`: Set of URL paths that bypass authentication extraction - `header_extractors`: Custom list of header extractor functions (optional) **Custom header extractors:** ```python from flyte.app.extras import FastAPIPassthroughAuthMiddleware app.add_middleware( FastAPIPassthroughAuthMiddleware, header_extractors=[ FastAPIPassthroughAuthMiddleware.extract_authorization_header, FastAPIPassthroughAuthMiddleware.extract_custom_header("x-api-key"), ], excluded_paths={"/health", "/metrics"}, ) ``` #### Option 2: Using the `auth_metadata()` context manager (any script, web serving framework) The `flyte.remote.auth_metadata()` context manager allows you to explicitly set authentication headers for a block of code: ```python import flyte.remote as remote @app.post("/run-task") async def run_task(request: Request): # Extract authentication from the request auth_header = request.headers.get("authorization") # Use auth_metadata to forward the caller's credentials with remote.auth_metadata(("authorization", auth_header)): # Get and run the task with the caller's identity task = remote.Task.get(project="my-project", domain="development", name="my_task") run = await flyte.run.aio(task, x=42) return {"run_url": run.url} ``` The `auth_metadata()` context manager accepts one or more tuples of `(header_name, header_value)`: ```python with remote.auth_metadata( ("authorization", auth_header), ("cookie", cookie_header), ): # All Flyte API calls within this block use these headers ... ``` ## Complete example Here's a complete FastAPI webhook service that runs Flyte tasks with passthrough authentication: ```python import os from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from starlette import status import flyte import flyte.errors import flyte.remote as remote from flyte.app.extras import FastAPIAppEnvironment, FastAPIPassthroughAuthMiddleware @asynccontextmanager async def lifespan(app: FastAPI): """Initialize Flyte with passthrough auth on startup.""" endpoint = os.getenv("FLYTE_ENDPOINT") if not endpoint: raise RuntimeError("FLYTE_ENDPOINT environment variable not set") await flyte.init_passthrough.aio( endpoint=endpoint, project=os.getenv("FLYTE_INTERNAL_EXECUTION_PROJECT"), domain=os.getenv("FLYTE_INTERNAL_EXECUTION_DOMAIN"), ) yield app = FastAPI( title="Flyte Webhook Runner", description="A webhook service that runs Flyte tasks", lifespan=lifespan, ) # Add passthrough auth middleware app.add_middleware(FastAPIPassthroughAuthMiddleware, excluded_paths={"/health"}) @app.get("/health") async def health_check(): """Health check endpoint (no auth required).""" return {"status": "healthy"} @app.get("/me") async def get_current_user(): """Get information about the authenticated user.""" user = await remote.User.get.aio() return { "subject": user.subject(), "name": user.name(), } @app.post("/run-task/{project}/{domain}/{name}") async def run_task( project: str, domain: str, name: str, inputs: dict, version: str | None = None, ): """ Run a Flyte task with the caller's credentials. Args: project: Flyte project name domain: Flyte domain (e.g., development, staging, production) name: Task name inputs: Dictionary of input parameters for the task version: Task version (optional, defaults to "latest") Returns: Dictionary containing the run information """ try: # Get the task task = remote.Task.get( project=project, domain=domain, name=name, version=version, auto_version="latest" if version is None else None, ) # Run the task with the caller's identity run = await flyte.run.aio(task, **inputs) return {"url": run.url, "name": run.name} except flyte.errors.RemoteTaskNotFoundError: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Task {name} with {version} in {project} and {domain} not found", ) except flyte.errors.RemoteTaskUsageError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e), ) except Exception as e: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e), ) # Configure the app deployment image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn") app_env = FastAPIAppEnvironment( name="webhook-runner", app=app, description="A webhook service that runs Flyte tasks with passthrough auth", image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, # Platform handles auth at gateway env_vars={ "FLYTE_ENDPOINT": "your-endpoint.hosted.unionai.cloud", }, ) ``` For a complete working example, see [`examples/apps/run_webhook.py`](https://github.com/unionai/flyte-sdk/blob/main/examples/apps/run_webhook.py) in the Flyte SDK repository. ## Calling the webhook Once deployed, you can call your webhook using standard HTTP tools: Get your API key: ```bash flyte get api-key my-webhook-key ``` Call the webhook to run a task: ```bash curl -X POST \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"x": 42, "y": "hello"}' \ https://your-app.apps.unionai.cloud/run-task/my-project/development/my_task ``` The task will execute with the permissions associated with the API key used in the request. ## Best practices 1. **Set an endpoint when running outside a cluster**: `init_passthrough()` auto-configures the `endpoint` from the injected environment when running inside a Flyte cluster; pass it explicitly (for example, from `FLYTE_ENDPOINT`) when running outside one 2. **Use middleware for FastAPI**: The `FastAPIPassthroughAuthMiddleware` eliminates boilerplate and ensures consistent auth handling 3. **Exclude public endpoints**: Use `excluded_paths` to skip auth for health checks and public endpoints 4. **Set default project/domain**: If most requests target the same project/domain, set them during initialization to simplify your endpoint handlers 5. **Handle errors gracefully**: Catch `flyte.errors.RemoteTaskNotFoundError` or `flyte.errors.RemoteTaskUsageError` and other exceptions to return appropriate HTTP status codes 6. **Validate inputs**: Always validate task inputs before passing them to `flyte.run()` 7. **Use the caller's identity**: Passthrough auth ensures proper authorization and audit trails - avoid using static service credentials when possible ## Troubleshooting ### "FLYTE_ENDPOINT environment variable not set" Ensure you set the `FLYTE_ENDPOINT` environment variable in your app configuration, or pass it explicitly to `init_passthrough()`. ### "Authentication credentials required" The middleware returns this error when no authentication headers are found. Ensure: - The client includes an `Authorization` header with a valid token - The endpoint is not in the `excluded_paths` set - Header extractors are configured correctly ### "Task not found" Verify: - The task exists in the specified project/domain - The task name is correct (use the fully qualified name: `package.module.task_name`) - The caller has permission to view the task ### Tasks run with wrong permissions If tasks aren't respecting the caller's permissions: - Verify the app initializes with `flyte.init_passthrough()`, which is what enables passthrough authentication - Ensure auth headers are being extracted and forwarded correctly - Check that the middleware is added before route handlers === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/deployment-patterns === Deployment shapes for different project structures and dependency setups. # Deployment patterns Once you understand the basics of task deployment, you can use various deployment patterns to handle different project structures, dependency management approaches, and deployment requirements. This section covers the most common patterns with practical examples. ## Overview of deployment patterns Flyte supports multiple deployment patterns to accommodate different project structures and requirements: 1. ****Tasks > Run and deploy tasks > Deployment patterns > Simple file deployment**** - Single file with tasks and environments 2. ****Tasks > Run and deploy tasks > Deployment patterns > Custom Dockerfile deployment**** - Full control over container environment 3. ****Tasks > Run and deploy tasks > Deployment patterns > PyProject package deployment**** - Structured Python packages with dependencies and async tasks 4. ****Tasks > Run and deploy tasks > Deployment patterns > Package structure deployment**** - Organized packages with shared environments 5. ****Tasks > Run and deploy tasks > Deployment patterns > Full build deployment**** - Complete code embedding in containers 6. ****Tasks > Run and deploy tasks > Deployment patterns > Python path deployment**** - Multi-directory project structures 7. ****Tasks > Run and deploy tasks > Deployment patterns > Dynamic environment deployment**** - Environment selection based on domain context Each pattern serves specific use cases and can be combined as needed for complex projects. ## Simple file deployment The simplest deployment pattern involves defining both your tasks and task environment in a single Python file. This pattern works well for: - Prototyping and experimentation - Simple tasks with minimal dependencies - Educational examples and tutorials ### Example structure ```python import flyte env = flyte.TaskEnvironment(name="simple_env") @env.task async def my_task(name: str) -> str: return f"Hello, {name}!" if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/simple_file.py* ### Deployment commands Deploy the environment: ```bash flyte deploy my_example.py env ``` Run the task ephemerally: ```bash flyte run my_example.py my_task --name "World" ``` ### When to use - Quick prototypes and experiments - Single-purpose scripts - Learning Flyte basics - Tasks with no external dependencies ## Custom Dockerfile deployment When you need full control over the container environment, you can specify a custom Dockerfile. This pattern is ideal for: - Complex system dependencies - Specific OS or runtime requirements - Custom base images - Multi-stage builds ### Example structure ```dockerfile # syntax=docker/dockerfile:1.5 FROM ghcr.io/astral-sh/uv:0.13 as uv FROM python:3.12-slim-bookworm USER root # Copy in uv so that later commands don't have to mount it in COPY --from=uv /uv /usr/bin/uv # Configure default envs ENV UV_COMPILE_BYTECODE=1 \ UV_LINK_MODE=copy \ VIRTUALENV=/opt/venv \ UV_PYTHON=/opt/venv/bin/python \ PATH="/opt/venv/bin:$PATH" # Create a virtualenv with the user specified python version RUN uv venv /opt/venv --python=3.12 WORKDIR /root # Install dependencies COPY requirements.txt . RUN uv pip install --pre -r /root/requirements.txt ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/dockerfile/Dockerfile* ```python from pathlib import Path import flyte env = flyte.TaskEnvironment( name="docker_env", image=flyte.Image.from_dockerfile( # relative paths in python change based on where you call, so set it relative to this file Path(__file__).parent / "Dockerfile", registry="ghcr.io/flyteorg", name="docker_env_image", ), ) @env.task def main(x: int) -> int: return x * 2 if __name__ == "__main__": import flyte.git flyte.init_from_config(flyte.git.config_from_root()) run = flyte.run(main, x=10) print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/dockerfile/dockerfile_env.py* ### Alternative: Dockerfile in different directory You can also reference Dockerfiles from subdirectories: ```python from pathlib import Path import flyte env = flyte.TaskEnvironment( name="docker_env_in_dir", image=flyte.Image.from_dockerfile( # relative paths in python change based on where you call, so set it relative to this file Path(__file__).parent.parent / "Dockerfile.workdir", registry="ghcr.io/flyteorg", name="docker_env_image", ), ) @env.task def main(x: int) -> int: return x * 2 if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, x=10) print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/dockerfile/src/docker_env_in_dir.py* ```dockerfile # syntax=docker/dockerfile:1.5 FROM ghcr.io/astral-sh/uv:0.13 as uv FROM python:3.12-slim-bookworm USER root # Copy in uv so that later commands don't have to mount it in COPY --from=uv /uv /usr/bin/uv # Configure default envs ENV UV_COMPILE_BYTECODE=1 \ UV_LINK_MODE=copy \ VIRTUALENV=/opt/venv \ UV_PYTHON=/opt/venv/bin/python \ PATH="/opt/venv/bin:$PATH" # Create a virtualenv with the user specified python version RUN uv venv /opt/venv --python=3.12 WORKDIR /app # Install dependencies COPY requirements.txt . RUN uv pip install --pre -r /app/requirements.txt ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/dockerfile/Dockerfile.workdir* ### Key considerations - **Path handling**: Use `Path(__file__).parent` for relative Dockerfile paths ```python # relative paths in python change based on where you call, so set it relative to this file Path(__file__).parent / "Dockerfile" ``` - **Registry configuration**: Specify a registry for image storage - **Build context**: The directory containing the Dockerfile becomes the build context - **Flyte installation**: Ensure Flyte is installed in the container and available on `$PATH` ```dockerfile # Install Flyte in your Dockerfile RUN pip install flyte ``` - **Dependencies**: Include all application requirements in the Dockerfile or requirements.txt ### When to use - Need specific system packages or tools - Custom base image requirements - Complex installation procedures - Multi-stage build optimization ## PyProject package deployment For structured Python projects with proper package management, use the PyProject pattern. This approach demonstrates a **realistic Python project structure** that provides: - Proper dependency management with `pyproject.toml` and external packages like `httpx` - Clean separation of business logic and Flyte tasks across multiple modules - Professional project structure with `src/` layout - Async task execution with API calls and data processing - Entrypoint patterns for both command-line and programmatic execution ### Example structure ``` pyproject_package/ โ”œโ”€โ”€ pyproject.toml # Project metadata and dependencies โ”œโ”€โ”€ README.md # Documentation โ””โ”€โ”€ src/ โ””โ”€โ”€ pyproject_package/ โ”œโ”€โ”€ __init__.py # Package initialization โ”œโ”€โ”€ main.py # Entrypoint script โ”œโ”€โ”€ data/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ”œโ”€โ”€ loader.py # Data loading utilities (no Flyte) โ”‚ โ””โ”€โ”€ processor.py # Data processing utilities (no Flyte) โ”œโ”€โ”€ models/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ””โ”€โ”€ analyzer.py # Analysis utilities (no Flyte) โ””โ”€โ”€ tasks/ โ”œโ”€โ”€ __init__.py โ””โ”€โ”€ tasks.py # Flyte task definitions ``` ### Business logic modules The business logic is completely separate from Flyte and can be used independently: #### Data loading (`data/loader.py`) ```python import json from pathlib import Path from typing import Any import httpx async def fetch_data_from_api(url: str) -> list[dict[str, Any]]: async with httpx.AsyncClient() as client: response = await client.get(url, timeout=10.0) response.raise_for_status() return response.json() def load_local_data(file_path: str | Path) -> dict[str, Any]: path = Path(file_path) if not path.exists(): raise FileNotFoundError(f"File not found: {file_path}") with path.open("r") as f: return json.load(f) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/pyproject_package/src/pyproject_package/data/loader.py* #### Data processing (`data/processor.py`) ```python import asyncio from typing import Any from pydantic import BaseModel, Field, field_validator class DataItem(BaseModel): id: int = Field(gt=0, description="Item ID must be positive") value: float = Field(description="Item value") category: str = Field(min_length=1, description="Item category") @field_validator("category") @classmethod def category_must_be_lowercase(cls, v: str) -> str: return v.lower() def clean_data(raw_data: dict[str, Any]) -> dict[str, Any]: # Remove None values cleaned = {k: v for k, v in raw_data.items() if v is not None} # Validate items if present if "items" in cleaned: validated_items = [] for item in cleaned["items"]: try: validated = DataItem(**item) validated_items.append(validated.model_dump()) except Exception as e: print(f"Skipping invalid item {item}: {e}") continue cleaned["items"] = validated_items return cleaned def transform_data(data: dict[str, Any]) -> list[dict[str, Any]]: items = data.get("items", []) # Add computed fields transformed = [] for item in items: transformed_item = { **item, "value_squared": item["value"] ** 2, "category_upper": item["category"].upper(), } transformed.append(transformed_item) return transformed async def aggregate_data(items: list[dict[str, Any]]) -> dict[str, Any]: # Simulate async processing await asyncio.sleep(0.1) aggregated: dict[str, dict[str, Any]] = {} for item in items: category = item["category"] if category not in aggregated: aggregated[category] = { "count": 0, "total_value": 0.0, "values": [], } aggregated[category]["count"] += 1 aggregated[category]["total_value"] += item["value"] aggregated[category]["values"].append(item["value"]) # Calculate averages for category, v in aggregated.items(): total = v["total_value"] count = v["count"] v["average_value"] = total / count if count > 0 else 0.0 return {"categories": aggregated, "total_items": len(items)} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/pyproject_package/src/pyproject_package/data/processor.py* #### Analysis (`models/analyzer.py`) ```python from typing import Any import numpy as np def calculate_statistics(data: list[dict[str, Any]]) -> dict[str, Any]: if not data: return { "count": 0, "mean": 0.0, "median": 0.0, "std_dev": 0.0, "min": 0.0, "max": 0.0, } values = np.array([item["value"] for item in data]) stats = { "count": len(values), "mean": float(np.mean(values)), "median": float(np.median(values)), "std_dev": float(np.std(values)), "min": float(np.min(values)), "max": float(np.max(values)), "percentile_25": float(np.percentile(values, 25)), "percentile_75": float(np.percentile(values, 75)), } return stats def generate_report(stats: dict[str, Any]) -> str: report_lines = [ "=" * 60, "DATA ANALYSIS REPORT", "=" * 60, ] # Basic statistics section if "basic" in stats: basic = stats["basic"] report_lines.extend( [ "", "BASIC STATISTICS:", f" Count: {basic.get('count', 0)}", f" Mean: {basic.get('mean', 0.0):.2f}", f" Median: {basic.get('median', 0.0):.2f}", f" Std Dev: {basic.get('std_dev', 0.0):.2f}", f" Min: {basic.get('min', 0.0):.2f}", f" Max: {basic.get('max', 0.0):.2f}", f" 25th %ile: {basic.get('percentile_25', 0.0):.2f}", f" 75th %ile: {basic.get('percentile_75', 0.0):.2f}", ] ) # Category aggregations section if "aggregated" in stats and "categories" in stats["aggregated"]: categories = stats["aggregated"]["categories"] total_items = stats["aggregated"].get("total_items", 0) report_lines.extend( [ "", "CATEGORY BREAKDOWN:", f" Total Items: {total_items}", "", ] ) for category, cat_stats in sorted(categories.items()): report_lines.extend( [ f" Category: {category.upper()}", f" Count: {cat_stats.get('count', 0)}", f" Total Value: {cat_stats.get('total_value', 0.0):.2f}", f" Average Value: {cat_stats.get('average_value', 0.0):.2f}", "", ] ) report_lines.append("=" * 60) return "\n".join(report_lines) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/pyproject_package/src/pyproject_package/models/analyzer.py* These modules demonstrate: - **No Flyte dependencies** - can be tested and used independently - **Pydantic models** for data validation with custom validators - **Async patterns** with proper context managers and error handling - **NumPy integration** for statistical calculations - **Professional error handling** with timeouts and validation ### Flyte orchestration layer The Flyte tasks orchestrate the business logic with proper async execution: ```python import pathlib from typing import Any import flyte from pyproject_package.data import loader, processor from pyproject_package.models import analyzer UV_PROJECT_ROOT = pathlib.Path(__file__).parent.parent.parent.parent env = flyte.TaskEnvironment( name="data_pipeline", image=flyte.Image.from_debian_base().with_uv_project(pyproject_file=UV_PROJECT_ROOT / "pyproject.toml"), resources=flyte.Resources(memory="512Mi", cpu="500m"), ) @env.task async def fetch_task(url: str) -> list[dict[str, Any]]: print(f"Fetching data from: {url}") data = await loader.fetch_data_from_api(url) print(f"Fetched {len(data)} top-level keys") return data @env.task async def process_task(raw_data: dict[str, Any]) -> list[dict[str, Any]]: print("Cleaning data...") cleaned = processor.clean_data(raw_data) print("Transforming data...") transformed = processor.transform_data(cleaned) print(f"Processed {len(transformed)} items") return transformed @env.task async def analyze_task(processed_data: list[dict[str, Any]]) -> str: print("Aggregating data...") aggregated = await processor.aggregate_data(processed_data) print("Calculating statistics...") stats = analyzer.calculate_statistics(processed_data) print("Generating report...") report = analyzer.generate_report({"basic": stats, "aggregated": aggregated}) print("\n" + report) return report @env.task async def pipeline(api_url: str) -> str: # Chain tasks together raw_data = await fetch_task(url=api_url) processed_data = await process_task(raw_data=raw_data[0]) report = await analyze_task(processed_data=processed_data) return report ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/pyproject_package/src/pyproject_package/tasks/tasks.py* ### Entrypoint configuration The main entrypoint demonstrates proper initialization and execution patterns: ```python import pathlib import flyte from pyproject_package.tasks.tasks import pipeline def main(): # Initialize Flyte connection flyte.init_from_config(root_dir=pathlib.Path(__file__).parent.parent) # Example API URL with mock data # In a real scenario, this would be a real API endpoint example_url = "https://jsonplaceholder.typicode.com/posts" # For demonstration, we'll use mock data instead of the actual API # to ensure the example works reliably print("Starting data pipeline...") print(f"Target API: {example_url}") # To run remotely, uncomment the following: run = flyte.run(pipeline, api_url=example_url) print(f"\nRun Name: {run.name}") print(f"Run URL: {run.url}") run.wait() if __name__ == "__main__": main() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/pyproject_package/src/pyproject_package/main.py* ### Dependencies and configuration ```toml [project] name = "pyproject-package" version = "0.1.0" description = "Example Python package with Flyte tasks and modular business logic" readme = "README.md" authors = [ { name = "Ketan Umare", email = "kumare3@users.noreply.github.com" } ] requires-python = ">=3.10" dependencies = [ "flyte>=2.0.0b52", "httpx>=0.27.0", "numpy>=1.26.0", "pydantic>=2.0.0", ] [project.scripts] run-pipeline = "pyproject_package.main:main" [build-system] requires = ["hatchling"] build-backend = "hatchling.build" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/pyproject_package/pyproject.toml* ### Key features - **Async task chains**: Tasks can be chained together with proper async/await patterns - **External dependencies**: Demonstrates integration with external libraries (`httpx`, `pyyaml`) - **uv integration**: Uses `.with_uv_project()` for dependency management - **Resource specification**: Shows how to set memory and CPU requirements - **Proper error handling**: Includes timeout and error handling in API calls ### Key learning points 1. **Separation of concerns**: Business logic (`data/`, `models/`) separate from orchestration (`main.py`) 2. **Reusable code**: Non-Flyte modules can be tested independently and reused 3. **Async support**: Demonstrates async Flyte tasks for I/O-bound operations 4. **Dependency management**: Shows how external packages integrate with Flyte 5. **Realistic structure**: Mirrors real-world Python project organization 6. **Entrypoint script**: Shows how to create runnable entry points ### Usage patterns **Run locally:** ```bash python -m pyproject_package.main ``` **Deploy to Flyte:** ```bash flyte deploy . ``` **Run remotely:** ```bash python -m pyproject_package.main # Uses remote execution ``` ### What this example demonstrates - Multiple files and modules in a package - Async Flyte tasks with external API calls - Separation of business logic from orchestration - External dependencies (`httpx`, `numpy`, `pydantic`) - **Data validation with Pydantic models** for data processing - **Professional error handling** with try/catch for data validation - **Timeout configuration** for external API calls (`timeout=10.0`) - **Async context managers** for proper resource management (`async with httpx.AsyncClient()`) - Entrypoint script pattern with `project.scripts` - Realistic project structure with `src/` layout - Task chaining and data flow - How non-Flyte code integrates with Flyte tasks ### When to use - Production-ready, maintainable projects - Projects requiring external API integration - Complex data processing pipelines - Team development with proper separation of concerns - Applications needing async execution patterns ## Package structure deployment For organizing Flyte workflows in a package structure with shared task environments and utilities, use this pattern. It's particularly useful for: - Multiple workflows that share common environments and utilities - Organized code structure with clear module boundaries - Projects where you want to reuse task environments across workflows ### Example structure ``` lib/ โ”œโ”€โ”€ __init__.py โ””โ”€โ”€ workflows/ โ”œโ”€โ”€ __init__.py โ”œโ”€โ”€ workflow1.py # First workflow โ”œโ”€โ”€ workflow2.py # Second workflow โ”œโ”€โ”€ env.py # Shared task environment โ””โ”€โ”€ utils.py # Shared utilities ``` ### Key concepts - **Shared environments**: Define task environments in `env.py` and import across workflows - **Utility modules**: Common functions and utilities shared between workflows - **Root directory handling**: Use `--root-dir` flag for proper Python path configuration ### Running with root directory When running workflows with a package structure, specify the root directory: ```bash flyte run --root-dir . lib/workflows/workflow1.py process_workflow flyte run --root-dir . lib/workflows/workflow2.py math_workflow --n 6 ``` ### How `--root-dir` works The `--root-dir` flag automatically configures the Python path (`sys.path`) to ensure: 1. **Local execution**: Package imports work correctly when running locally 2. **Consistent behavior**: Same Python path configuration locally and at runtime 3. **No manual PYTHONPATH**: Eliminates need to manually export environment variables 4. **Runtime packaging**: Flyte packages and copies code correctly to execution environment 5. **Runtime consistency**: The same package structure is preserved in the runtime container ### Alternative: Using a Python project For larger projects, create a proper Python project with `pyproject.toml`: ```toml # pyproject.toml [project] name = "lib" version = "0.1.0" [build-system] requires = ["setuptools>=45", "wheel"] build-backend = "setuptools.build_meta" ``` Then install in editable mode: ```bash pip install -e . ``` After installation, you can run workflows without `--root-dir`: ```bash flyte run lib/workflows/workflow1.py process_workflow ``` However, for deployment and on-cluster execution, still use `--root-dir` for consistency: ```bash flyte run --root-dir . lib/workflows/workflow1.py process_workflow flyte deploy --root-dir . lib/workflows/workflow1.py ``` ### When to use - Multiple related workflows in one project - Shared task environments and utilities - Team projects with multiple contributors - Applications requiring organized code structure - Projects that benefit from proper Python packaging ## Full build deployment When you need complete reproducibility and want to embed all code directly in the container image, use the full build pattern. This disables Flyte's fast deployment system in favor of traditional container builds. ### Overview By default, Flyte uses a fast deployment system that: - Creates a tar archive of your files - Skips the full image build and push process - Provides faster iteration during development However, sometimes you need to **completely embed your code into the container image** for: - Full reproducibility with immutable container images - Environments where fast deployment isn't available - Production deployments with all dependencies baked in - Air-gapped or restricted deployment environments ### Key configuration ```python import pathlib from dep import foo import flyte env = flyte.TaskEnvironment( name="full_build", image=flyte.Image.from_debian_base().with_source_folder( pathlib.Path(__file__).parent, copy_contents_only=True # Avoid nested folders ), ) @env.task def square(x) -> int: return x ** foo() @env.task def main(n: int) -> list[int]: return list(flyte.map(square, range(n))) if __name__ == "__main__": # copy_contents_only=True requires root_dir=parent, False requires root_dir=parent.parent flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.with_runcontext(copy_style="none", version="x").run(main, n=10) print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/full_build/main.py* ### Local dependency example The main.py file imports from a local dependency that gets included in the build: ```python def foo() -> int: return 1 ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/full_build/dep.py* ### Critical configuration components 1. **Set `copy_style` to `"none"`**: ```python flyte.with_runcontext(copy_style="none", version="x").run(main, n=10) ``` This disables Flyte's fast deployment system and forces a full container build. 2. **Set a custom version**: ```python flyte.with_runcontext(copy_style="none", version="x").run(main, n=10) ``` The `version` parameter should be set to a desired value (not auto-generated) for consistent image tagging. 3. **Configure image source copying**: ```python image=flyte.Image.from_debian_base().with_source_folder( pathlib.Path(__file__).parent, copy_contents_only=True ) ``` Use `.with_source_folder()` to specify what code to copy into the container. 4. **Set `root_dir` correctly**: ```python flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) ``` - If `copy_contents_only=True`: Set `root_dir` to the source folder (contents are copied) - If `copy_contents_only=False`: Set `root_dir` to parent directory (folder is copied) ### Configuration options #### Option A: Copy folder structure ```python # Copies the entire folder structure into the container image=flyte.Image.from_debian_base().with_source_folder( pathlib.Path(__file__).parent, copy_contents_only=False # Default ) # When copy_contents_only=False, set root_dir to parent.parent flyte.init_from_config(root_dir=pathlib.Path(__file__).parent.parent) ``` #### Option B: Copy contents only (recommended) ```python # Copies only the contents of the folder (flattens structure) # This is useful when you want to avoid nested folders - for example all your code is in the root of the repo image=flyte.Image.from_debian_base().with_source_folder( pathlib.Path(__file__).parent, copy_contents_only=True ) # When copy_contents_only=True, set root_dir to parent flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) ``` ### Version management best practices When using `copy_style="none"`, always specify an explicit version: - Use semantic versioning: `"v1.0.0"`, `"v1.1.0"` - Use build numbers: `"build-123"` - Use git commits: `"abc123"` Avoid auto-generated versions to ensure reproducible deployments. ### Performance considerations - **Full builds take longer** than fast deployment - **Container images will be larger** as they include all source code - **Better for production** where immutability is important - **Use during development** when testing the full deployment pipeline ### When to use โœ… **Use full build when:** - Deploying to production environments - Need immutable, reproducible container images - Working with complex dependency structures - Deploying to air-gapped or restricted environments - Building CI/CD pipelines โŒ **Don't use full build when:** - Rapid development and iteration - Working with frequently changing code - Development environments where speed matters - Simple workflows without complex dependencies ### Troubleshooting **Common issues:** 1. **Import errors**: Check your `root_dir` configuration matches `copy_contents_only` 2. **Missing files**: Ensure all dependencies are in the source folder 3. **Version conflicts**: Use explicit, unique version strings 4. **Build failures**: Check that the base image has all required system dependencies **Debug tips:** - Add print statements to verify file paths in containers - Use `docker run -it /bin/bash` to inspect built images - Check Flyte logs for build errors and warnings - Verify that relative imports work correctly in the container context ## Python path deployment For projects where workflows are separated from business logic across multiple directories, use the Python path pattern with proper `root_dir` configuration. ### Example structure ``` pythonpath/ โ”œโ”€โ”€ workflows/ โ”‚ โ””โ”€โ”€ workflow.py # Flyte workflow definitions โ”œโ”€โ”€ src/ โ”‚ โ””โ”€โ”€ my_module.py # Business logic modules โ”œโ”€โ”€ run.sh # Execute from project root โ””โ”€โ”€ run_inside_folder.sh # Execute from workflows/ directory ``` ### Implementation ```python import pathlib from src.my_module import env, say_hello import flyte env = flyte.TaskEnvironment( name="workflow_env", depends_on=[env], ) @env.task async def greet(name: str) -> str: return await say_hello(name) if __name__ == "__main__": current_dir = pathlib.Path(__file__).parent flyte.init_from_config(root_dir=current_dir.parent) r = flyte.run(greet, name="World") print(r.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/pythonpath/workflows/workflow.py* ```python import flyte env = flyte.TaskEnvironment( name="my_module", ) @env.task async def say_hello(name: str) -> str: return f"Hello, {name}!" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/pythonpath/src/my_module.py* ### Task environment dependencies Note how the workflow imports both the task environment and the task function: ```python from src.my_module import env, say_hello env = flyte.TaskEnvironment( name="workflow_env", depends_on=[env], # Depends on the imported environment ) ``` This pattern allows sharing task environments across modules while maintaining proper dependency relationships. ### Key considerations - **Import resolution**: `root_dir` enables proper module imports across directories - **File packaging**: Flyte packages all files starting from `root_dir` - **Execution flexibility**: Works regardless of where you execute the script - **PYTHONPATH handling**: Different behavior for CLI vs direct Python execution ### CLI vs direct Python execution #### Using Flyte CLI with `--root-dir` (Recommended) When using `flyte run` with `--root-dir`, you don't need to export PYTHONPATH: ```bash flyte run --root-dir . workflows/workflow.py greet --name "World" ``` The CLI automatically: - Adds the `--root-dir` location to `sys.path` - Resolves all imports correctly - Packages files from the root directory for on-cluster execution #### Using Python directly When running Python scripts directly, you must set PYTHONPATH manually: ```bash PYTHONPATH=.:$PYTHONPATH python workflows/workflow.py ``` This is because: - Python doesn't automatically know about your project structure - You need to explicitly tell Python where to find your modules - The `root_dir` parameter handles remote packaging, not local path resolution ### Best practices 1. **Always set `root_dir`** when workflows import from multiple directories 2. **Use pathlib** for cross-platform path handling 3. **Set `root_dir` to your project root** to ensure all dependencies are captured 4. **Test both execution patterns** to ensure deployment works from any directory ### Common pitfalls - **Forgetting `root_dir`**: Results in import errors during on-cluster execution - **Wrong `root_dir` path**: May package too many or too few files - **Not setting PYTHONPATH when using Python directly**: Use `flyte run --root-dir .` instead - **Mixing execution methods**: If you use `flyte run --root-dir .`, you don't need PYTHONPATH ### When to use - Legacy projects with established directory structures - Separation of concerns between workflows and business logic - Multiple workflow definitions sharing common modules - Projects with complex import hierarchies **Note:** This pattern is an escape hatch for larger projects where code organization requires separating workflows from business logic. Ideally, structure projects with `pyproject.toml` for cleaner dependency management. ## Dynamic environment deployment For environments that need to change based on deployment context (development vs production), use dynamic environment selection based on Flyte domains. ### Domain-based environment selection Use `flyte.current_domain()` to deterministically create different task environments based on the deployment domain: ```python # NOTE: flyte.init() invocation at the module level is strictly discouraged. # At runtime, Flyte controls initialization and configuration files are not present. import os import flyte def create_env(): if flyte.current_domain() == "development": return flyte.TaskEnvironment(name="dev", image=flyte.Image.from_debian_base(), env_vars={"MY_ENV": "dev"}) return flyte.TaskEnvironment(name="prod", image=flyte.Image.from_debian_base(), env_vars={"MY_ENV": "prod"}) env = create_env() @env.task async def my_task(n: int) -> int: print(f"Environment Variable MY_ENV = {os.environ['MY_ENV']}", flush=True) return n + 1 @env.task async def entrypoint(n: int) -> int: print(f"Environment Variable MY_ENV = {os.environ['MY_ENV']}", flush=True) return await my_task(n) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/dynamic_environments/environment_picker.py* ### Why this pattern works **Environment reproducibility in local and remote clusters is critical.** Flyte re-instantiates modules in remote clusters, so `current_domain()` will be set correctly based on where the code executes. โœ… **Do use `flyte.current_domain()`** - Flyte automatically sets this based on the execution context โŒ **Don't use environment variables directly** - They won't yield correct results unless manually passed to the downstream system ### How it works 1. Flyte sets the domain context when initializing 2. `current_domain()` returns the domain string (e.g., "development", "staging", "production") 3. Your code deterministically configures resources based on this domain 4. When Flyte executes remotely, it re-instantiates modules with the correct domain context 5. The same environment configuration logic runs consistently everywhere ### Important constraints `flyte.current_domain()` only works **after** `flyte.init()` is called: - โœ… Works with `flyte run` and `flyte deploy` CLI commands (they init automatically) - โœ… Works when called from `if __name__ == "__main__"` after explicit `flyte.init()` - โŒ Does NOT work at module level without initialization **Critical:** `flyte.init()` invocation at the module level is **strictly discouraged**. The reason is that at runtime, Flyte controls the initialization and configuration files are not present at runtime. ### Alternative: environment variable approach For cases where you need to pass domain information as environment variables to the container runtime, use this approach: ```python import os import flyte def create_env(domain: str): # Pass domain as environment variable so tasks can see which domain they're running in if domain == "development": return flyte.TaskEnvironment(name="dev", image=flyte.Image.from_debian_base(), env_vars={"DOMAIN_NAME": domain}) return flyte.TaskEnvironment(name="prod", image=flyte.Image.from_debian_base(), env_vars={"DOMAIN_NAME": domain}) env = create_env(os.getenv("DOMAIN_NAME", "development")) @env.task async def my_task(n: int) -> int: print(f"Environment Variable MY_ENV = {os.environ['DOMAIN_NAME']}", flush=True) return n + 1 @env.task async def entrypoint(n: int) -> int: print(f"Environment Variable MY_ENV = {os.environ['DOMAIN_NAME']}", flush=True) return await my_task(n) if __name__ == "__main__": flyte.init_from_config() r = flyte.run(entrypoint, n=5) print(r.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/dynamic_environments_with_envvars/environment_picker.py* #### Key differences from domain-based approach - **Environment variable access**: The domain name is available inside tasks via `os.environ['DOMAIN_NAME']` - **External control**: Can be controlled via system environment variables before execution - **Runtime visibility**: Tasks can inspect which environment they're running in during execution - **Default fallback**: Uses `"development"` as default when `DOMAIN_NAME` is not set #### Usage with environment variables Set the environment variable and run: ```bash export DOMAIN_NAME=production flyte run environment_picker.py entrypoint --n 5 ``` Or set it inline: ```bash DOMAIN_NAME=development flyte run environment_picker.py entrypoint --n 5 ``` #### When to use environment variables vs domain-based **Use environment variables when:** - Tasks need runtime access to environment information - External systems set environment configuration - You need flexibility to override environment externally - Debugging requires visibility into environment selection **Use domain-based approach when:** - Environment selection should be automatic based on Flyte domain - You want tighter integration with Flyte's domain system - No need for runtime environment inspection within tasks You can vary multiple aspects based on context: - **Base images**: Different images for dev vs prod - **Environment variables**: Configuration per environment - **Resource requirements**: Different CPU/memory per domain - **Dependencies**: Different package versions - **Registry settings**: Different container registries ### Usage patterns ```bash flyte run environment_picker.py entrypoint --n 5 flyte deploy environment_picker.py ``` For programmatic usage, ensure proper initialization: ```python import flyte flyte.init_from_config() from environment_picker import entrypoint if __name__ == "__main__": r = flyte.run(entrypoint, n=5) print(r.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/deployment-patterns/dynamic_environments/main.py* ### When to use dynamic environments **General use cases:** - Multi-environment deployments (dev/staging/prod) - Different resource requirements per environment - Environment-specific dependencies or settings - Context-sensitive configuration needs **Domain-based approach for:** - Automatic environment selection tied to Flyte domains - Simpler configuration without external environment variables - Integration with Flyte's built-in domain system **Environment variable approach for:** - Runtime visibility into environment selection within tasks - External control over environment configuration - Debugging and logging environment-specific behavior - Integration with external deployment systems that set environment variables ## Dependency and version management Flyte declares its dependencies with loose version ranges so that installing `flyte` doesn't over-constrain the rest of your project. The downside is that a new release of a transitive dependency can sometimes introduce a regression in an environment that isn't otherwise pinned. To get reproducible installs, pin your dependency versions using one of the approaches below. Both are optional. Neither changes how a plain `pip install flyte` behaves. ### Recommended: use a lockfile If you manage your project with `uv` (or any tool that produces a lockfile), commit the lockfile and install from it: ```bash uv add flyte # resolves and records exact versions in uv.lock uv sync --frozen # installs exactly what uv.lock specifies, no re-resolution ``` Commit `uv.lock` to version control. A lockfile records the exact version of every direct and transitive dependency, so every install resolves to the same versions locally, in CI, and in your Flyte task images. When you build task images with `.with_uv_project()` (see **Tasks > Run and deploy tasks > Deployment patterns > PyProject package deployment**), the image is built from the locked environment, so what you test is what runs remotely. ### No lockfile? Install against Flyte's published constraints If you don't use a lockfile tool, Flyte publishes a constraints file with every release. It lists the exact transitive dependency versions that release was tested against. Pass it to your installer with `-c`: ```bash # Pin to the versions tested for a specific release pip install "flyte==" \ -c "https://github.com/flyteorg/flyte-sdk/releases/download/v/constraints-.txt" # Or always track the latest release's constraints pip install flyte \ -c "https://github.com/flyteorg/flyte-sdk/releases/latest/download/constraints.txt" ``` `uv pip install` accepts the same `-c` flag. A constraints file only pins the versions of packages that get installed. It never pulls a package into your environment on its own, and using it is optional. It gives you Flyte's tested dependency set without adopting a lockfile. ### Choosing an approach | Approach | Reproducibility | Best for | |----------|-----------------|----------| | Lockfile (`uv.lock`) | Full. Every dependency pinned in your own repo | Projects already using `uv` or another lockfile tool | | Published constraints (`-c`) | Pinned to Flyte's per-release tested versions | Projects that can't or don't want to maintain a lockfile | | Default ranges (no pinning) | None | Quick prototypes and experiments | ## Best practices ### Project organization 1. **Separate concerns**: Keep business logic separate from Flyte task definitions 2. **Use proper imports**: Structure projects for clean import patterns 3. **Version control**: Include all necessary files in version control 4. **Documentation**: Document deployment requirements and patterns ### Image management 1. **Registry configuration**: Use consistent registry settings across environments 2. **Image tagging**: Use meaningful tags for production deployments 3. **Base image selection**: Choose appropriate base images for your needs 4. **Dependency management**: Keep container images lightweight but complete ### Configuration management 1. **Root directory**: Set `root_dir` appropriately for your project structure 2. **Path handling**: Use `pathlib.Path` for cross-platform compatibility 3. **Environment variables**: Use environment-specific configurations 4. **Secrets management**: Handle sensitive data appropriately ### Development workflow 1. **Local testing**: Test tasks locally before deployment 2. **Incremental development**: Use `flyte run` for quick iterations 3. **Production deployment**: Use `flyte deploy` for permanent deployments 4. **Monitoring**: Monitor deployed tasks and environments ## Choosing the right pattern | Pattern | Use Case | Complexity | Best For | |---------|----------|------------|----------| | Simple file | Quick prototypes, learning | Low | Single tasks, experiments | | Custom Dockerfile | System dependencies, custom environments | Medium | Complex dependencies | | PyProject package | Professional projects, async pipelines | Medium-High | Production applications | | Package structure | Multiple workflows, shared utilities | Medium | Organized team projects | | Full build | Production, reproducibility | High | Immutable deployments | | Python path | Legacy structures, separated concerns | Medium | Existing codebases | | Dynamic environment | Multi-environment, domain-aware deployments | Medium | Context-aware deployments | Start with simpler patterns and evolve to more complex ones as your requirements grow. Many projects will combine multiple patterns as they scale and mature. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/run-context === Set where a run executes, where its outputs go, and how caching behaves. # Run context Every Flyte run has a **run context**: a set of invocation-time parameters that control where the run executes, where its outputs are stored, how caching behaves, and more. There are two sides to run context: - **Write side**: `flyte.with_runcontext()` sets run parameters before the run starts (programmatic) or via CLI flags. - **Read side**: `flyte.ctx()` accesses run parameters inside a running task. ## Configuring a run with `flyte.with_runcontext()` `flyte.with_runcontext()` returns a runner object. Call `.run(task, ...)` on it to start the run with the specified context: ``` import flyte env = flyte.TaskEnvironment("run-context-example") @env.task async def process(n: int) -> int: return n * 2 @env.task async def root() -> int: return await process(21) if __name__ == "__main__": flyte.init_from_config() flyte.with_runcontext( name="my-run", project="my-project", domain="development", ).run(root) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/run-context/run_context.py* All parameters are optional. Unset parameters inherit from the configuration file (`config.yaml`) or system defaults. ### Execution target | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `mode` | `"local"` \| `"remote"` | *from config* | Where the run executes. `"remote"` runs on the Flyte backend your config points at, whether a devbox or a deployed cluster; `"local"` runs in-process. | | `project` | `str` | *from config* | Project to run in. | | `domain` | `str` | *from config* | Domain to run in (e.g. `"development"`, `"production"`). | | `name` | `str` | *auto-generated* | Custom name for the run, visible in the UI. | | `version` | `str` | *from code bundle* | Version string for the ephemeral task deployment. | | `queue` | `str` | *from config* | Cluster queue to schedule tasks on. | | `interruptible` | `bool` | *per-task setting* | Override the interruptible setting for all tasks in the run. `True` allows spot/preemptible instances; `False` forces non-interruptible instances. | > [!NOTE] > `with_runcontext()` also accepts a `debug` parameter (`bool`, default `False`): launch the run in debug mode, starting a browser-based VS Code session on the task pod so you can step through the task interactively. See **Tasks > Run and deploy tasks > Debug a run**. ### Storage | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `raw_data_path` | `str` | *from config* | Storage prefix for offloaded data types (**Tasks > Build tasks > Files and directories**, **Tasks > Build tasks > Files and directories**, **Tasks > Build tasks > DataFrames**, checkpoints). Accepts local paths and any remote scheme the storage layer resolves: `s3://`, `gs://`, `abfs://` and `abfss://` natively, plus any other scheme `fsspec` has a filesystem for (such as `hf://`). | | `run_base_dir` | `str` | *auto-generated* | Base directory for the run's inputs, outputs, and intermediate per-action artifacts in the data plane object store. Distinct from `raw_data_path`. | For the difference between what `raw_data_path` controls (offloaded values) and what stays at the deployment-configured location (`inputs.pb`, `outputs.pb`, Decks) or in the control plane database, see **Get started > Core concepts > Where your data lives**. To direct all task outputs to a specific bucket for a run: ``` if __name__ == "__main__": flyte.init_from_config() flyte.with_runcontext( # Store all task outputs in a dedicated S3 prefix for this run raw_data_path="s3://my-bucket/runs/experiment-42/", ).run(root) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/run-context/run_context.py* The equivalent CLI flag is `--raw-data-path`. See **Tasks > Run and deploy tasks > Run command options > `--raw-data-path`** for CLI usage. ### Caching | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `overwrite_cache` | `bool` | `False` | Re-execute all tasks even if a cached result exists, and overwrite the cache with new results. | | `disable_run_cache` | `bool` | `False` | In local runs, skip task cache lookups and writes entirely. As of flyte 2.12, remote runs don't send this setting to the backend, so cached task results are still used. | | `cache_lookup_scope` | `"global"` \| ... | `"global"` | Scope for cache lookups. | ### Identity and resources | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `service_account` | `str` | *from config* | Kubernetes service account for task pods. | | `env_vars` | `Dict[str, str]` | `None` | Additional environment variables to inject into task containers. | | `labels` | `Dict[str, str]` | `None` | User-defined `key=value` labels attached to the run โ€” used to filter/organize runs (`flyte get run --with-label`) and propagated to the task pods as Kubernetes labels. | | `annotations` | `Dict[str, str]` | `None` | User-defined `key=value` annotations attached to the run and propagated to the task pods as Kubernetes annotations (not filterable; no CLI flag). | Labels tag a run with arbitrary `key=value` metadata so you can find and group related runs later, and are also propagated to the run's task pods as Kubernetes labels (available for cluster-level monitoring, routing, or policies). Set them programmatically with `with_runcontext(labels={...})`, or from the CLI with the repeatable `--label` flag: ```bash flyte run --label team=ml --label env=prod my_example.py main ``` To list and filter runs by their labels, see **Tasks > Run and deploy tasks > Interact with runs and actions > Filtering runs by label**. ### Logging | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `log_level` | `int` | *from config* | Python log level for the framework logger (`flyte`), e.g. `logging.DEBUG`. | | `user_log_level` | `int` | *from config* | Python log level for the user logger (`flyte.user`, i.e. `flyte.logger`). | | `log_format` | `"console"` \| `"json"` | `"console"` | Log output format. | | `reset_root_logger` | `bool` | `False` | If `True`, clear the root logger's existing handlers and install Flyte's own; with `flyte` 2.12.5 or later, Python warnings are also routed through Flyte's root handler. If `False` (the default), leave existing root handlers in place and wrap their formatters with the run/action context. | For setting the logging level (including via environment variables), the framework-vs-user logger split, and capturing third-party library logs as JSON with `reset_root_logger`, see **Tasks > Configure tasks > Logging**. ### Code bundling | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `copy_style` | `"loaded_modules"` \| `"all"` \| `"none"` | `"loaded_modules"` | Code bundling strategy. See **Tasks > Run and deploy tasks > Run command options > `--copy-style`**. | | `dry_run` | `bool` | `False` | Build and upload the code bundle without executing the run. | | `copy_bundle_to` | `Path` | `None` | When `dry_run=True`, copy the bundle to this local path. | | `interactive_mode` | `bool` | *auto-detected* | Override interactive mode detection (set automatically for Jupyter notebooks). | | `preserve_original_types` | `bool` | `False` | Keep native DataFrame types (e.g. `pd.DataFrame`) rather than converting to `flyte.io.DataFrame` when deserializing outputs. | ### Context propagation | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `custom_context` | `Dict[str, str]` | `None` | Metadata propagated through the entire task hierarchy. Readable inside any task via `flyte.ctx().custom_context`. See **Tasks > Build tasks > Custom context**. | --- ## Reading context inside a task with `flyte.ctx()` Inside a running task, `flyte.ctx()` returns a `TaskContext` object with information about the current execution. Outside of a task, it returns a null context that is falsy and whose fields are all `None`. It is never `None` itself, so check it with `if flyte.ctx():` rather than `is None`. ``` @env.task async def inspect_context() -> str: ctx = flyte.ctx() action = ctx.action return ( f"run={action.run_name}, " f"action={action.name}, " f"mode={ctx.mode}, " f"in_cluster={ctx.is_in_cluster()}" ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/run-context/run_context.py* ### `TaskContext` fields | Field | Type | Description | |-------|------|-------------| | `action` | `ActionID` | Identity of this specific action (task invocation) within the run. | | `mode` | `"local"` \| `"remote"` | Execution mode of the current run. | | `version` | `str` | Version of the deployed task code bundle. | | `raw_data_path` | `RawDataPath` | Storage prefix where offloaded outputs are written, as a string in its `.path` attribute. | | `run_base_dir` | `str` | Base directory for the run's inputs, outputs, and intermediate per-action artifacts in the data plane object store. | | `custom_context` | `Dict[str, str]` | Propagated context metadata from `with_runcontext()`. | | `disable_run_cache` | `bool` | Whether `disable_run_cache` was set for this run. Set only in local runs; as of flyte 2.12, in remote runs it is `False`. | | `is_in_cluster()` | method | Returns `True` when `mode == "remote"`. Useful for branching local/remote behavior. | ### `ActionID` fields The `ctx.action` object identifies this specific task invocation: | Field | Type | Description | |-------|------|-------------| | `name` | `str` | Unique identifier for this action. | | `run_name` | `str` | Name of the parent run (defaults to `name` if not set). | | `project` | `str \| None` | Project the action runs in. | | `domain` | `str \| None` | Domain the action runs in. | | `org` | `str \| None` | Organization. | ### Naming external resources `ctx.action.run_name` is useful for tying external tool runs (experiment trackers, dashboards) to the corresponding Flyte run: ``` import wandb # type: ignore[import] @env.task async def train_model(epochs: int) -> float: ctx = flyte.ctx() # Use run_name to tie the W&B run to this Flyte run run = wandb.init( project="my-project", name=ctx.action.run_name, config={"epochs": epochs}, ) # ... training logic ... loss = 0.42 run.log({"loss": loss}) run.finish() return loss ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/run-context/run_context.py* This ensures that when you look up a run in Weights & Biases (or any other tool), its name matches what you see in the Flyte UI. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/entrypoints === Mark the tasks meant to be launched directly, so the task list stays readable as a project grows. # Entrypoint tasks As a project grows, the number of deployed tasks in a project/domain grows with it. Every `@env.task` you deploy shows up as a flat entry in the **Tasks list** alongside every other task, including internal helpers, leaf tasks, and intermediate steps that users aren't meant to invoke directly. Finding the handful of tasks that are actually meant to be *run* becomes a navigation problem. **Entrypoint tasks** solve this by letting you mark which tasks in an environment are the ones intended to be invoked by humans or other services. It's a purely declarative hint (it doesn't change how the task executes), but it makes the task easy to surface in the CLI, UI, and remote API. ## When to use entrypoints Mark a task as an entrypoint when: - **It is meant to be run directly**, by a user, a teammate, or a service, rather than only being called from another task. - **You want it to be discoverable** in the UI's entrypoint view or via filtered CLI queries. - **You are sharing tasks with team members** and want the "start here" tasks to stand out from internal helpers. Conversely, don't mark a task as an entrypoint if it only exists as a subtask called by another task, or if it's a utility helper not intended to be invoked on its own. > [!NOTE] > Entrypoints and [triggers](../../triggers/_index) solve related but distinct problems. A **trigger** automates *when* a task runs (on a schedule, on an event). An **entrypoint** declares *which* tasks are meant to be run at all. A task can be both: a scheduled entrypoint is simply a named starting point that also runs on a cron. ## Mark a task as an entrypoint Pass `entrypoint=True` to the `@env.task` decorator: ```python import flyte env = flyte.TaskEnvironment( name="hello_world", resources=flyte.Resources(cpu=1, memory="1Gi"), ) @env.task async def square(i: int) -> int: return i * i @env.task(entrypoint=True) async def say_hello_nested(data: str = "default string", n: int = 3) -> str: vals = [await square(i=i) for i in range(n)] return f"Hello {data} {vals}" ``` Here `say_hello_nested` is the intended starting point; `square` is an internal helper that `say_hello_nested` calls. Both get deployed, but only `say_hello_nested` is marked as an entrypoint. The flag is also available on `task.override()`, so you can promote or demote a task as an entrypoint at invocation time without editing the source: ```python promoted = square.override(entrypoint=True) ``` The default is `entrypoint=False`. If you don't mark anything, nothing is treated as an entrypoint. ## Discover entrypoint tasks Once deployed, entrypoint tasks can be surfaced in three ways. ### CLI Filter `flyte get task` to only entrypoint tasks: ```bash flyte get task --entrypoint ``` This lists every task in the configured project/domain that was deployed with `entrypoint=True`. ### Programmatic Use `flyte.remote.Task.listall()` with the `entrypoint` filter: ```python import flyte flyte.init_from_config() for task in flyte.remote.Task.listall(entrypoint=True): print(task.name, task.version) ``` This is useful for building your own catalogs, dashboards, or tooling on top of the Flyte API. ### UI The **Tasks list** in the UI has an **entrypoints** toggle that filters the view to only tasks marked as entrypoints. Use this when you're browsing a project and want to see only the tasks meant to be run. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/run-python-script === Run an arbitrary .py file remotely without wrapping it in a task. # Run a Python script `flyte run python-script` executes an arbitrary `.py` file on a remote Flyte cluster without wrapping it in a workflow or `@env.task`. Point it at a script, request resources, and the SDK builds an image, bundles the code, and runs it. ## When to use it Reach for `python-script` when: - You have a working script and want to run it on real cluster hardware (GPUs, big memory, long jobs) without rewriting it as a `@env.task`. - You're prototyping, benchmarking, or reproducing a one-off job and don't need typed I/O, caching, or DAG semantics. - You want to give a collaborator something they can run themselves with a single CLI command. Reach for a normal `@env.task` workflow instead when you need typed inputs and outputs, cross-task dependencies, caching, retries, or parameterized re-runs from the UI. ## Quickstart ```bash flyte run python-script hello.py ``` This uses the default Debian base image, 1 CPU, and 2 GiB of memory, enough for "hello world". Add flags to request more. ```bash flyte run python-script train.py \ --gpu 1 --gpu-type A100 --memory 64Gi \ --packages torch,transformers \ --output-dir output ``` Run-level options (`--follow`, `--name`, `--project`, `--domain`) go on the `flyte run` command, before `python-script`: ```bash flyte run --project my-proj --domain development python-script ... ``` ## What you can specify | Flag | Default | Purpose | |---|---|---| | `--cpu` | `1` | CPU cores to request. | | `--memory` | `2Gi` | Memory to request. | | `--gpu` | `0` | Number of GPUs (omit for CPU-only). | | `--gpu-type` | `T4` | Accelerator class: `T4`, `A100`, `H100`, `L4`, `A10G`, etc. Only used when `--gpu > 0`. | | `--image` | *(auto)* | Container image URI or a named image from your config. Mutually exclusive with `--packages`. | | `--packages` | *(none)* | Comma-separated pip packages layered onto the default base image, e.g. `torch,transformers`. Mutually exclusive with `--image`. | | `--timeout` | `3600` | Task timeout in seconds. The subprocess is killed 60 s before this. | | `--extra-args` | *(none)* | Comma-separated values passed to the script as `sys.argv`. | | `--output-dir` | *(none)* | Directory path *inside the container* to upload as the task's output after the script finishes. | | `--include-files` | *(none)* | Path or glob (relative to the script's directory) to bundle alongside the script. Repeat the flag to pass multiple entries. | | `--queue` | *(config)* | Flyte queue / cluster override. | ## Handling dependencies Three modes, in order of increasing control: ### 1. Standard library only No flag needed. The default image is a plain Debian with Python; anything in the stdlib (`json`, `os`, `subprocess`, `csv`, `datetime`, โ€ฆ) works without further setup. ```bash flyte run python-script hello.py ``` ### 2. Pip packages on top of the default image ```bash flyte run python-script analyze.py --packages numpy,pandas,matplotlib ``` The SDK layers a `pip install` step onto the default image and caches the result. Re-runs with the same package set skip the build. Changing the set invalidates the cache and rebuilds. ### 3. Bring your own image When you need a specific Python version, system packages, or a pre-baked environment, pass a full image URI: ```bash flyte run python-script job.py \ --image 1234.dkr.ecr.us-east-2.amazonaws.com/my-org/job:v1.2.3 ``` Your image **must have `flyte` installed** so the Flyte runtime inside the pod can launch the script. A Dockerfile starting from `python:3.12-slim-bookworm` with `pip install flyte` works. If your image is registered in your Flyte config under a short name, pass the short name instead of a URI and the SDK looks it up in the image map. ## Handling inputs and outputs `python-script` does **not** use Flyte's typed I/O. Your script is a regular Python program: it reads `sys.argv` and writes to a directory on disk. ### Passing inputs Use `--extra-args` for positional arguments. The comma-separated values become `sys.argv[1:]` inside the container: ```bash flyte run python-script job.py --extra-args "alice,42,--verbose" ``` ```python # job.py import sys name, count, *flags = sys.argv[1:] ``` For structured inputs (JSON payloads, files), either inline the data as a single `--extra-args` value that your script parses, or have the script download from an object storage URI it knows about (for example, an S3 URI). ### Capturing outputs Use `--output-dir` to point at a directory the script writes to. After the script exits with code 0, the SDK uploads the entire directory recursively (including subdirectories and binary files) as a `flyte.io.Dir` on the task's output: ```bash flyte run python-script job.py --output-dir output ``` ```python # job.py import os os.makedirs("output", exist_ok=True) with open("output/result.csv", "w") as f: f.write("col1,col2\n1,2\n") ``` The uploaded directory appears in the run's outputs panel as a blob store URI (for example, an S3 URI). Browse or download it from the UI. `stdout` (with `stderr` merged) is also available on the task output as a ~80-line tail, so you can peek at the end-of-run output without reopening the log stream. ## Bundling: what gets uploaded By default the CLI only bundles the script you pointed at. If your script imports sibling modules or reads local config/data files, list them with `--include-files` (repeat the flag for multiple entries): ```bash flyte run python-script train.py \ --include-files "*.py" \ --include-files "configs/settings.yaml" ``` Entries are paths or globs resolved relative to the script's directory; absolute paths are passed through unchanged. Given: ``` my_job/ train.py # flyte run python-script my_job/train.py --include-files "*.py" data_utils.py # importable as: from data_utils import ... model.py # importable as: from model import ... ``` the glob `"*.py"` picks up both sibling modules and makes them importable inside the container. For anything more elaborate (transitive package trees, large data assets, system dependencies), bake the files into a custom image with `--image`, or switch to a regular `@env.task` workflow. ## Python API The same feature is available as `flyte.run_python_script()` for programmatic use: ```python from pathlib import Path import flyte flyte.init_from_config("config.yaml") run = flyte.run_python_script( Path("train.py"), gpu=1, gpu_type="A100", memory="64Gi", image=["torch", "transformers"], # list = pip packages on base image output_dir="output", extra_args=["--epochs", "10"], include_files=["*.py", "configs/settings.yaml"], ) print(run.url) ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/run-with-notifications === Fire a notification when a run reaches a terminal state. # Run with notifications You can attach notifications to a single run by passing them to `flyte.with_runcontext()`. Notifications fire when the run reaches the terminal execution phase; no trigger or persistent deployment is required. ``` import os import flyte from flyte import notify from flyte.models import ActionPhase env = flyte.TaskEnvironment(name="notify_example") SLACK_WEBHOOK_URL = os.environ["SLACK_WEBHOOK_URL"] NOTIFICATION_EMAIL = os.environ["NOTIFICATION_EMAIL"] @env.task def compute(x: int, y: int) -> int: return x + y if __name__ == "__main__": result = flyte.with_runcontext( notifications=( notify.Slack( on_phase=ActionPhase.SUCCEEDED, webhook_url=SLACK_WEBHOOK_URL, message="Run {{.Run.Name}} succeeded.", ), notify.Email( on_phase=ActionPhase.FAILED, recipients=[NOTIFICATION_EMAIL], subject="ALERT: Run {{.Run.Name}} failed", body="Run: {{.Run.Name}}\nError: {{.Error}}", ), ), ).run(compute, x=3, y=7) print(f"Result: {result}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/run-with-notifications/run_with_notifications.py* Pass a single notification or a tuple of notifications. The notification types in `flyte.notify` are `Slack`, `Email`, `Teams`, and `Webhook`. > [!NOTE] > Delivery details such as `webhook_url` and `recipients` are plain values, sent to the backend with the run when you submit it. The example reads `SLACK_WEBHOOK_URL` from your local environment at submission, not inside the task, and a notification can't reference a secret. To choose the destination at runtime, for example a different webhook on each cluster, **Tasks > Run and deploy tasks > Send notifications from your code**. > [!NOTE] > To attach notifications to every run created by a scheduled trigger, set `notifications` on the `flyte.Trigger` object instead. See **Triggers > Notifications**. ## Execution phases The `on_phase` parameter accepts a single phase or a tuple of phases from `flyte.models.ActionPhase`: | Phase | Description | |-------|-------------| | `ActionPhase.SUCCEEDED` | Run completed successfully | | `ActionPhase.FAILED` | Run failed with an error | | `ActionPhase.TIMED_OUT` | Run exceeded its timeout | | `ActionPhase.ABORTED` | Run was manually aborted | ## Template variables All message fields support template variables substituted at delivery time: | Variable | Description | |----------|-------------| | `{{.Run.Project}}` | Project name | | `{{.Run.Domain}}` | Domain name | | `{{.Run.Name}}` | Run ID | | `{{.Phase}}` | Execution phase | | `{{.Error}}` | Error message (failed) or abort reason (aborted) | ## Slack notifications `notify.Slack` sends a message to a Slack channel via an [incoming webhook](https://api.slack.com/messaging/webhooks). **Simple message:** ``` notify.Slack( on_phase=ActionPhase.FAILED, webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL", message="Run {{.Run.Name}} failed in {{.Run.Project}}/{{.Run.Domain}}: {{.Error}}", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* **Rich formatting with [Block Kit](https://api.slack.com/block-kit):** Use `blocks` instead of `message` for structured layouts. When `blocks` is provided, `message` is ignored. ``` notify.Slack( on_phase=ActionPhase.SUCCEEDED, webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL", blocks=[ { "type": "header", "text": {"type": "plain_text", "text": "Task Succeeded"}, }, { "type": "section", "fields": [ {"type": "mrkdwn", "text": "*Run:*\n{{.Run.Name}}"}, {"type": "mrkdwn", "text": "*Phase:*\n{{.Phase}}"}, ], }, {"type": "divider"}, { "type": "context", "elements": [ {"type": "mrkdwn", "text": "{{.Run.Project}}/{{.Run.Domain}}"}, ], }, ], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* ## Email notifications `notify.Email` sends an email notification. Provide `body` for plain text, `html_body` for HTML, or both (sent as multipart). ``` notify.Email( on_phase=ActionPhase.FAILED, recipients=["oncall@example.com"], cc=["team-lead@example.com"], subject="ALERT: Run {{.Run.Name}} failed", body="Run: {{.Run.Name}}\nError: {{.Error}}", html_body="Error: {{.Error}}
", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* To receive emails locally while developing, start a debug SMTP server before running your script: ```bash # Python >= 3.12 pip install aiosmtpd python -m aiosmtpd -n -l localhost:1025 ``` The server prints received emails to stdout. Port 1025 needs no special privileges; to listen on the standard SMTP port 25 instead, run the command with `sudo`. Either way, set the SMTP port in your configuration to match. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/notify-from-code === Post a message when a run succeeds or fails, from the run's own driver task, with the destination read from a secret at runtime. # Send notifications from your code To report a run's outcome, wrap the work in the driver task in `try`/`except`, post the message, and re-raise. The notification is ordinary code, so it reads its destination from a secret when the task runs. The same deployment can then post to a different webhook on each cluster. **Tasks > Run and deploy tasks > Run with notifications** need no code, but their delivery details are fixed when you submit the run. Use this pattern when the destination must be chosen at runtime, or when the message needs results the run computed. ``` import os import httpx import flyte env = flyte.TaskEnvironment( name="notify_from_code", secrets=[flyte.Secret(key="SLACK_WEBHOOK_URL")], ) @flyte.trace async def post_slack(text: str) -> None: # The secret is read when the task runs, not when it is deployed. async with httpx.AsyncClient() as client: response = await client.post(os.environ["SLACK_WEBHOOK_URL"], json={"text": text}) response.raise_for_status() @env.task(retries=3) async def train(x: int) -> int: if x < 0: raise ValueError("x must be non-negative") return x * 2 @env.task async def pipeline(x: int) -> int: run_name = flyte.ctx().action.run_name try: result = await train(x) except Exception as e: await post_slack(f"Run {run_name} failed: {e}") raise await post_slack(f"Run {run_name} succeeded with result {result}.") return result ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-deployment/notify-from-code/notify_from_code.py* Create the secret before you run the task: ```bash flyte create secret SLACK_WEBHOOK_URL --value ``` Each **Clusters and queues > Cluster pools** has its own secret store. To post to a different webhook from each pool, create `SLACK_WEBHOOK_URL` in each one with `--cluster-pool`. See **Tasks > Configure tasks > Secrets**. ## Notify once per run While the driver runs without interruption, two details make it post once and still report the failure. A driver that resumes after an interruption can post again; see **Tasks > Run and deploy tasks > Send notifications from your code > Limitations**. - **Put retries on the child tasks, not the driver.** `train` retries up to three times, and the driver sees the exception only after the last attempt fails, so it posts once. If the driver had `retries`, each driver attempt would post again. - **Re-raise after posting.** The run still ends as failed, and the error stays in the run. The exception from a failed child task reaches the driver as `flyte.errors.RuntimeUserError`, with the original error message. The example catches `Exception` so that system errors notify too. ## Limitations The driver sends the notification, so nothing is sent if the driver itself doesn't reach the `except` block. This happens when: - The driver task runs out of memory, times out, or crashes. - The run is aborted. If the driver resumes after an interruption, it can send the message again. `post_slack` is a **Tasks > Build tasks > Traces** that returns `None`, so a resumed driver has no recorded result to replay and runs it again. A traced function that returns a value other than `None`, such as the response's status code, is replayed instead. Even then, a post that was sent but not yet recorded when the driver stopped is sent again. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/rerun-runs === Launch a fresh run from a previous one's recorded task, code, inputs, and configuration. # Rerun a run Every run in Union.ai is durable: its task, code, inputs, and configuration are all recorded on the backend. That means you can launch a brand-new run from any previous one without having the original code checked out locally. This is useful for retrying a transient failure, reproducing a result, or tweaking a few inputs and running again. You can rerun at two levels of granularity: - **The whole run**: re-execute the entry point task (the `a0` action) and everything it calls. - **A single action**: re-execute one nested action on its own. And you can trigger a rerun from three places: the **UI**, the **CLI**, or **programmatically** with the Python SDK. ## Rerun from the UI ### Rerun an entire run Open the run in the UI. In the top-right corner of the run view, click **Rerun**. ![The Rerun button in the top-right of the run view](../../../_static/images/user-guide/task-deployment/rerun-runs/rerun-button.png) This opens the launch form pre-filled with the original run's inputs, environment variables, and code. You can either: - Trigger the run as-is to reproduce the original execution exactly, or - Edit the inputs, environment variables, and other launch settings in the form before triggering to run a variation. ![The launch form, pre-filled with the run's recorded inputs](../../../_static/images/user-guide/task-deployment/rerun-runs/rerun-launch-form.png) ### Rerun a single action You can also rerun an individual action without rerunning the whole workflow. Navigate to the action in the run's action list, open its details view, and use the **Rerun action** option (in the action menu in the top-right of the action details panel). ![The action menu with the Rerun action option](../../../_static/images/user-guide/task-deployment/rerun-runs/rerun-action-menu.png) This launches a new run starting from that action, using the action's recorded inputs. As with a full rerun, you can adjust the inputs in the launch form first. ## Run lineage When you rerun a run from the UI, Union.ai records the run you started from as the new run's parent. This provenance is captured automatically, so you never have to set it yourself. A parent link is also recorded when a run is derived from another run in other ways, such as recovering a failed run. Run lineage lets you trace a run back to the one it was started from. The parent is surfaced in two places in the console: - **In the run list**, a rerun is marked with a rerun icon next to its run ID. Hover the icon to see "Rerun of" and the ID of the parent run, so you can tell at a glance which runs were started from an earlier run. A rerun also shows no trigger and is owned by the user who started it, rather than by a schedule. ![A run list with the rerun icon and "Rerun of" tooltip on a rerun row](../../../_static/images/user-guide/task-deployment/rerun-runs/run-list-rerun-indicator.png) - **On the run details page**, a rerun shows a **Rerun** badge next to its status. Hover the badge, or open **Run info**, to see the **Rerun of** link to the parent run. ![The Rerun badge and "Rerun of" parent link on the run details page](../../../_static/images/user-guide/task-deployment/rerun-runs/run-details-rerun-of-parent.png) ## Rerun from the CLI `flyte rerun` fetches the prior run's task **and** inputs from the backend and launches a new run. You don't need the original code checked out locally. Everything is pulled from the platform: ```bash # Rerun with the prior run's exact code and inputs flyte rerun # Give the new run a name and stream its parent-action logs flyte rerun --name retry-1 --follow ``` Common options: | Option | Description | |---|---| | `-p`, `--project` | Project for the new run (defaults to your config). | | `-d`, `--domain` | Domain for the new run (defaults to your config). | | `--name` | Name for the new run (a random name is generated if unset). | | `-e`, `--env KEY=VALUE` | Override an environment variable for the new run. Repeatable. | | `--label KEY=VALUE` | Set a label on the new run. Repeatable. | | `-f`, `--follow` | Stream the parent action's logs after launch. | > [!NOTE] > `flyte rerun` reuses the prior run's inputs as-is. To change input values from the command line, > use the programmatic `flyte.rerun(, key=value)` form shown below. ### Rerun compared with a fresh run | Command | Code | Inputs | |---|---|---| | `flyte run ` | local | from CLI | | `flyte rerun ` | fetched from backend | prior run's | Both start the run over from the beginning. To instead keep the successful actions of a failed run and re-execute only what failed, add `--recover` to `flyte rerun`. See **Tasks > Run and deploy tasks > Recover a failed run**. `flyte rerun` never substitutes local code, with or without `--recover`. To replay a prior run with code you have changed, see **Tasks > Run and deploy tasks > Fork a run**. ## Rerun programmatically Use `flyte.rerun()` to rerun from Python. Like the CLI, it fetches the prior run's task and inputs from the backend, so no local code is required: ```python import flyte flyte.init_from_config() # Rerun a prior run with its exact inputs (task + inputs fetched from the platform): flyte.rerun("ul56wcvgqrb9vzhzz5l2") # Change input parameters โ€” they are converted against the prior run's interface: flyte.rerun("ul56wcvgqrb9vzhzz5l2", x_list=[1, 2, 3]) ``` `flyte.rerun()` returns a `flyte.remote.Run`, just like `flyte.run()`, so you can monitor it, wait on it, and retrieve its outputs in the same way. See **Tasks > Run and deploy tasks > Interact with runs and actions** for details. To control launch settings (name, project, domain, environment variables, labels) use `flyte.with_runcontext(...).rerun(...)`: ```python flyte.with_runcontext( name="retry-1", env_vars={"LOG_LEVEL": "20"}, ).rerun("ul56wcvgqrb9vzhzz5l2") ``` ## Related - **Tasks > Run and deploy tasks > Recover a failed run**: re-run only what failed, reusing the actions that succeeded. - **Tasks > Run and deploy tasks > Interact with runs and actions**: retrieve, monitor, and inspect runs and actions. - **Tasks > Run and deploy tasks > Run command options**: the full set of `flyte run` options. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/recover-runs === Relaunch a failed run so it reuses the actions that already succeeded. # Recover a failed run When a run fails partway through, most of its work is usually still good. **Recovery** launches a new run that reuses the successful actions from a previous one and re-executes only what failed. A reused action is not executed again at all: its recorded output is handed straight to whatever consumes it. This is the difference between recovery and a plain **Tasks > Run and deploy tasks > Rerun a run**: a re-run starts the whole run over from the beginning, while a recovery picks up where the failure left off. Recovery is one of two behaviours of the same verb, `flyte rerun`. It is remote-only: rerun and recover are not supported in local mode. ## What a recovery reuses Given a run whose `summarize` task failed, leaving its downstream `report` task unreached: ```mermaid flowchart LR subgraph src["Source run"] s1["prepare ร—6
succeeded"] --> s2["process ร—6
succeeded"] --> s3["summarize
failed"] --> s4["report
never ran"] end subgraph rec["Recovery run"] r1["prepare ร—6
reused"] --> r2["process ร—6
reused"] --> r3["summarize
re-executed"] --> r4["report
ran"] end s1 -. "matched by action name" .-> r1 s2 -.-> r2 s3 -.-> r3 s4 -.-> r4 ``` The parent task that issues these calls always re-executes, since it is the code that re-drives the graph. Its children are then matched one at a time as it calls them. ## How this differs from caching Caching and recovery both skip work that has already been done, but they are keyed on different things, and they are not alternatives to one another. Caching is **content-addressed**. A task's cache key comes from its inputs, name, interface, and cache version, so a hit can be served to any run at any time, subject to the lookup scope. You opt in per task, in code, and `flyte.TaskEnvironment` defaults to caching disabled. Recovery is **scoped to a single run**. It reuses what one named run produced, at the position in the graph where that run produced it. You opt in per run, at launch, and no task has to be marked as anything beforehand. | | Caching | Recovery | |---|---|---| | Keyed on | inputs and task version | the source run, plus the action's position within it | | Reuse comes from | any prior run in the lookup scope | the one run you name | | Enabled | per task, in code (off by default) | per run, at launch | | Two identical calls in one run | the second is a cache hit | both remain distinct actions | Three practical consequences follow: - **Recovery needs no preparation.** A task that was never marked cacheable is recovered anyway, which is usually the situation you are in when a long run fails. - **Each one makes a different claim.** Marking a task cached asserts that it is a pure function of its inputs, for every future run. Recovery asserts only that one run's result at one point is still good, so it can reuse output from tasks that would not be safe to cache at all. - **They are independent.** Caching applies on any run, including a recovery run; recovery covers the actions caching does not. A recovered action is reported in its own terminal phase, distinct from an action that succeeded by executing. ## One verb, two behaviours `flyte rerun` fetches the prior run's task spec and inputs from the platform. No local code is involved, and nothing you edit locally is picked up. | Call | What happens | |---|---| | `flyte rerun ` | A whole new run with the same inputs. Every action executes again, subject to global caching. | | `flyte rerun --recover` | A whole new run, but actions that already succeeded are reused as-is. Only what failed or never ran executes. | Recovery always replays the source run's **code** as-is. It is durability against intermittent failures, not a way to patch a run. To replay a prior run with code you have changed, see **Tasks > Run and deploy tasks > Fork a run**. ## Recover from the CLI ```bash flyte rerun --recover --follow ``` | Option | Description | |---|---| | `--recover` | Reuse the prior run's succeeded actions, re-running only what failed or never ran. | | `--action-name ` | Re-run only this action, rooted at its task with the inputs it received. Cannot be combined with `--recover`. | | `--force-rerun-action ` | With `--recover`, re-execute an action even though it succeeded in the source run. Repeatable. | | `--allow-missing-outputs` | Proceed when the source run's outputs have been cleaned up from storage. | | `-e`, `--env KEY=VALUE` | Set an environment variable on the new run. Repeatable. | Action names are deterministic hashes rather than positions, so list them with `flyte get action ` and copy the one you want. A listed parent re-enqueues its children, so list those too to force a whole subtree; unknown names are ignored. Reused actions land in the `RECOVERED` phase, which is terminal and success-equivalent, so `flyte get action ` tells you exactly what recovery skipped. ### Changing inputs The source task's inputs become options on `flyte rerun`, read off the run itself rather than from local code. Every one is optional: an input you leave out keeps the prior run's value, so changing one input of a five-input task is one flag rather than five. ```bash flyte rerun --threshold 0.9 flyte rerun --recover --threshold 0.9 ``` > [!WARNING] Recovered actions keep their original outputs > An action reused from the source run keeps the output it produced under the **original** inputs. > Recovery does not recompute it against the new ones. Name the actions that must re-execute in > `--force-rerun-action`. When the inputs you pass cover the task's whole interface, the source run's inputs are never read, which makes `--allow-missing-outputs` irrelevant in that case. Because recovery matches succeeded actions by name, and a run rooted at a single action has a different action tree, `--action-name` cannot be combined with `--recover`. ## Recover programmatically `flyte.rerun()` takes the same arguments the CLI exposes: ```python import flyte flyte.init_from_config() # Re-run everything with the prior run's inputs: flyte.rerun("") # Reuse the succeeded actions, re-running only what failed or never ran: flyte.rerun("", recover=True) # Force specific actions to re-execute even though they succeeded: flyte.rerun("", recover=True, force_rerun_actions=["a3", "a7"]) # Change inputs, keeping the ones you leave out, and still reuse succeeded actions: flyte.rerun("", recover=True, threshold=0.9) # Re-run a single action, rooted at its task with the inputs it received: flyte.rerun("", action_name="a3") ``` `allow_missing_source_outputs=True` is the programmatic equivalent of `--allow-missing-outputs`. Launch settings still come from `flyte.with_runcontext()`: ```python flyte.with_runcontext(name="retry-1", env_vars={"LOG_LEVEL": "20"}).rerun("", recover=True) ``` Task inputs share the keyword namespace with those arguments, so a task input named `run_name`, `action_name`, `recover`, `force_rerun_actions` or `allow_missing_source_outputs` cannot be passed this way. ## Related - **Tasks > Run and deploy tasks > Rerun a run**: launch a fresh run from a previous one, without reusing its actions. - **Tasks > Run and deploy tasks > Interact with runs and actions**: retrieve, monitor, and inspect runs and actions. - **Tasks > Run and deploy tasks > Run command options**: the full set of `flyte run` options. - **Tasks > Run and deploy tasks > Fork a run**: replay a prior run with code you have changed. - **Tasks > Run and deploy tasks > Debug a run**: inspect a failure before deciding how to recover from it. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/fork-runs === Replay a prior run with your current code and inputs, reusing what still holds. # Fork a run Forking replays a prior run with the code and inputs you have **now**: the actions that succeeded are reused, and the ones you changed re-execute. It is time-travel debugging for a pipeline. Go back to a run, change a task or an input, and re-run only what that change actually affects. ```bash flyte fork main.py main ``` A fresh code bundle is built from your working tree, so nothing about the source run's code is replayed except where it is unchanged. > [!NOTE] Availability > `flyte fork` ships in `flyteplugins-union` 0.8.1 and later (`pip install flyteplugins-union`), > alongside `flyte` 2.6.5. It is remote-only: forking a run has no local equivalent. ## How it relates to rerun and recover **Tasks > Run and deploy tasks > Recover a failed run** deliberately refuses to substitute your code, because it exists to survive infrastructure failures rather than to patch a run. Fork is the verb that does substitute it, and the three form a progression: | Command | Code | Actions | |---|---|---| | `flyte rerun ` | the source run's | everything re-executes | | `flyte rerun --recover` | the source run's | succeeded actions reused | | `flyte fork ` | **yours** | succeeded actions reused | ```mermaid flowchart LR R["Source run
(failed)"] -- "same code
everything re-runs" --> A["flyte rerun"] R -- "same code
reuse succeeded" --> B["flyte rerun --recover"] R -- "reuse succeeded" --> C["flyte fork"] L["Your working tree"] -- "new code" --> C ``` Fork can also change the root action's inputs. In Python the substitute code is optional too: `fork(run, threshold=0.9)` with no `task_template` replays the source run's task spec against new inputs, which makes fork the way to recover a run with different inputs. On the CLI the file and task are always given, since the command is built from them. ## Fork from the CLI `flyte fork` takes the run first, then the file and task. `flyte run`'s options (image, copy style, service account, env, labels, queue) come before the run name: ```bash flyte fork main.py main flyte fork --name fix-1 --env LOG_LEVEL=debug main.py main ``` `--force-rerun-action` forces an action to re-execute even though it succeeded in the source run: ```bash flyte fork --force-rerun-action a3 main.py main ``` List action names with `flyte get action `. A listed parent re-enqueues its children, so list those too to force a whole subtree; unknown names are ignored. ### Changing inputs The task's inputs become options, built from the signature in your local code. They are optional and carry no defaults: an input you leave out keeps the source run's value, so changing one input of a five-input task is one flag rather than five. Booleans take `--x/--no-x` so either value stays expressible, and unknown input names are rejected up front. ```bash flyte fork main.py main --threshold 0.9 ``` > [!WARNING] Recovered actions keep their original outputs > An action reused from the source run keeps the output it produced under the **original** inputs. > Fork does not recompute it against the new ones. Name the actions that must re-execute in > `--force-rerun-action`. When the inputs you pass cover the whole interface, the source run's inputs are never fetched, so a run whose inputs have been cleaned up from storage can still be forked. ## Fork programmatically ```python from flyteplugins.union import fork, with_forkcontext fork("", task_template=main) # new code fork("", task_template=main, threshold=0.9) # new code and inputs fork("", threshold=0.9) # source code, new inputs fork("", task_template=main, force_rerun_actions=["a3"]) ``` `with_forkcontext()` accepts the same keyword arguments as `flyte.with_runcontext()` and returns a runner that can also `fork()`: ```python with_forkcontext(name="fix-1", env_vars={"LOG_LEVEL": "debug"}).fork("", task_template=main) ``` ## What re-executes A fork reuses an action when its **action name** matches one that succeeded in the source run, and action names are computed rather than assigned: ```mermaid flowchart LR tn["task name"] --> TI["task identity"] ih["interface hash"] --> TI fb["hash of the task
function's own body"] --> TI TI --> AN["action name"] pan["parent action name"] --> AN inh["inputs hash"] --> AN seq["call sequence"] --> AN grp["group"] --> AN ex["image ยท resources
env vars ยท code bundle"] -. "not included" .-x AN ``` Two properties follow, and they explain nearly everything about what a fork re-runs: - **Deployment details are excluded on purpose.** Changing a task's resources or image does not rename its action, so the rest of the run stays reusable. Raising the memory on a task that hit `flyte.errors.OOMError` and forking does exactly what you would hope: the successful upstream is reused, and the failed task re-executes with its new limit. - **Matching follows the data.** Because a child's name folds in its inputs hash, an upstream task that re-executes but produces *identical* outputs leaves its downstream actions matchable, and they are still reused. ### What a code change re-runs | You change | On fork | |---|---| | A task's function body | that task re-runs | | A task's signature | that task re-runs | | A task's docstring | that task re-runs | | The task function's name | that task re-runs | | The `flyte.TaskEnvironment` name | every task in it re-runs | | Comments inside a task | reused | | Formatting or whitespace | reused | | `flyte.Resources` (cpu, memory) | reused | | The image, or added packages | reused | | A module-level constant a task reads | reused (see below) | | A helper function a task calls | reused (see below) | > [!WARNING] Identity is the function body, and only the function body > A task's identity hashes only the decorated function's own source. If you edit a module-level > constant it reads, or a helper function it calls, the action name does not change, so a task > that already succeeded is reused and your change has no effect on it. Nothing warns you. > > Use `--force-rerun-action` to re-execute those actions explicitly, or move the changed logic > into the task body. The same rule governs `flyte.trace` functions: a traced function hashes its own body, so editing it causes it to re-execute instead of replaying its recorded result. A helper it calls still does not count as a change. Runs launched from a notebook or with a pickled code bundle behave differently: they version on the bundle itself, so any code change renames every action and nothing is reused. ## Related - **Tasks > Run and deploy tasks > Recover a failed run**: replay a failed run with its original code, reusing what succeeded. - **Tasks > Run and deploy tasks > Rerun a run**: launch a fresh run from a previous one, without reusing its actions. - **Tasks > Run and deploy tasks > Debug a run**: inspect a failure before deciding how to fork it. - **Tasks > Run and deploy tasks > Interact with runs and actions**: retrieve, monitor, and inspect runs and actions. === PAGE: https://www.union.ai/docs/v2/union/user-guide/tasks/task-deployment/debug-runs === Drop into a live session on a running action to inspect its environment, filesystem, and code. # Debug a run When an action behaves unexpectedly, Union.ai lets you drop into a live debugging session for that action, inspecting its environment, filesystem, and code from the inside instead of guessing from logs alone. There are three ways to debug: - **From the UI**: open a debugging session for any action with a single click. - **From the SDK or CLI**: launch a run in debug mode (`debug=True` / `--debug`) to start a browser-based VS Code session on the task pod and step through your code line-by-line. - **SSH into the task** (Beta): attach your local terminal or VS Code directly to a running task pod, using the `flyteplugins-union` plugin. ## Debug from the UI Open the run in the UI and select the action you want to debug from the action list. In the action details view, click **Debug action** (the button in the top-right of the summary panel). This opens an interactive debugging session for that action, where you can explore the action's state directly. Debugging is scoped to the individual action, so you can debug a single nested action without affecting the rest of the run. ## Debug from the SDK or CLI Launching a run in **debug mode** starts a browser-based VS Code session (a `code-server`) inside the task pod. You connect to it from the UI and step through your task code line-by-line on the same infrastructure the run uses, against the same data, images, and dependencies. This is especially valuable when a task behaves differently remotely than it does locally, where the inputs, models, or environment often differ and reproducing the problem on your laptop is impractical. Unlike ****Tasks > Run and deploy tasks > Debug a run > Debug from the UI****, which you open on an action after it has started, debug mode is requested at **launch time**, from your own code or from the CLI. ### From the SDK Pass `debug=True` to `flyte.with_runcontext()`, then call `.run(...)` as usual. After the run starts, `run.get_debug_url()` returns the URL of the VS Code session: ```python # debug.py import flyte env = flyte.TaskEnvironment(name="debug_example") @env.task def say_hello(name: str) -> str: greeting = f"Hello, {name}!" print(greeting) return greeting if __name__ == "__main__": flyte.init_from_config() run = flyte.with_runcontext(debug=True).run(say_hello, name="World") print("Run URL:", run.url) print("Debug URL:", run.get_debug_url()) ``` `run.get_debug_url()` waits for the VS Code Debugger entry to appear in the run's action details, then returns its URL. It returns `None` if the entry never appears. Check the task logs if so. The same URL is also available in the UI on the action's details view. ### From the CLI Pass `--debug` to `flyte run`: ```bash flyte run --debug debug.py say_hello --name World ``` The run starts with a `code-server` attached. Once the session is ready, the CLI prints a **Debug** panel containing the VS Code Debugger URL. Open it to connect to the interactive session. If the URL doesn't appear, the panel points you to the task logs. > [!NOTE] > The debug session runs on the remote task pod and stays alive while you use it, shutting down > automatically after a period of inactivity. Because the session runs inside the task container, > it has the run's real inputs, image, and dependencies available for interactive inspection. ## SSH into the task (Beta) > [!WARNING] Beta feature > SSH-into-task debugging is a Beta feature delivered through the `flyteplugins-union` plugin. Its > commands and APIs may change in future releases. This mode launches your run with an in-pod SSH server fronted by a small WebSocket bridge, then gives you a ready-to-paste `~/.ssh/config` block so you can attach your **local** `ssh` client or **VS Code Remote-SSH** straight into the task pod. The SSH keypair is auto-managed: you never run `ssh-keygen`. ### Requirements - `flyte` (SDK) version **2.5.8 or newer** - `flyteplugins-union` version **greater than 0.5.0** The in-pod SSH server is pure Python (`asyncssh`), so there is no `openssh-server` install. From `flyte` 2.12.2, `asyncssh` is the optional `flyte[ssh]` extra: - The default task image includes it, and so do images you build on it with `Image.from_debian_base()`. Nothing else is needed. - On any other image without it, `flyte` installs `asyncssh` when the SSH session starts, which needs `uv` on the `PATH` or `pip` in the task's Python environment, and access to a package index. Without them, the session fails with an `ImportError` that says to add `flyte[ssh]`. To skip the install, add the extra to the image, for example `.with_pip_packages("flyte[ssh]")`. Install the plugin: ```bash uv pip install flyteplugins-union ``` ### Debug from the CLI `flyte debug ` does everything in one shot: it relaunches an existing run with ssh-debug enabled (fetching that run's code and inputs), waits for the pod's ssh route to come up, and prints a ready-to-paste `~/.ssh/config` block. The canonical flow is to write the `Host` block straight into `~/.ssh/config`, then `ssh` to it: ```bash flyte debug --write-config ssh flyte-debug ``` `--write-config` adds a `Host flyte-debug` block to your `~/.ssh/config`, so `ssh flyte-debug` (or **VS Code โ†’ Remote-SSH โ†’ `flyte-debug`**) connects straight into the task pod. Only `` is required; the action name defaults to the root action `a0`. Pass an action name as a second argument to source the task and inputs from a nested action instead. #### Naming a session Pass `--name` to name the debug session. The name is used as **both** the remote debug run name and the `~/.ssh/config` Host alias, so you then `ssh `: ```bash flyte debug --name my-dbg --write-config ssh my-dbg ``` Naming lets you keep several debug sessions side by side. The debug run uses a **deterministic name** (derived from the source run, or from `--name`), so re-running the same command **reconnects to the live debug session instead of spawning a duplicate**. To start a fresh debug run (for example if the previous one died), pass a new `--name`. For a long-lived tunnel that survives re-logins, add `--api-key`; to relaunch without blocking on the pod coming up, add `--no-wait`: ```bash flyte debug --name my-dbg --api-key --write-config ``` Useful options: | Option | Description | |---|---| | `--user` | SSH login user inside the pod (default `root`). | | `--identity-file` | Private key to authenticate with. Defaults to the auto-managed `~/.flyte/ssh-debug/id_ed25519`. | | `--name` | Name for this debug session: used as **both** the `~/.ssh/config` Host alias and the remote debug run name. Re-running with the same name reconnects; a new name starts a fresh debug run. | | `--api-key` | Authenticate the tunnel with a dedicated, long-lived API key instead of your interactive session token. | | `--refresh-token` | Force a fresh token instead of reusing the cached one (use if you hit auth errors). | | `--write-config` | Write the `Host` block into `~/.ssh/config`, replacing any prior block of the same name. | | `--wait` / `--no-wait` | Wait for the route to become ready and print the ssh-config (default), or relaunch and return immediately. | | `--timeout` | Seconds to wait for the debug route to become ready (default `300`). | > [!NOTE] > Tokens expire. If you get a `401` on reconnect, just re-run the same `flyte debug` command; it > reconnects and refreshes the token in place (no `--write-config` needed). For multi-day sessions, > use `--api-key`. ### Debug programmatically The `debug()` convenience function mirrors `flyte.run()` / `flyte.rerun()`, with the ssh-debug environment injected so the new run comes up with an in-pod SSH server. After it returns, resolve the connection with `SSHDebug.connect()`: ```python import flyte from flyteplugins.union import debug from flyteplugins.union.remote import SSHDebug flyte.init_from_config() # Launch a NEW task in debug mode... run = debug(my_task, x=1) # ...or relaunch an EXISTING run in debug mode (fetches its code + inputs): run = debug("some-prior-run") # Print a ready-to-paste ~/.ssh/config block for the run's root action (a0). print(SSHDebug.connect(run.name).ssh_config) ``` For the run-name form, pass `inputs={...}` to change parameters or `task_template=...` to substitute code. For finer control over launch settings, use `with_debugcontext()`: it is `flyte.with_runcontext()` preconfigured for ssh-into-task debug (it creates the auto-managed keypair and sets the SSH-debug environment variables), so you call `.run(...)` or `.rerun(...)` on it: ```python from flyteplugins.union import with_debugcontext run = with_debugcontext(env_vars={"LOG_LEVEL": "20"}).run(my_task, x=1) ``` ## Related - **Tasks > Run and deploy tasks > Run context**: set `debug` and other invocation-time parameters with `flyte.with_runcontext()`. - **Tasks > Run and deploy tasks > Rerun a run**: launch a new run from a previous one. - **Tasks > Run and deploy tasks > Interact with runs and actions**: retrieve, monitor, and inspect runs and actions. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps === Long-running services for dashboards, REST APIs, and model endpoints. # Apps An app is a long-running service that Flyte keeps up, rather than a job that runs to completion. Use an app when something needs to stay reachable at a URL: a dashboard, a REST API, a model endpoint, or an MCP server. Apps are declared the same way tasks are. An `AppEnvironment` names the image, the port, and the scaling behavior, and the code inside it is an ordinary web application. ```python app = flyte.app.AppEnvironment(name="dashboard", image=..., port=8080) ``` Because apps and tasks live in the same project, an app can read what a task produced without moving data between systems, and a task can call an app it depends on. Apps scale to zero when idle, so a rarely-used dashboard costs nothing between visits. ### **Apps > Configure apps** Define `AppEnvironment`s with ports, autoscaling, custom domains, and authentication. ### **Apps > Build apps** Build dashboards, REST APIs, and model endpoints with FastAPI, Streamlit, vLLM, and more. ### **Apps > Native app integrations** Use pre-built environments for popular frameworks like Streamlit, FastAPI, vLLM, SGLang, and Ollama. ### **Apps > Serve and deploy apps** Use `flyte serve` for fast iteration or `flyte deploy` for production deployments. ## Related ### **Inference** Run models from Flyte by calling a hosted provider, serving open-weight models on your own GPUs, or deploying the models your tasks train. ### **Tasks** The batch workloads an app usually serves the results of. ### **Agents** Agents are often deployed as apps so they can be reached over HTTP. ## Subpages - **Apps > Configure apps** - Define `AppEnvironment`s with ports, autoscaling, custom domains, and authentication. - **Apps > Build apps** - Build dashboards, REST APIs, and model endpoints with FastAPI, Streamlit, vLLM, and more. - **Apps > Native app integrations** - Use pre-built environments for popular frameworks like Streamlit, FastAPI, vLLM, SGLang, and Ollama. - **Apps > Serve and deploy apps** - Use `flyte serve` for fast iteration or `flyte deploy` for production deployments. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/configure-apps === Define `AppEnvironment`s with ports, autoscaling, custom domains, and authentication. # Configure apps `[[AppEnvironment]]`s allows you to configure the environment in which your app runs, including the container image, compute resources, secrets, domains, scaling behavior, and more. Similar to `[[TaskEnvironment]]`, configuration can be set when creating the `[[AppEnvironment]]` object. Unlike tasks, apps are long-running services, so they have additional configuration options specific to web services: - `port`: What port the app listens on - `command` and `args`: How to start the app - `scaling`: Autoscaling configuration for handling variable load - `domain`: Custom domains and subdomains for your app - `requires_auth`: Whether the app requires authentication to access - `depends_on`: Other app or task environments that the app depends on ## Hello World example Here's a complete example of deploying a simple Streamlit "hello world" app with a custom subdomain. There are two ways to build apps in Flyte: 1. Defining `AppEnvironment(.., args=[...])` to run the app with the underlying `fserve` command. 2. Defining `@app_env.server` to run the app with a custom server function. ### Using fserve args ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("streamlit==1.41.1") # {{/docs-fragment image}} # {{docs-fragment app-env}} app_env = flyte.app.AppEnvironment( name="hello-world-app", image=image, args=["streamlit", "hello", "--server.port", "8080"], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, domain=flyte.app.Domain(subdomain="hello"), ) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() # Deploy the app app = flyte.serve(app_env) print(f"App served at: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/hello-world-app.py* This example demonstrates: - Creating a custom Docker image with Streamlit - Setting the `args` to run the Streamlit hello app, which uses the underlying `fserve` command to run the app. - Configuring the port - Setting resource limits - Disabling authentication (for public access) - Using a custom subdomain ### Using @app_env.server ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("streamlit==1.41.1") # {{/docs-fragment image}} # {{docs-fragment app-env}} app_env = flyte.app.AppEnvironment( name="hello-world-app-server", image=image, port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, domain=flyte.app.Domain(subdomain="hello-server"), ) @app_env.server def server(): import subprocess subprocess.run(["streamlit", "hello", "--server.port", "8080"], check=False) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() # Deploy the app app = flyte.serve(app_env) print(f"App served at: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/hello-world-app-server.py* This example demonstrates: - Creating a custom Docker image with Streamlit - Using the `@app_env.server` decorator to define a server function that runs the Streamlit hello app. - Configuring the port - Setting resource limits - Disabling authentication (for public access) - Using a custom subdomain Once deployed, your app will be accessible at the generated URL or your custom subdomain. ## Differences from TaskEnvironment While `AppEnvironment` inherits from `Environment` (the same base class as `TaskEnvironment`), it has several app-specific parameters: | Parameter | AppEnvironment | TaskEnvironment | Description | |-----------|----------------|-----------------|-------------| | `type` | โœ… | โŒ | Type of app (e.g., "FastAPI", "Streamlit") | | `port` | โœ… | โŒ | Port the app listens on | | `args` | โœ… | โŒ | Arguments to pass to the app | | `command` | โœ… | โŒ | Command to run the app | | `requires_auth` | โœ… | โŒ | Whether app requires authentication | | `scaling` | โœ… | โŒ | Autoscaling configuration | | `domain` | โœ… | โŒ | Custom domain/subdomain | | `links` | โœ… | โŒ | Links to include in the App UI page | | `include` | โœ… | โŒ | Files to include in app | | `parameters` | โœ… | โŒ | Parameters to pass to app | | `cluster_pool` | โœ… | โŒ | Cluster pool for deployment | Parameters like `image`, `resources`, `secrets`, `env_vars`, and `depends_on` are shared between both environment types. See the [task configuration](../../tasks/task-configuration/_index) docs for details on these shared parameters. ## Configuration topics Learn more about configuring apps: - **Apps > Configure apps > App environment settings**: Images, resources, secrets, and app-specific settings like `type`, `port`, `args`, `requires_auth` - **Apps > Configure apps > App environment settings > App startup**: Understanding the difference between `args` and `command` - **Apps > Configure apps > Including additional files**: How to include additional files needed by your app - **Apps > Configure apps > Passing parameters into app environments**: Pass parameters to your app at deployment time - **Apps > Configure apps > /// script**: Configure scaling up and down based on traffic with idle TTL - **Apps > Configure apps > Apps depending on other environments**: Use `depends_on` to deploy dependent apps together {{< subpage-cards >}} ## Subpages - **Apps > Configure apps > App environment settings** - Control an app's image, resources, secrets, startup behavior, and autoscaling through AppEnvironment. - **Apps > Configure apps > Including additional files** - Bundle utility modules, config, and data files alongside your app script with include. - **Apps > Configure apps > Passing parameters into app environments** - Pass primitives, files, directories, and deferred values into an app at deploy time. - **Apps > Configure apps > /// script** - Scale an app up with traffic and down to nothing when idle. - **Apps > Configure apps > Apps depending on other environments** - Use depends_on so deploying an app or task environment also deploys the environments it needs. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/configure-apps/app-environment-settings === Control an app's image, resources, secrets, startup behavior, and autoscaling through AppEnvironment. # App environment settings `[[AppEnvironment]]`s control how your apps run in Flyte, including images, resources, secrets, startup behavior, and autoscaling. ## Shared environment settings `[[AppEnvironment]]`s share many configuration options with `[[TaskEnvironment]]`s: - **Images**: See **Tasks > Configure tasks > Container images** for details on creating and using container images - **Resources**: See **Tasks > Configure tasks > Resources** for CPU, memory, GPU, and storage configuration - **Secrets**: See **Tasks > Configure tasks > Secrets** for injecting secrets into your app - **Environment variables**: Set via the `env_vars` parameter (same as tasks) - **Volumes**: Mount a Volume with `pod_template=allow_volumes()`. See [Volumes in apps](../../tasks/task-programming/volumes/_index#volumes-in-apps) ## App-specific environment settings For complete parameter documentation, type signatures, and defaults, see the **Flyte SDK > flyte.app > AppEnvironment**. Key app-specific parameters include `type`, `port`, `args`, `command`, `requires_auth`, `scaling`, `domain`, `links`, `parameters`, `cluster_pool`, `cluster`, and `timeouts`. See also: - **Apps > Configure apps > Including additional files** in your app deployment - **Apps > Configure apps > Passing parameters into app environments** to your app - **Apps > Configure apps > /// script** - **Apps > Configure apps > Apps depending on other environments** ### Environment variable substitution in `args` When you use the default `fserve` command, environment variables in `args` that start with the `$` character are substituted at runtime. This works for both: - Values from `env_vars` - Secrets that are specified as environment variables (via `as_env_var` in `flyte.Secret`) The `$VARIABLE_NAME` syntax will be replaced with the actual environment variable value at runtime: ```python # Using env_vars app_env = flyte.app.AppEnvironment( name="my-app", env_vars={"API_KEY": "secret-key-123"}, args="--api-key $API_KEY", # $API_KEY will be replaced with "secret-key-123" # ... ) # Using secrets app_env = flyte.app.AppEnvironment( name="my-app", secrets=flyte.Secret(key="AUTH_SECRET", as_env_var="AUTH_SECRET"), args=["--api-key", "$AUTH_SECRET"], # $AUTH_SECRET will be replaced with the secret value # ... ) ``` This is particularly useful for passing API keys or other sensitive values to command-line arguments without hardcoding them in your code. The substitution happens at runtime, ensuring secrets are never exposed in your code or configuration files. > [!TIP] > For most `AppEnvironment`s, use `args` instead of `command` to specify the app startup command > in the container. This is because `args` will use the `fserve` command to run the app, which > enables features like local code bundling and file/directory mounting via parameter injection. ## App startup There are two ways to start up an app in Flyte: 1. With a server function using `@app_env.server` 2. As a container command using `command` or `args` ### Server decorator via `@app_env.server` The server function is a Python function that runs the app. It is defined using the `@app_env.server` decorator. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "fastapi", # "uvicorn", # "flyte>=2.0.0b52", # ] # /// import fastapi import uvicorn import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment fastapi-app}} app = fastapi.FastAPI() env = FastAPIAppEnvironment( name="configure-fastapi-example", app=app, image=flyte.Image.from_uv_script(__file__, name="configure-fastapi-example"), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, port=8080, ) @env.server def server(): print("Starting server...") uvicorn.run(app, port=8080) @app.get("/") async def root() -> dict: return {"message": "Hello from FastAPI!"} # {{/docs-fragment fastapi-app}} # {{docs-fragment on-startup-decorator}} state = {} @env.on_startup async def app_startup(): print("App started up") state["data"] = ["Here's", "some", "data"] # {{/docs-fragment on-startup-decorator}} # {{docs-fragment on-shutdown-decorator}} @env.on_shutdown async def app_shutdown(): print("App shut down") state.clear() # clears the data # {{/docs-fragment on-shutdown-decorator}} # {{docs-fragment deploy}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) deployed_app = flyte.serve(env) print(f"App served at: {deployed_app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/fastapi-server-example.py* The `@app_env.server` decorator allows you to define a synchronous or asynchronous function that runs the app, either with a server start command like `uvicorn.run`, [`HTTPServer.serve_forever`](https://docs.python.org/3/library/http.server.html), etc. > [!NOTE] > Generally the `[[FastAPIAppEnvironment]]` handles serving automatically under the hood, > the example above just shows how the `@app_env.server` decorator can be used to define a server function > that runs the app. #### Startup hook The startup hook runs before the server function is called. It is defined using the `@app_env.on_startup` decorator. This is useful if you need to load any state or external connections needed to run the app before it starts. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "fastapi", # "uvicorn", # "flyte>=2.0.0b52", # ] # /// import fastapi import uvicorn import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment fastapi-app}} app = fastapi.FastAPI() env = FastAPIAppEnvironment( name="configure-fastapi-example", app=app, image=flyte.Image.from_uv_script(__file__, name="configure-fastapi-example"), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, port=8080, ) @env.server def server(): print("Starting server...") uvicorn.run(app, port=8080) @app.get("/") async def root() -> dict: return {"message": "Hello from FastAPI!"} # {{/docs-fragment fastapi-app}} # {{docs-fragment on-startup-decorator}} state = {} @env.on_startup async def app_startup(): print("App started up") state["data"] = ["Here's", "some", "data"] # {{/docs-fragment on-startup-decorator}} # {{docs-fragment on-shutdown-decorator}} @env.on_shutdown async def app_shutdown(): print("App shut down") state.clear() # clears the data # {{/docs-fragment on-shutdown-decorator}} # {{docs-fragment deploy}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) deployed_app = flyte.serve(env) print(f"App served at: {deployed_app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/fastapi-server-example.py* #### Shutdown hook The shutdown hook is called before the app instance shuts down during scale down. It is defined using the `@app_env.on_shutdown` decorator. This is useful if you need to clean up any state or external connections in the container running the app. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "fastapi", # "uvicorn", # "flyte>=2.0.0b52", # ] # /// import fastapi import uvicorn import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment fastapi-app}} app = fastapi.FastAPI() env = FastAPIAppEnvironment( name="configure-fastapi-example", app=app, image=flyte.Image.from_uv_script(__file__, name="configure-fastapi-example"), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, port=8080, ) @env.server def server(): print("Starting server...") uvicorn.run(app, port=8080) @app.get("/") async def root() -> dict: return {"message": "Hello from FastAPI!"} # {{/docs-fragment fastapi-app}} # {{docs-fragment on-startup-decorator}} state = {} @env.on_startup async def app_startup(): print("App started up") state["data"] = ["Here's", "some", "data"] # {{/docs-fragment on-startup-decorator}} # {{docs-fragment on-shutdown-decorator}} @env.on_shutdown async def app_shutdown(): print("App shut down") state.clear() # clears the data # {{/docs-fragment on-shutdown-decorator}} # {{docs-fragment deploy}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) deployed_app = flyte.serve(env) print(f"App served at: {deployed_app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/fastapi-server-example.py* ### Container command via `command` vs `args` The difference between `args` and `command` is crucial for properly configuring how your app starts. - **`command`**: The full command to run your app, for example, `"streamlit hello --server.port 8080"`. For most use cases, you don't need to specify `command` as it's automatically configured, and uses the `fserve` executable to run the app. `fserve` does additional setup for you, like setting up the code bundle and loading **Apps > Configure apps > Passing parameters into app environments** if provided, so it's highly recommended to use the default command. - **`args`**: Arguments to pass to your app's command (used with the default Flyte command or your custom command). The `fserve` executable takes in additional arguments, which you can specify as the arguments needed to run your app, for example, `streamlit run main.py --server.port 8080`. #### Default startup behavior When you don't specify a `command`, Flyte generates a default command that uses `fserve` to run your app. This default command handles: - Setting up the code bundle - Configuring the version - Setting up project/domain context - Injecting parameters if provided The default command looks like: ```bash fserve --version --project --domain -- ``` So if you specify `args`, they'll be appended after the `--` separator. #### Using args with the default command When you use `args` without specifying `command`, the args are passed to the default Flyte command: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "fastapi", # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment args-with-default-command}} # Using args with default command app_env = flyte.app.AppEnvironment( name="streamlit-app", args="streamlit run main.py --server.port 8080", port=8080, include=["main.py"], # command is None, so default Flyte command is used ) # {{/docs-fragment args-with-default-command}} # {{docs-fragment explicit-command}} # Using explicit command app_env2 = flyte.app.AppEnvironment( name="streamlit-hello", command="streamlit hello --server.port 8080", port=8080, # No args needed since command includes everything ) # {{/docs-fragment explicit-command}} # {{docs-fragment command-with-args}} # Using command with args app_env3 = flyte.app.AppEnvironment( name="custom-app", command="python -m myapp", args="--option1 value1 --option2 value2", # This runs: python -m myapp --option1 value1 --option2 value2 ) # {{/docs-fragment command-with-args}} # {{docs-fragment fastapi-auto-command}} from flyte.app.extras import FastAPIAppEnvironment from fastapi import FastAPI app = FastAPI() # FastAPIAppEnvironment serves the app with uvicorn; no command or args needed env = FastAPIAppEnvironment( name="my-api", app=app, ) # {{/docs-fragment fastapi-auto-command}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/app-startup-examples.py* This effectively runs: ```bash fserve --version ... --project ... --domain ... -- streamlit run main.py --server.port 8080 ``` #### Using an explicit command When you specify a `command`, it completely replaces the default command: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "fastapi", # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment args-with-default-command}} # Using args with default command app_env = flyte.app.AppEnvironment( name="streamlit-app", args="streamlit run main.py --server.port 8080", port=8080, include=["main.py"], # command is None, so default Flyte command is used ) # {{/docs-fragment args-with-default-command}} # {{docs-fragment explicit-command}} # Using explicit command app_env2 = flyte.app.AppEnvironment( name="streamlit-hello", command="streamlit hello --server.port 8080", port=8080, # No args needed since command includes everything ) # {{/docs-fragment explicit-command}} # {{docs-fragment command-with-args}} # Using command with args app_env3 = flyte.app.AppEnvironment( name="custom-app", command="python -m myapp", args="--option1 value1 --option2 value2", # This runs: python -m myapp --option1 value1 --option2 value2 ) # {{/docs-fragment command-with-args}} # {{docs-fragment fastapi-auto-command}} from flyte.app.extras import FastAPIAppEnvironment from fastapi import FastAPI app = FastAPI() # FastAPIAppEnvironment serves the app with uvicorn; no command or args needed env = FastAPIAppEnvironment( name="my-api", app=app, ) # {{/docs-fragment fastapi-auto-command}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/app-startup-examples.py* This runs exactly: ```bash streamlit hello --server.port 8080 ``` #### Using a command with args You can combine both, though this is less common: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "fastapi", # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment args-with-default-command}} # Using args with default command app_env = flyte.app.AppEnvironment( name="streamlit-app", args="streamlit run main.py --server.port 8080", port=8080, include=["main.py"], # command is None, so default Flyte command is used ) # {{/docs-fragment args-with-default-command}} # {{docs-fragment explicit-command}} # Using explicit command app_env2 = flyte.app.AppEnvironment( name="streamlit-hello", command="streamlit hello --server.port 8080", port=8080, # No args needed since command includes everything ) # {{/docs-fragment explicit-command}} # {{docs-fragment command-with-args}} # Using command with args app_env3 = flyte.app.AppEnvironment( name="custom-app", command="python -m myapp", args="--option1 value1 --option2 value2", # This runs: python -m myapp --option1 value1 --option2 value2 ) # {{/docs-fragment command-with-args}} # {{docs-fragment fastapi-auto-command}} from flyte.app.extras import FastAPIAppEnvironment from fastapi import FastAPI app = FastAPI() # FastAPIAppEnvironment serves the app with uvicorn; no command or args needed env = FastAPIAppEnvironment( name="my-api", app=app, ) # {{/docs-fragment fastapi-auto-command}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/app-startup-examples.py* #### FastAPIAppEnvironment example When using `FastAPIAppEnvironment`, you don't need to set `command` or `args`. The app runs with the default `fserve` command, which serves your FastAPI app with uvicorn: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "fastapi", # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment args-with-default-command}} # Using args with default command app_env = flyte.app.AppEnvironment( name="streamlit-app", args="streamlit run main.py --server.port 8080", port=8080, include=["main.py"], # command is None, so default Flyte command is used ) # {{/docs-fragment args-with-default-command}} # {{docs-fragment explicit-command}} # Using explicit command app_env2 = flyte.app.AppEnvironment( name="streamlit-hello", command="streamlit hello --server.port 8080", port=8080, # No args needed since command includes everything ) # {{/docs-fragment explicit-command}} # {{docs-fragment command-with-args}} # Using command with args app_env3 = flyte.app.AppEnvironment( name="custom-app", command="python -m myapp", args="--option1 value1 --option2 value2", # This runs: python -m myapp --option1 value1 --option2 value2 ) # {{/docs-fragment command-with-args}} # {{docs-fragment fastapi-auto-command}} from flyte.app.extras import FastAPIAppEnvironment from fastapi import FastAPI app = FastAPI() # FastAPIAppEnvironment serves the app with uvicorn; no command or args needed env = FastAPIAppEnvironment( name="my-api", app=app, ) # {{/docs-fragment fastapi-auto-command}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/app-startup-examples.py* The `FastAPIAppEnvironment` automatically: 1. Uses an internal server function to start the app with `uvicorn.Server(...).serve()`. 2. Handles all the startup configuration for you ## Shared settings For more details on shared settings like images, resources, and secrets, refer to the [task configuration](../../tasks/task-configuration/_index) documentation. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/configure-apps/including-additional-files === Bundle utility modules, config, and data files alongside your app script with include. # Including additional files When your app needs additional files beyond the main script (like utility modules, configuration files, or data files), you can use the `include` parameter to specify which files to bundle with your app. ## How include works The `include` parameter takes a list of file paths (relative to the directory containing your app definition). These files are bundled together and made available in the app container at runtime. ```python include=["main.py", "utils.py", "config.yaml"] ``` ## When to use include Use `include` when: - Your app spans multiple Python files (modules) - You have configuration files that your app needs - You have data files or templates your app uses - You want to ensure specific files are available in the container > [!NOTE] > If you're using specialized app environments like `FastAPIAppEnvironment`, Flyte automatically detects and includes the necessary files, so you may not need to specify `include` explicitly. ## Examples ### Multi-file Streamlit app ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A custom Streamlit app with multiple files.""" import pathlib import flyte import flyte.app # {{docs-fragment app-env}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit==1.41.1", "pandas==2.2.3", "numpy==2.2.3", ) app_env = flyte.app.AppEnvironment( name="streamlit-multi-file-app", image=image, args="streamlit run main.py --server.port 8080", port=8080, include=["main.py", "utils.py"], # Include your app files resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app = flyte.deploy(app_env) print(f"Deployed app: {app[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/multi_file_streamlit.py* In this example: - `main.py` is your main Streamlit app file - `utils.py` contains helper functions used by `main.py` - Both files are included in the app bundle ### Multi-file FastAPI app ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """Multi-file FastAPI app example.""" from fastapi import FastAPI from module import function # Import from another file import pathlib import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment app-definition}} app = FastAPI(title="Multi-file FastAPI Demo") app_env = FastAPIAppEnvironment( name="fastapi-multi-file", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, # FastAPIAppEnvironment automatically includes necessary files # But you can also specify explicitly: # include=["app.py", "module.py"], ) # {{/docs-fragment app-definition}} # {{docs-fragment endpoint}} @app.get("/") async def root(): return function() # Uses function from module.py # {{/docs-fragment endpoint}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(app_env) print(f"Deployed: {app_deployment[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/multi_file/app.py* ### App with configuration files ```python include=["app.py", "config.yaml", "templates/"] ``` ## File discovery When using specialized app environments like `FastAPIAppEnvironment`, Flyte uses code introspection to automatically discover and include the necessary files. This means you often don't need to manually specify `include`. However, if you have files that aren't automatically detected (like configuration files, data files, or templates), you should explicitly list them in `include`. ## Path resolution Files in `include` are resolved relative to the directory containing your app definition file. For example: ``` project/ โ”œโ”€โ”€ apps/ โ”‚ โ”œโ”€โ”€ app.py # Your app definition โ”‚ โ”œโ”€โ”€ utils.py # Included file โ”‚ โ””โ”€โ”€ config.yaml # Included file ``` In `app.py`: ```python include=["utils.py", "config.yaml"] # Relative to apps/ directory ``` ## Best practices 1. **Only include what you need**: Don't include unnecessary files as it increases bundle size 2. **Use relative paths**: Always use paths relative to your app definition file 3. **Include directories**: You can include entire directories, but be mindful of size 4. **Test locally**: Verify your includes work by testing locally before deploying 5. **Check automatic discovery**: Specialized app environments may already include files automatically ## Limitations - Large files or directories can slow down deployment - Binary files are supported but consider using data storage (S3, etc.) for very large files - The bundle size is limited by your Flyte cluster configuration === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/configure-apps/passing-parameters === Pass primitives, files, directories, and deferred values into an app at deploy time. # Passing parameters into app environments `[[AppEnvironment]]`s support various parameter types that can be passed at deployment time. This includes primitive values, files, directories, and delayed values like `RunOutput` and `AppEndpoint`. ## Parameter types overview There are several parameter types: - **Primitive values**: Strings, numbers, booleans - **Files**: `flyte.io.File` objects (use `flyte.io.File.from_existing_remote(...)` for remote files) - **Directories**: `flyte.io.Dir` objects (use `flyte.io.Dir.from_existing_remote(...)` for remote directories) - **Delayed values**: `RunOutput` (from task runs) or `AppEndpoint` (inject endpoint urls of other apps) ## Basic parameter types ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "scikit-learn", # "joblib", # ] # /// """Examples showing different ways to pass parameters into apps.""" import os import flyte import flyte.app import flyte.io from flyte.app import Parameter, get_parameter # {{docs-fragment basic-parameter-types}} # String parameters app_env = flyte.app.AppEnvironment( name="configurable-app", parameters=[ Parameter(name="environment", value="production"), Parameter(name="log_level", value="INFO"), ], # ... ) # File parameters app_env2 = flyte.app.AppEnvironment( name="app-with-model", parameters=[ Parameter( name="model_file", value=flyte.io.File.from_existing_remote("s3://bucket/models/model.pkl"), mount="/app/models/", ), ], # ... ) # Directory parameters app_env3 = flyte.app.AppEnvironment( name="app-with-data", parameters=[ Parameter( name="data_dir", value=flyte.io.Dir.from_existing_remote("s3://bucket/data/"), mount="/app/data", ), ], # ... ) # {{/docs-fragment basic-parameter-types}} # {{docs-fragment parameter-access-methods}} from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment DATA_MOUNT_PATH = "/tmp/data_file.txt" DATA_ENV_VAR = "DATA_FILE_PATH" demo_app = FastAPI() demo_env = FastAPIAppEnvironment( name="parameter-access-demo", app=demo_app, parameters=[ # With mount and env_var: the file is downloaded to the mount path, # and an environment variable is set to point to the file location. Parameter( name="data", type="file", mount=DATA_MOUNT_PATH, env_var=DATA_ENV_VAR, ), # With no mount or env_var: accessible only via get_parameter, # which returns the path to the downloaded file. Parameter(name="data_raw", type="file"), ], # ... ) @demo_app.get("/from-mount") def read_from_mount() -> dict: """Access the file directly at the mount path.""" with open(DATA_MOUNT_PATH, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-env-var") def read_from_env_var() -> dict: """Access the file through its environment variable.""" data_path = os.environ[DATA_ENV_VAR] with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-get-parameter") def read_from_get_parameter() -> dict: """Access the file using the get_parameter helper.""" data_path = get_parameter("data") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/raw") def read_raw() -> dict: """Access a parameter that has no mount or env_var.""" data_path = get_parameter("data_raw") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} # {{/docs-fragment parameter-access-methods}} # {{docs-fragment parameter-serve-override}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) app_handle = flyte.with_servecontext( parameter_values={ demo_env.name: { "data": flyte.io.File.from_existing_remote("s3://bucket/data.txt"), "data_raw": flyte.io.File.from_existing_remote("s3://bucket/raw.txt"), } } ).serve(demo_env) print(f"Deployed app: {app_handle.url}") # {{/docs-fragment parameter-serve-override}} # {{docs-fragment runoutput-example}} env = flyte.TaskEnvironment(name="training-env") @env.task async def train_model() -> flyte.io.File: # ... training logic ... return await flyte.io.File.from_local("/tmp/trained-model.pkl") app_env4 = flyte.app.AppEnvironment( name="serving-app", parameters=[ Parameter( name="model", value=flyte.app.RunOutput(type="file", task_name="training-env.train_model"), mount="/app/model", ), ], # ... ) # {{/docs-fragment runoutput-example}} # {{docs-fragment appendpoint-example}} app1_env = flyte.app.AppEnvironment(name="backend-api") app2_env = flyte.app.AppEnvironment( name="frontend-app", parameters=[ Parameter( name="backend_url", value=flyte.app.AppEndpoint(app_name="backend-api"), env_var="BACKEND_URL", ), ], # ... ) # {{/docs-fragment appendpoint-example}} # {{docs-fragment runoutput-serving-example}} import joblib from sklearn.ensemble import RandomForestClassifier training_env = flyte.TaskEnvironment(name="training-env") @training_env.task async def train_model_task() -> flyte.io.File: """Train a model and return it.""" model = RandomForestClassifier() # ... training logic ... path = "./trained-model.pkl" joblib.dump(model, path) return await flyte.io.File.from_local(path) serving_app = FastAPI() model_serving_env = FastAPIAppEnvironment( name="model-serving-app", app=serving_app, parameters=[ Parameter( name="model", value=flyte.app.RunOutput( type="file", task_name="training-env.train_model_task", ), mount="/app/model", env_var="MODEL_PATH", ), ], ) # {{/docs-fragment runoutput-serving-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/passing-parameters-examples.py* > [!WARNING] > Do not use `flyte.io.File(...)` or `flyte.io.Dir(...)` directly as parameter values. > Use `flyte.io.File.from_existing_remote(...)` and `flyte.io.Dir.from_existing_remote(...)` to > reference existing remote files and directories. ## Accessing parameters in your app There are three ways to access parameter values at runtime: **mount paths**, **environment variables**, and the **`get_parameter` helper function**. ### `mount` When `mount` is specified on a `Parameter`, the file or directory is downloaded to the given path. If the mount path ends with a `/`, the file is placed inside that directory with its original name. Otherwise, the file is downloaded to the exact path specified. Your app reads directly from the mount path: ```python with open("/tmp/data_file.txt", "rb") as fh: contents = fh.read() ``` ### `env_var` When `env_var` is specified, an environment variable is set containing the path to the downloaded file or directory. This is useful when you want your app code to be decoupled from specific mount paths: ```python import os data_path = os.environ["DATA_FILE_PATH"] with open(data_path, "rb") as fh: contents = fh.read() ``` ### `get_parameter` The `get_parameter(name)` helper function from `flyte.app` returns the path to the downloaded file or the string value of the parameter. This works regardless of whether `mount` or `env_var` are specified and is the most flexible access method: ```python from flyte.app import get_parameter data_path = get_parameter("data") with open(data_path, "rb") as fh: contents = fh.read() ``` When a parameter has no `mount` or `env_var` configured, `get_parameter` is the only way to access its value at runtime. ### Full example The following example defines a FastAPI app with parameters using all three access methods: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "scikit-learn", # "joblib", # ] # /// """Examples showing different ways to pass parameters into apps.""" import os import flyte import flyte.app import flyte.io from flyte.app import Parameter, get_parameter # {{docs-fragment basic-parameter-types}} # String parameters app_env = flyte.app.AppEnvironment( name="configurable-app", parameters=[ Parameter(name="environment", value="production"), Parameter(name="log_level", value="INFO"), ], # ... ) # File parameters app_env2 = flyte.app.AppEnvironment( name="app-with-model", parameters=[ Parameter( name="model_file", value=flyte.io.File.from_existing_remote("s3://bucket/models/model.pkl"), mount="/app/models/", ), ], # ... ) # Directory parameters app_env3 = flyte.app.AppEnvironment( name="app-with-data", parameters=[ Parameter( name="data_dir", value=flyte.io.Dir.from_existing_remote("s3://bucket/data/"), mount="/app/data", ), ], # ... ) # {{/docs-fragment basic-parameter-types}} # {{docs-fragment parameter-access-methods}} from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment DATA_MOUNT_PATH = "/tmp/data_file.txt" DATA_ENV_VAR = "DATA_FILE_PATH" demo_app = FastAPI() demo_env = FastAPIAppEnvironment( name="parameter-access-demo", app=demo_app, parameters=[ # With mount and env_var: the file is downloaded to the mount path, # and an environment variable is set to point to the file location. Parameter( name="data", type="file", mount=DATA_MOUNT_PATH, env_var=DATA_ENV_VAR, ), # With no mount or env_var: accessible only via get_parameter, # which returns the path to the downloaded file. Parameter(name="data_raw", type="file"), ], # ... ) @demo_app.get("/from-mount") def read_from_mount() -> dict: """Access the file directly at the mount path.""" with open(DATA_MOUNT_PATH, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-env-var") def read_from_env_var() -> dict: """Access the file through its environment variable.""" data_path = os.environ[DATA_ENV_VAR] with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-get-parameter") def read_from_get_parameter() -> dict: """Access the file using the get_parameter helper.""" data_path = get_parameter("data") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/raw") def read_raw() -> dict: """Access a parameter that has no mount or env_var.""" data_path = get_parameter("data_raw") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} # {{/docs-fragment parameter-access-methods}} # {{docs-fragment parameter-serve-override}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) app_handle = flyte.with_servecontext( parameter_values={ demo_env.name: { "data": flyte.io.File.from_existing_remote("s3://bucket/data.txt"), "data_raw": flyte.io.File.from_existing_remote("s3://bucket/raw.txt"), } } ).serve(demo_env) print(f"Deployed app: {app_handle.url}") # {{/docs-fragment parameter-serve-override}} # {{docs-fragment runoutput-example}} env = flyte.TaskEnvironment(name="training-env") @env.task async def train_model() -> flyte.io.File: # ... training logic ... return await flyte.io.File.from_local("/tmp/trained-model.pkl") app_env4 = flyte.app.AppEnvironment( name="serving-app", parameters=[ Parameter( name="model", value=flyte.app.RunOutput(type="file", task_name="training-env.train_model"), mount="/app/model", ), ], # ... ) # {{/docs-fragment runoutput-example}} # {{docs-fragment appendpoint-example}} app1_env = flyte.app.AppEnvironment(name="backend-api") app2_env = flyte.app.AppEnvironment( name="frontend-app", parameters=[ Parameter( name="backend_url", value=flyte.app.AppEndpoint(app_name="backend-api"), env_var="BACKEND_URL", ), ], # ... ) # {{/docs-fragment appendpoint-example}} # {{docs-fragment runoutput-serving-example}} import joblib from sklearn.ensemble import RandomForestClassifier training_env = flyte.TaskEnvironment(name="training-env") @training_env.task async def train_model_task() -> flyte.io.File: """Train a model and return it.""" model = RandomForestClassifier() # ... training logic ... path = "./trained-model.pkl" joblib.dump(model, path) return await flyte.io.File.from_local(path) serving_app = FastAPI() model_serving_env = FastAPIAppEnvironment( name="model-serving-app", app=serving_app, parameters=[ Parameter( name="model", value=flyte.app.RunOutput( type="file", task_name="training-env.train_model_task", ), mount="/app/model", env_var="MODEL_PATH", ), ], ) # {{/docs-fragment runoutput-serving-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/passing-parameters-examples.py* ## Delayed values Delayed values are parameters whose actual values are materialized at deployment time. ### RunOutput Use `RunOutput` to pass outputs from task runs as app parameters: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "scikit-learn", # "joblib", # ] # /// """Examples showing different ways to pass parameters into apps.""" import os import flyte import flyte.app import flyte.io from flyte.app import Parameter, get_parameter # {{docs-fragment basic-parameter-types}} # String parameters app_env = flyte.app.AppEnvironment( name="configurable-app", parameters=[ Parameter(name="environment", value="production"), Parameter(name="log_level", value="INFO"), ], # ... ) # File parameters app_env2 = flyte.app.AppEnvironment( name="app-with-model", parameters=[ Parameter( name="model_file", value=flyte.io.File.from_existing_remote("s3://bucket/models/model.pkl"), mount="/app/models/", ), ], # ... ) # Directory parameters app_env3 = flyte.app.AppEnvironment( name="app-with-data", parameters=[ Parameter( name="data_dir", value=flyte.io.Dir.from_existing_remote("s3://bucket/data/"), mount="/app/data", ), ], # ... ) # {{/docs-fragment basic-parameter-types}} # {{docs-fragment parameter-access-methods}} from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment DATA_MOUNT_PATH = "/tmp/data_file.txt" DATA_ENV_VAR = "DATA_FILE_PATH" demo_app = FastAPI() demo_env = FastAPIAppEnvironment( name="parameter-access-demo", app=demo_app, parameters=[ # With mount and env_var: the file is downloaded to the mount path, # and an environment variable is set to point to the file location. Parameter( name="data", type="file", mount=DATA_MOUNT_PATH, env_var=DATA_ENV_VAR, ), # With no mount or env_var: accessible only via get_parameter, # which returns the path to the downloaded file. Parameter(name="data_raw", type="file"), ], # ... ) @demo_app.get("/from-mount") def read_from_mount() -> dict: """Access the file directly at the mount path.""" with open(DATA_MOUNT_PATH, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-env-var") def read_from_env_var() -> dict: """Access the file through its environment variable.""" data_path = os.environ[DATA_ENV_VAR] with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-get-parameter") def read_from_get_parameter() -> dict: """Access the file using the get_parameter helper.""" data_path = get_parameter("data") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/raw") def read_raw() -> dict: """Access a parameter that has no mount or env_var.""" data_path = get_parameter("data_raw") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} # {{/docs-fragment parameter-access-methods}} # {{docs-fragment parameter-serve-override}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) app_handle = flyte.with_servecontext( parameter_values={ demo_env.name: { "data": flyte.io.File.from_existing_remote("s3://bucket/data.txt"), "data_raw": flyte.io.File.from_existing_remote("s3://bucket/raw.txt"), } } ).serve(demo_env) print(f"Deployed app: {app_handle.url}") # {{/docs-fragment parameter-serve-override}} # {{docs-fragment runoutput-example}} env = flyte.TaskEnvironment(name="training-env") @env.task async def train_model() -> flyte.io.File: # ... training logic ... return await flyte.io.File.from_local("/tmp/trained-model.pkl") app_env4 = flyte.app.AppEnvironment( name="serving-app", parameters=[ Parameter( name="model", value=flyte.app.RunOutput(type="file", task_name="training-env.train_model"), mount="/app/model", ), ], # ... ) # {{/docs-fragment runoutput-example}} # {{docs-fragment appendpoint-example}} app1_env = flyte.app.AppEnvironment(name="backend-api") app2_env = flyte.app.AppEnvironment( name="frontend-app", parameters=[ Parameter( name="backend_url", value=flyte.app.AppEndpoint(app_name="backend-api"), env_var="BACKEND_URL", ), ], # ... ) # {{/docs-fragment appendpoint-example}} # {{docs-fragment runoutput-serving-example}} import joblib from sklearn.ensemble import RandomForestClassifier training_env = flyte.TaskEnvironment(name="training-env") @training_env.task async def train_model_task() -> flyte.io.File: """Train a model and return it.""" model = RandomForestClassifier() # ... training logic ... path = "./trained-model.pkl" joblib.dump(model, path) return await flyte.io.File.from_local(path) serving_app = FastAPI() model_serving_env = FastAPIAppEnvironment( name="model-serving-app", app=serving_app, parameters=[ Parameter( name="model", value=flyte.app.RunOutput( type="file", task_name="training-env.train_model_task", ), mount="/app/model", env_var="MODEL_PATH", ), ], ) # {{/docs-fragment runoutput-serving-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/passing-parameters-examples.py* The `type` argument is required and must be one of `string`, `file`, or `directory`. When the app is deployed, it will make the remote calls needed to figure out the actual value of the parameter. ### AppEndpoint Use `AppEndpoint` to pass endpoints from other apps: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "scikit-learn", # "joblib", # ] # /// """Examples showing different ways to pass parameters into apps.""" import os import flyte import flyte.app import flyte.io from flyte.app import Parameter, get_parameter # {{docs-fragment basic-parameter-types}} # String parameters app_env = flyte.app.AppEnvironment( name="configurable-app", parameters=[ Parameter(name="environment", value="production"), Parameter(name="log_level", value="INFO"), ], # ... ) # File parameters app_env2 = flyte.app.AppEnvironment( name="app-with-model", parameters=[ Parameter( name="model_file", value=flyte.io.File.from_existing_remote("s3://bucket/models/model.pkl"), mount="/app/models/", ), ], # ... ) # Directory parameters app_env3 = flyte.app.AppEnvironment( name="app-with-data", parameters=[ Parameter( name="data_dir", value=flyte.io.Dir.from_existing_remote("s3://bucket/data/"), mount="/app/data", ), ], # ... ) # {{/docs-fragment basic-parameter-types}} # {{docs-fragment parameter-access-methods}} from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment DATA_MOUNT_PATH = "/tmp/data_file.txt" DATA_ENV_VAR = "DATA_FILE_PATH" demo_app = FastAPI() demo_env = FastAPIAppEnvironment( name="parameter-access-demo", app=demo_app, parameters=[ # With mount and env_var: the file is downloaded to the mount path, # and an environment variable is set to point to the file location. Parameter( name="data", type="file", mount=DATA_MOUNT_PATH, env_var=DATA_ENV_VAR, ), # With no mount or env_var: accessible only via get_parameter, # which returns the path to the downloaded file. Parameter(name="data_raw", type="file"), ], # ... ) @demo_app.get("/from-mount") def read_from_mount() -> dict: """Access the file directly at the mount path.""" with open(DATA_MOUNT_PATH, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-env-var") def read_from_env_var() -> dict: """Access the file through its environment variable.""" data_path = os.environ[DATA_ENV_VAR] with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-get-parameter") def read_from_get_parameter() -> dict: """Access the file using the get_parameter helper.""" data_path = get_parameter("data") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/raw") def read_raw() -> dict: """Access a parameter that has no mount or env_var.""" data_path = get_parameter("data_raw") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} # {{/docs-fragment parameter-access-methods}} # {{docs-fragment parameter-serve-override}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) app_handle = flyte.with_servecontext( parameter_values={ demo_env.name: { "data": flyte.io.File.from_existing_remote("s3://bucket/data.txt"), "data_raw": flyte.io.File.from_existing_remote("s3://bucket/raw.txt"), } } ).serve(demo_env) print(f"Deployed app: {app_handle.url}") # {{/docs-fragment parameter-serve-override}} # {{docs-fragment runoutput-example}} env = flyte.TaskEnvironment(name="training-env") @env.task async def train_model() -> flyte.io.File: # ... training logic ... return await flyte.io.File.from_local("/tmp/trained-model.pkl") app_env4 = flyte.app.AppEnvironment( name="serving-app", parameters=[ Parameter( name="model", value=flyte.app.RunOutput(type="file", task_name="training-env.train_model"), mount="/app/model", ), ], # ... ) # {{/docs-fragment runoutput-example}} # {{docs-fragment appendpoint-example}} app1_env = flyte.app.AppEnvironment(name="backend-api") app2_env = flyte.app.AppEnvironment( name="frontend-app", parameters=[ Parameter( name="backend_url", value=flyte.app.AppEndpoint(app_name="backend-api"), env_var="BACKEND_URL", ), ], # ... ) # {{/docs-fragment appendpoint-example}} # {{docs-fragment runoutput-serving-example}} import joblib from sklearn.ensemble import RandomForestClassifier training_env = flyte.TaskEnvironment(name="training-env") @training_env.task async def train_model_task() -> flyte.io.File: """Train a model and return it.""" model = RandomForestClassifier() # ... training logic ... path = "./trained-model.pkl" joblib.dump(model, path) return await flyte.io.File.from_local(path) serving_app = FastAPI() model_serving_env = FastAPIAppEnvironment( name="model-serving-app", app=serving_app, parameters=[ Parameter( name="model", value=flyte.app.RunOutput( type="file", task_name="training-env.train_model_task", ), mount="/app/model", env_var="MODEL_PATH", ), ], ) # {{/docs-fragment runoutput-serving-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/passing-parameters-examples.py* The endpoint URL will be injected as the parameter value when the app starts. This is particularly useful when you want to chain apps together (for example, a frontend app calling a backend app), without hardcoding URLs. ## Overriding parameters at serve time You can override parameter values when serving apps using `parameter_values` in `flyte.with_servecontext`. File and directory values must use `from_existing_remote`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "scikit-learn", # "joblib", # ] # /// """Examples showing different ways to pass parameters into apps.""" import os import flyte import flyte.app import flyte.io from flyte.app import Parameter, get_parameter # {{docs-fragment basic-parameter-types}} # String parameters app_env = flyte.app.AppEnvironment( name="configurable-app", parameters=[ Parameter(name="environment", value="production"), Parameter(name="log_level", value="INFO"), ], # ... ) # File parameters app_env2 = flyte.app.AppEnvironment( name="app-with-model", parameters=[ Parameter( name="model_file", value=flyte.io.File.from_existing_remote("s3://bucket/models/model.pkl"), mount="/app/models/", ), ], # ... ) # Directory parameters app_env3 = flyte.app.AppEnvironment( name="app-with-data", parameters=[ Parameter( name="data_dir", value=flyte.io.Dir.from_existing_remote("s3://bucket/data/"), mount="/app/data", ), ], # ... ) # {{/docs-fragment basic-parameter-types}} # {{docs-fragment parameter-access-methods}} from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment DATA_MOUNT_PATH = "/tmp/data_file.txt" DATA_ENV_VAR = "DATA_FILE_PATH" demo_app = FastAPI() demo_env = FastAPIAppEnvironment( name="parameter-access-demo", app=demo_app, parameters=[ # With mount and env_var: the file is downloaded to the mount path, # and an environment variable is set to point to the file location. Parameter( name="data", type="file", mount=DATA_MOUNT_PATH, env_var=DATA_ENV_VAR, ), # With no mount or env_var: accessible only via get_parameter, # which returns the path to the downloaded file. Parameter(name="data_raw", type="file"), ], # ... ) @demo_app.get("/from-mount") def read_from_mount() -> dict: """Access the file directly at the mount path.""" with open(DATA_MOUNT_PATH, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-env-var") def read_from_env_var() -> dict: """Access the file through its environment variable.""" data_path = os.environ[DATA_ENV_VAR] with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-get-parameter") def read_from_get_parameter() -> dict: """Access the file using the get_parameter helper.""" data_path = get_parameter("data") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/raw") def read_raw() -> dict: """Access a parameter that has no mount or env_var.""" data_path = get_parameter("data_raw") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} # {{/docs-fragment parameter-access-methods}} # {{docs-fragment parameter-serve-override}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) app_handle = flyte.with_servecontext( parameter_values={ demo_env.name: { "data": flyte.io.File.from_existing_remote("s3://bucket/data.txt"), "data_raw": flyte.io.File.from_existing_remote("s3://bucket/raw.txt"), } } ).serve(demo_env) print(f"Deployed app: {app_handle.url}") # {{/docs-fragment parameter-serve-override}} # {{docs-fragment runoutput-example}} env = flyte.TaskEnvironment(name="training-env") @env.task async def train_model() -> flyte.io.File: # ... training logic ... return await flyte.io.File.from_local("/tmp/trained-model.pkl") app_env4 = flyte.app.AppEnvironment( name="serving-app", parameters=[ Parameter( name="model", value=flyte.app.RunOutput(type="file", task_name="training-env.train_model"), mount="/app/model", ), ], # ... ) # {{/docs-fragment runoutput-example}} # {{docs-fragment appendpoint-example}} app1_env = flyte.app.AppEnvironment(name="backend-api") app2_env = flyte.app.AppEnvironment( name="frontend-app", parameters=[ Parameter( name="backend_url", value=flyte.app.AppEndpoint(app_name="backend-api"), env_var="BACKEND_URL", ), ], # ... ) # {{/docs-fragment appendpoint-example}} # {{docs-fragment runoutput-serving-example}} import joblib from sklearn.ensemble import RandomForestClassifier training_env = flyte.TaskEnvironment(name="training-env") @training_env.task async def train_model_task() -> flyte.io.File: """Train a model and return it.""" model = RandomForestClassifier() # ... training logic ... path = "./trained-model.pkl" joblib.dump(model, path) return await flyte.io.File.from_local(path) serving_app = FastAPI() model_serving_env = FastAPIAppEnvironment( name="model-serving-app", app=serving_app, parameters=[ Parameter( name="model", value=flyte.app.RunOutput( type="file", task_name="training-env.train_model_task", ), mount="/app/model", env_var="MODEL_PATH", ), ], ) # {{/docs-fragment runoutput-serving-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/passing-parameters-examples.py* > [!NOTE] > Parameter overrides are only available when using `flyte.with_servecontext().serve()`. > The `flyte.deploy()` function does not support parameter overrides. Parameters must be specified in the `AppEnvironment` definition. This is useful for: - Testing different configurations during development - Using different models or data sources for testing - A/B testing different app configurations ## Example: FastAPI app with configurable model Here's a complete example showing how to use parameters in a FastAPI app: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "fastapi", # "uvicorn", # "joblib", # "scikit-learn", # "flyte>=2.0.0b52", # ] # /// from contextlib import asynccontextmanager from pathlib import Path import flyte import flyte.app import flyte.io from flyte.app.extras import FastAPIAppEnvironment from fastapi import FastAPI # {{docs-fragment model-serving-api}} image = flyte.Image.from_uv_script(__file__, name="app-parameters-fastapi-example") task_env = flyte.TaskEnvironment( name="model_serving_task", image=image, resources=flyte.Resources(cpu=2, memory="1Gi"), cache="auto", ) @task_env.task async def train_model_task() -> flyte.io.File: """Train a model and return it.""" import joblib import sklearn.ensemble import sklearn.datasets X, y = sklearn.datasets.make_classification(n_samples=1000, n_features=5, n_classes=2, random_state=42) model = sklearn.ensemble.RandomForestClassifier() model.fit(X, y) model_dir = Path("/tmp/model") model_dir.mkdir(parents=True, exist_ok=True) model_path = model_dir / "model.joblib" joblib.dump(model, model_path) return await flyte.io.File.from_local(model_path) state = {} @asynccontextmanager async def lifespan(app: FastAPI): import joblib model = joblib.load("/root/models/model.joblib") state["model"] = model yield app = FastAPI(lifespan=lifespan) app_env = FastAPIAppEnvironment( name="model-serving-api", app=app, parameters=[ flyte.app.Parameter( name="model_file", # this is a placeholder value=flyte.io.File.from_existing_remote("s3://bucket/models/default.pkl"), mount="/root/models/", download=True, ), ], image=image, resources=flyte.Resources(cpu=2, memory="2Gi"), requires_auth=False, ) @app.post("/predict") async def predict(data: list[float]) -> dict[str, list[float]]: model = state["model"] return {"prediction": model.predict([data]).tolist()} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) run = flyte.run(train_model_task) print(f"Run: {run.url}") run.wait() model_file = run.outputs()[0] print(f"Model file: {model_file.path}") app = flyte.with_servecontext( parameter_values={ "model-serving-api": { "model_file": flyte.io.File.from_existing_remote(model_file.path) } } ).serve(app_env) print(f"API URL: {app.url}") # {{/docs-fragment model-serving-api}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/app-parameters-fastapi-example.py* ## Example: Using RunOutput for model serving ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "scikit-learn", # "joblib", # ] # /// """Examples showing different ways to pass parameters into apps.""" import os import flyte import flyte.app import flyte.io from flyte.app import Parameter, get_parameter # {{docs-fragment basic-parameter-types}} # String parameters app_env = flyte.app.AppEnvironment( name="configurable-app", parameters=[ Parameter(name="environment", value="production"), Parameter(name="log_level", value="INFO"), ], # ... ) # File parameters app_env2 = flyte.app.AppEnvironment( name="app-with-model", parameters=[ Parameter( name="model_file", value=flyte.io.File.from_existing_remote("s3://bucket/models/model.pkl"), mount="/app/models/", ), ], # ... ) # Directory parameters app_env3 = flyte.app.AppEnvironment( name="app-with-data", parameters=[ Parameter( name="data_dir", value=flyte.io.Dir.from_existing_remote("s3://bucket/data/"), mount="/app/data", ), ], # ... ) # {{/docs-fragment basic-parameter-types}} # {{docs-fragment parameter-access-methods}} from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment DATA_MOUNT_PATH = "/tmp/data_file.txt" DATA_ENV_VAR = "DATA_FILE_PATH" demo_app = FastAPI() demo_env = FastAPIAppEnvironment( name="parameter-access-demo", app=demo_app, parameters=[ # With mount and env_var: the file is downloaded to the mount path, # and an environment variable is set to point to the file location. Parameter( name="data", type="file", mount=DATA_MOUNT_PATH, env_var=DATA_ENV_VAR, ), # With no mount or env_var: accessible only via get_parameter, # which returns the path to the downloaded file. Parameter(name="data_raw", type="file"), ], # ... ) @demo_app.get("/from-mount") def read_from_mount() -> dict: """Access the file directly at the mount path.""" with open(DATA_MOUNT_PATH, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-env-var") def read_from_env_var() -> dict: """Access the file through its environment variable.""" data_path = os.environ[DATA_ENV_VAR] with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/from-get-parameter") def read_from_get_parameter() -> dict: """Access the file using the get_parameter helper.""" data_path = get_parameter("data") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} @demo_app.get("/raw") def read_raw() -> dict: """Access a parameter that has no mount or env_var.""" data_path = get_parameter("data_raw") with open(data_path, "rb") as fh: return {"contents": fh.read().decode()} # {{/docs-fragment parameter-access-methods}} # {{docs-fragment parameter-serve-override}} if __name__ == "__main__": import logging flyte.init_from_config(log_level=logging.DEBUG) app_handle = flyte.with_servecontext( parameter_values={ demo_env.name: { "data": flyte.io.File.from_existing_remote("s3://bucket/data.txt"), "data_raw": flyte.io.File.from_existing_remote("s3://bucket/raw.txt"), } } ).serve(demo_env) print(f"Deployed app: {app_handle.url}") # {{/docs-fragment parameter-serve-override}} # {{docs-fragment runoutput-example}} env = flyte.TaskEnvironment(name="training-env") @env.task async def train_model() -> flyte.io.File: # ... training logic ... return await flyte.io.File.from_local("/tmp/trained-model.pkl") app_env4 = flyte.app.AppEnvironment( name="serving-app", parameters=[ Parameter( name="model", value=flyte.app.RunOutput(type="file", task_name="training-env.train_model"), mount="/app/model", ), ], # ... ) # {{/docs-fragment runoutput-example}} # {{docs-fragment appendpoint-example}} app1_env = flyte.app.AppEnvironment(name="backend-api") app2_env = flyte.app.AppEnvironment( name="frontend-app", parameters=[ Parameter( name="backend_url", value=flyte.app.AppEndpoint(app_name="backend-api"), env_var="BACKEND_URL", ), ], # ... ) # {{/docs-fragment appendpoint-example}} # {{docs-fragment runoutput-serving-example}} import joblib from sklearn.ensemble import RandomForestClassifier training_env = flyte.TaskEnvironment(name="training-env") @training_env.task async def train_model_task() -> flyte.io.File: """Train a model and return it.""" model = RandomForestClassifier() # ... training logic ... path = "./trained-model.pkl" joblib.dump(model, path) return await flyte.io.File.from_local(path) serving_app = FastAPI() model_serving_env = FastAPIAppEnvironment( name="model-serving-app", app=serving_app, parameters=[ Parameter( name="model", value=flyte.app.RunOutput( type="file", task_name="training-env.train_model_task", ), mount="/app/model", env_var="MODEL_PATH", ), ], ) # {{/docs-fragment runoutput-serving-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/passing-parameters-examples.py* ## Best practices 1. **Use `from_existing_remote`**: Always use `flyte.io.File.from_existing_remote(...)` or `flyte.io.Dir.from_existing_remote(...)` to reference remote files and directories as parameter values. 2. **Use delayed parameters**: Use `RunOutput` and `AppEndpoint` to create app dependencies between tasks and apps, or app-to-app chains. 3. **Override for testing**: Use the `parameter_values` argument in `flyte.with_servecontext()` to test different configurations without changing code. 4. **Mount paths clearly**: Use descriptive mount paths for file/directory parameters so your app code is easy to understand. 5. **Use environment variables**: For paths that your app needs to reference dynamically, use `env_var` to inject values as environment variables. 6. **Use `get_parameter` for flexibility**: When you want to keep your parameter access decoupled from specific mount paths or env var names, use `get_parameter(name)`. ## Limitations - Large files/directories can slow down app startup. - Parameter overrides are only available when using `flyte.with_servecontext(...).serve(...)`. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/configure-apps/auto-scaling-apps === Scale an app up with traffic and down to nothing when idle. ## Autoscaling apps Flyte apps support autoscaling, allowing them to scale up and down based on traffic. This helps optimize costs by scaling down when there's no traffic and scaling up when needed. ### Scaling configuration The `scaling` parameter uses a `[[Scaling]]` object to configure autoscaling behavior: ```python scaling=flyte.app.Scaling( replicas=(min_replicas, max_replicas), scaledown_after=idle_ttl_seconds, ) ``` #### Parameters - **`replicas`**: A tuple `(min_replicas, max_replicas)` specifying the minimum and maximum number of replicas. - **`scaledown_after`**: Time in seconds to wait before scaling down when idle (idle TTL). ### Basic scaling example Here's a simple example with scaling from 0 to 1 replica: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment basic-scaling}} # Basic example: scale from 0 to 1 replica app_env = flyte.app.AppEnvironment( name="autoscaling-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Scale from 0 to 1 replica scaledown_after=300, # Scale down after 5 minutes of inactivity ), # ... ) # {{/docs-fragment basic-scaling}} # {{docs-fragment always-on}} # Always-on app app_env2 = flyte.app.AppEnvironment( name="always-on-api", scaling=flyte.app.Scaling( replicas=(1, 1), # Always keep 1 replica running # scaledown_after is ignored when min_replicas > 0 ), # ... ) # {{/docs-fragment always-on}} # {{docs-fragment scale-to-zero}} # Scale-to-zero app app_env3 = flyte.app.AppEnvironment( name="scale-to-zero-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Can scale down to 0 scaledown_after=600, # Scale down after 10 minutes of inactivity ), # ... ) # {{/docs-fragment scale-to-zero}} # {{docs-fragment high-availability}} # High-availability app app_env4 = flyte.app.AppEnvironment( name="ha-api", scaling=flyte.app.Scaling( replicas=(2, 5), # Keep at least 2, scale up to 5 scaledown_after=300, # Scale down after 5 minutes ), # ... ) # {{/docs-fragment high-availability}} # {{docs-fragment burstable}} # Burstable app app_env5 = flyte.app.AppEnvironment( name="bursty-app", scaling=flyte.app.Scaling( replicas=(1, 10), # Start with 1, scale up to 10 under load scaledown_after=180, # Scale down quickly after 3 minutes ), # ... ) # {{/docs-fragment burstable}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/autoscaling-examples.py* This configuration: - Starts with 0 replicas (no running instances) - Scales up to 1 replica when there's traffic - Scales back down to 0 after 5 minutes (300 seconds) of no traffic ### Scaling patterns #### Always-on app For apps that need to always be running: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment basic-scaling}} # Basic example: scale from 0 to 1 replica app_env = flyte.app.AppEnvironment( name="autoscaling-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Scale from 0 to 1 replica scaledown_after=300, # Scale down after 5 minutes of inactivity ), # ... ) # {{/docs-fragment basic-scaling}} # {{docs-fragment always-on}} # Always-on app app_env2 = flyte.app.AppEnvironment( name="always-on-api", scaling=flyte.app.Scaling( replicas=(1, 1), # Always keep 1 replica running # scaledown_after is ignored when min_replicas > 0 ), # ... ) # {{/docs-fragment always-on}} # {{docs-fragment scale-to-zero}} # Scale-to-zero app app_env3 = flyte.app.AppEnvironment( name="scale-to-zero-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Can scale down to 0 scaledown_after=600, # Scale down after 10 minutes of inactivity ), # ... ) # {{/docs-fragment scale-to-zero}} # {{docs-fragment high-availability}} # High-availability app app_env4 = flyte.app.AppEnvironment( name="ha-api", scaling=flyte.app.Scaling( replicas=(2, 5), # Keep at least 2, scale up to 5 scaledown_after=300, # Scale down after 5 minutes ), # ... ) # {{/docs-fragment high-availability}} # {{docs-fragment burstable}} # Burstable app app_env5 = flyte.app.AppEnvironment( name="bursty-app", scaling=flyte.app.Scaling( replicas=(1, 10), # Start with 1, scale up to 10 under load scaledown_after=180, # Scale down quickly after 3 minutes ), # ... ) # {{/docs-fragment burstable}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/autoscaling-examples.py* #### Scale-to-zero app For apps that can scale to zero when idle: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment basic-scaling}} # Basic example: scale from 0 to 1 replica app_env = flyte.app.AppEnvironment( name="autoscaling-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Scale from 0 to 1 replica scaledown_after=300, # Scale down after 5 minutes of inactivity ), # ... ) # {{/docs-fragment basic-scaling}} # {{docs-fragment always-on}} # Always-on app app_env2 = flyte.app.AppEnvironment( name="always-on-api", scaling=flyte.app.Scaling( replicas=(1, 1), # Always keep 1 replica running # scaledown_after is ignored when min_replicas > 0 ), # ... ) # {{/docs-fragment always-on}} # {{docs-fragment scale-to-zero}} # Scale-to-zero app app_env3 = flyte.app.AppEnvironment( name="scale-to-zero-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Can scale down to 0 scaledown_after=600, # Scale down after 10 minutes of inactivity ), # ... ) # {{/docs-fragment scale-to-zero}} # {{docs-fragment high-availability}} # High-availability app app_env4 = flyte.app.AppEnvironment( name="ha-api", scaling=flyte.app.Scaling( replicas=(2, 5), # Keep at least 2, scale up to 5 scaledown_after=300, # Scale down after 5 minutes ), # ... ) # {{/docs-fragment high-availability}} # {{docs-fragment burstable}} # Burstable app app_env5 = flyte.app.AppEnvironment( name="bursty-app", scaling=flyte.app.Scaling( replicas=(1, 10), # Start with 1, scale up to 10 under load scaledown_after=180, # Scale down quickly after 3 minutes ), # ... ) # {{/docs-fragment burstable}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/autoscaling-examples.py* #### High-availability app For apps that need multiple replicas for availability: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment basic-scaling}} # Basic example: scale from 0 to 1 replica app_env = flyte.app.AppEnvironment( name="autoscaling-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Scale from 0 to 1 replica scaledown_after=300, # Scale down after 5 minutes of inactivity ), # ... ) # {{/docs-fragment basic-scaling}} # {{docs-fragment always-on}} # Always-on app app_env2 = flyte.app.AppEnvironment( name="always-on-api", scaling=flyte.app.Scaling( replicas=(1, 1), # Always keep 1 replica running # scaledown_after is ignored when min_replicas > 0 ), # ... ) # {{/docs-fragment always-on}} # {{docs-fragment scale-to-zero}} # Scale-to-zero app app_env3 = flyte.app.AppEnvironment( name="scale-to-zero-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Can scale down to 0 scaledown_after=600, # Scale down after 10 minutes of inactivity ), # ... ) # {{/docs-fragment scale-to-zero}} # {{docs-fragment high-availability}} # High-availability app app_env4 = flyte.app.AppEnvironment( name="ha-api", scaling=flyte.app.Scaling( replicas=(2, 5), # Keep at least 2, scale up to 5 scaledown_after=300, # Scale down after 5 minutes ), # ... ) # {{/docs-fragment high-availability}} # {{docs-fragment burstable}} # Burstable app app_env5 = flyte.app.AppEnvironment( name="bursty-app", scaling=flyte.app.Scaling( replicas=(1, 10), # Start with 1, scale up to 10 under load scaledown_after=180, # Scale down quickly after 3 minutes ), # ... ) # {{/docs-fragment burstable}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/autoscaling-examples.py* #### Burstable app For apps with variable load: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// import flyte import flyte.app # {{docs-fragment basic-scaling}} # Basic example: scale from 0 to 1 replica app_env = flyte.app.AppEnvironment( name="autoscaling-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Scale from 0 to 1 replica scaledown_after=300, # Scale down after 5 minutes of inactivity ), # ... ) # {{/docs-fragment basic-scaling}} # {{docs-fragment always-on}} # Always-on app app_env2 = flyte.app.AppEnvironment( name="always-on-api", scaling=flyte.app.Scaling( replicas=(1, 1), # Always keep 1 replica running # scaledown_after is ignored when min_replicas > 0 ), # ... ) # {{/docs-fragment always-on}} # {{docs-fragment scale-to-zero}} # Scale-to-zero app app_env3 = flyte.app.AppEnvironment( name="scale-to-zero-app", scaling=flyte.app.Scaling( replicas=(0, 1), # Can scale down to 0 scaledown_after=600, # Scale down after 10 minutes of inactivity ), # ... ) # {{/docs-fragment scale-to-zero}} # {{docs-fragment high-availability}} # High-availability app app_env4 = flyte.app.AppEnvironment( name="ha-api", scaling=flyte.app.Scaling( replicas=(2, 5), # Keep at least 2, scale up to 5 scaledown_after=300, # Scale down after 5 minutes ), # ... ) # {{/docs-fragment high-availability}} # {{docs-fragment burstable}} # Burstable app app_env5 = flyte.app.AppEnvironment( name="bursty-app", scaling=flyte.app.Scaling( replicas=(1, 10), # Start with 1, scale up to 10 under load scaledown_after=180, # Scale down quickly after 3 minutes ), # ... ) # {{/docs-fragment burstable}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/autoscaling-examples.py* ### Idle TTL (Time to live) The `scaledown_after` parameter (idle TTL) determines how long an app instance can be idle before it's scaled down. #### Considerations - **Too short**: May cause frequent scale up/down cycles, leading to cold starts. - **Too long**: Keeps resources running unnecessarily, increasing costs. - **Optimal**: Balance between cost and user experience. #### Common idle TTL values - **Development/Testing**: 60-180 seconds (1-3 minutes) - quick scale down for cost savings. - **Production APIs**: 300-600 seconds (5-10 minutes) - balance cost and responsiveness. - **Batch processing**: 900-1800 seconds (15-30 minutes) - longer to handle bursts. - **Always-on**: Set `min_replicas > 0` - never scale down. ### Autoscaling best practices 1. **Start conservative**: Begin with longer idle TTL values and adjust based on usage. 2. **Monitor cold starts**: Track how long it takes for your app to become ready after scaling up. 3. **Consider costs**: Balance idle TTL between cost savings and user experience. 4. **Use appropriate min replicas**: Set `min_replicas > 0` for critical apps that need to be always available. 5. **Test scaling behavior**: Verify your app handles scale up/down correctly (for example, state management and connections). ### Autoscaling limitations - Scaling is based on traffic/request patterns, not CPU/memory utilization. - Cold starts may occur when scaling from zero. - Stateful apps need careful design to handle scaling (use external state stores). - Maximum replicas are limited by your cluster capacity. ### Autoscaling troubleshooting **App scales down too quickly:** - Increase `scaledown_after` value. - Set `min_replicas > 0` if the app needs to stay warm. **App doesn't scale up fast enough:** - Ensure your cluster has capacity. - Check if there are resource constraints. **Cold starts are too slow:** - Pre-warm with `min_replicas = 1`. - Optimize app startup time. - Consider using faster storage for model loading. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/configure-apps/apps-depending-on-environments === Use depends_on so deploying an app or task environment also deploys the environments it needs. # Apps depending on other environments The `depends_on` parameter allows you to specify that one app depends on another app (or task environment). When you deploy an app with `depends_on`, Flyte deploys its dependencies in the same deployment. ## Basic usage Use `depends_on` to specify a list of environments that this app depends on: ```python app1_env = flyte.app.AppEnvironment(name="backend-api", ...) app2_env = flyte.app.AppEnvironment( name="frontend-app", depends_on=[app1_env], # Deploying frontend-app also deploys backend-api # ... ) ``` When you deploy `app2_env`, Flyte puts `app1_env` and `app2_env` in one deployment plan and deploys them together. It doesn't wait for `app1_env` to be ready before it deploys `app2_env`, so code in `app2_env` that calls `app1_env` as soon as it starts should retry until `app1_env` answers. ## Example: App calling another app Here's a complete example where one FastAPI app calls another: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "httpx", # ] # /// """Example of one app calling another app.""" import httpx from fastapi import FastAPI import pathlib import flyte from flyte.app.extras import FastAPIAppEnvironment image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "httpx" ) # {{docs-fragment backend-app}} app1 = FastAPI( title="App 1", description="A FastAPI app that runs some computations", ) env1 = FastAPIAppEnvironment( name="app1-is-called-by-app2", app=app1, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, ) # {{/docs-fragment backend-app}} # {{docs-fragment frontend-app}} app2 = FastAPI( title="App 2", description="A FastAPI app that proxies requests to another FastAPI app", ) env2 = FastAPIAppEnvironment( name="app2-calls-app1", app=app2, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, depends_on=[env1], # Depends on backend-api ) # {{/docs-fragment frontend-app}} # {{docs-fragment backend-endpoint}} @app1.get("/greeting/{name}") async def greeting(name: str) -> str: return f"Hello, {name}!" # {{/docs-fragment backend-endpoint}} # {{docs-fragment frontend-endpoints}} @app2.get("/app1-endpoint") async def get_app1_endpoint() -> str: return env1.endpoint # Access the backend endpoint @app2.get("/greeting/{name}") async def greeting_proxy(name: str): """Proxy that calls the backend app.""" async with httpx.AsyncClient() as client: response = await client.get(f"{env1.endpoint}/greeting/{name}") response.raise_for_status() return response.json() # {{/docs-fragment frontend-endpoints}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployments = flyte.deploy(env2) print(f"Deployed FastAPI app: {deployments[0].env_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/app_calling_app.py* When you deploy `env2`, Flyte deploys `env1` (backend-api) and `env2` (frontend-api) together. `env2` then reaches `env1` through `env1.endpoint`. ## Dependency chain You can create chains of dependencies: ```python app1_env = flyte.app.AppEnvironment(name="service-1", ...) app2_env = flyte.app.AppEnvironment(name="service-2", depends_on=[app1_env], ...) app3_env = flyte.app.AppEnvironment(name="service-3", depends_on=[app2_env], ...) # Deploying app3_env also deploys app2_env and app1_env, all in one deployment ``` ## Multiple dependencies An app can depend on multiple environments: ```python backend_env = flyte.app.AppEnvironment(name="backend", ...) database_env = flyte.app.AppEnvironment(name="database", ...) api_env = flyte.app.AppEnvironment( name="api", depends_on=[backend_env, database_env], # Depends on both # ... ) ``` When you deploy `api_env`, `backend_env` and `database_env` are deployed with it. ## Using AppEndpoint for dependency URLs When one app depends on another, you can use `AppEndpoint` to get the URL: ```python backend_env = flyte.app.AppEnvironment(name="backend-api", ...) frontend_env = flyte.app.AppEnvironment( name="frontend-app", depends_on=[backend_env], parameters=[ flyte.app.Parameter( name="backend_url", value=flyte.app.AppEndpoint(app_name="backend-api"), ), ], # ... ) ``` The `backend_url` parameter will be automatically set to the backend app's endpoint URL. You can get this value in your app code using `flyte.app.get_input("backend_url")`. ## Deployment behavior When deploying with `flyte.deploy()`: ```python # Deploy the app (dependencies are automatically deployed) deployments = flyte.deploy(env2) # All dependencies are included in the deployment plan for deployment in deployments: print(f"Deployed: {deployment.env.name}") ``` Flyte will: 1. Build a deployment plan that includes all dependencies 2. Deploy every environment in the plan at the same time ## Task environment dependencies You can also depend on task environments: ```python task_env = flyte.TaskEnvironment(name="training-env", ...) serving_env = flyte.app.AppEnvironment( name="serving-app", depends_on=[task_env], # Can depend on task environments too # ... ) ``` Deploying the app then also deploys the task environment, which is useful if the app calls tasks in it. ## Best practices 1. **Explicit dependencies**: Always use `depends_on` to make app dependencies explicit 2. **Circular dependencies**: Avoid circular dependencies (app A depends on B, B depends on A) 3. **Dependency order**: Design your dependency graph to be a DAG (Directed Acyclic Graph) 4. **Endpoint access**: Use `AppEndpoint` to pass dependency URLs as inputs 5. **Document dependencies**: Make sure your app documentation explains its dependencies ## Example: A/B testing with dependencies Here's an example of an A/B testing setup where a root app depends on two variant apps: ```python app_a = FastAPI(title="Variant A") app_b = FastAPI(title="Variant B") root_app = FastAPI(title="Root App") env_a = FastAPIAppEnvironment(name="app-a-variant", app=app_a, ...) env_b = FastAPIAppEnvironment(name="app-b-variant", app=app_b, ...) env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, depends_on=[env_a, env_b], # Depends on both variants # ... ) ``` The root app can route traffic to either variant A or B based on A/B testing logic, and both variants are deployed together with it. ## Limitations - Circular dependencies are not supported - Dependencies must be in the same project/domain - `depends_on` decides which environments are deployed, not the order: all of them deploy at the same time === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps === Build dashboards, REST APIs, and model endpoints with FastAPI, Streamlit, vLLM, and more. # Build apps This section covers how to build different types of apps with Flyte, from single-script apps to multi-file projects, common usage patterns, and authentication. > [!TIP] > Go to **Get started > Core concepts > Apps** for an overview of apps and a quick example. For pre-built environments for popular frameworks like Streamlit, FastAPI, vLLM, SGLang, and Ollama, see [Native app integrations](../native-app-integrations/_index). ## App types Flyte supports various types of apps: - **UI dashboard apps**: Interactive web dashboards and data visualization tools like Streamlit and Gradio - **Web API apps**: REST APIs, webhooks, and backend services like FastAPI and Flask - **Model serving apps**: High-performance LLM serving with vLLM and SGLang, or lightweight serving with Ollama - **Connector apps**: Long-running services that delegate task execution to external systems For ready-to-use environments for these frameworks, see [Native app integrations](../native-app-integrations/_index). ## Usage patterns Apps and tasks can interact in various ways: calling each other via HTTP, webhooks, WebSockets, or direct browser usage. | Pattern | Use Case | Implementation | |---------|----------|----------------| | App | Stand-alone serving app | HTTP requests from arbitrary clients | | App โ†’ App | Microservices, proxies, agent routers, LLM routers | HTTP requests between apps | | App โ†’ Task | Webhooks, APIs triggering workflows | Flyte SDK in app | | Task โ†’ App | Batch processing using inference services | HTTP requests from task | | Browser app | User-facing dashboards (e.g. Streamlit, Gradio) | Direct browser access | ## Next steps - **Apps > Build apps > Single-script apps**: The simplest way to build and deploy apps in a single Python script - **Apps > Build apps > Multi-script apps**: Build FastAPI and Streamlit apps with multiple files - **Apps > Build apps > Serving graphs**: Apps calling other apps for microservice architectures - **Apps > Build apps > Hybrid app-task graphs**: Tasks calling apps and apps calling tasks (webhooks, APIs) - **Apps > Build apps > WebSocket apps**: Real-time, bidirectional communication with WebSockets - **Apps > Build apps > Browser apps**: User-facing dashboards and UIs - **Apps > Build apps > Secret-based authentication**: Authenticate FastAPI apps using Flyte secrets - **Apps > Build apps > Connector app**: Deploy a connector as a long-running service {{< subpage-cards >}} ## Subpages - **Apps > Build apps > Single-script apps** - Build and deploy an app from one Python file. - **Apps > Build apps > Multi-script apps** - Build a FastAPI or Streamlit app that spans several Python files. - **Apps > Build apps > Serving graphs** - Split a request across several apps that talk to each other inside the cluster. - **Apps > Build apps > Hybrid app-task graphs** - Have tasks call apps over HTTP and apps trigger runs through the SDK. - **Apps > Build apps > WebSocket apps** - Serve WebSocket endpoints for bidirectional, real-time communication. - **Apps > Build apps > Browser apps** - Serve Streamlit, Gradio, or custom dashboards that users reach directly in a browser. - **Apps > Build apps > Secret-based authentication** - Protect a public FastAPI endpoint with an API key held in a Flyte secret. - **Apps > Build apps > Connector app** - Extend Flyte with a custom task execution backend, such as an internal batch service. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps/single-script-apps === Build and deploy an app from one Python file. # Single-script apps The simplest way to build and deploy an app with Flyte is to write everything in a single Python script. This approach is perfect for: - **Quick prototypes**: Rapidly test ideas and concepts - **Simple services**: Basic HTTP servers, APIs, or dashboards - **Learning**: Understanding how Flyte apps work without complexity - **Minimal examples**: Demonstrating core functionality All the code for your app (the application logic, the app environment configuration, and the deployment code) lives in one file. This makes it easy to understand, share, and deploy. ## Plain Python HTTP server The simplest possible app is a plain Python HTTP server using Python's built-in `http.server` module. This requires no external dependencies beyond the Flyte SDK. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A plain Python HTTP server example - the simplest possible app.""" import flyte import flyte.app from pathlib import Path # {{docs-fragment server-code}} # Create a simple HTTP server handler from http.server import HTTPServer, BaseHTTPRequestHandler class SimpleHandler(BaseHTTPRequestHandler): """A simple HTTP server handler.""" def do_GET(self): if self.path == "/": self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(b"

Hello from Plain Python Server!

") elif self.path == "/health": self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(b'{"status": "healthy"}') else: self.send_response(404) self.end_headers() # {{/docs-fragment server-code}} # {{docs-fragment app-env}} file_name = Path(__file__).name app_env = flyte.app.AppEnvironment( name="plain-python-server", image=flyte.Image.from_debian_base(python_version=(3, 12)), args=["python", file_name, "--server"], port=8080, resources=flyte.Resources(cpu="1", memory="512Mi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": import sys if "--server" in sys.argv: server = HTTPServer(("0.0.0.0", 8080), SimpleHandler) print("Server running on port 8080") server.serve_forever() else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(app_env) print(f"App URL: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/plain_python_server.py* **Key points** - **No external dependencies**: Uses only Python's standard library - **Simple handler**: Define request handlers as Python classes - **Basic command**: Run the server with a simple Python command - **Minimal resources**: Requires only basic CPU and memory ## Streamlit app Streamlit makes it easy to build interactive web dashboards. Here's a complete single-script Streamlit app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # ] # /// """A single-script Streamlit app example.""" import pathlib import streamlit as st import flyte import flyte.app # {{docs-fragment streamlit-app}} def main(): st.set_page_config(page_title="Simple Streamlit App", page_icon="๐Ÿš€") st.title("Hello from Streamlit!") st.write("This is a simple single-script Streamlit app.") name = st.text_input("What's your name?", "World") st.write(f"Hello, {name}!") if st.button("Click me!"): st.balloons() st.success("Button clicked!") # {{/docs-fragment streamlit-app}} # {{docs-fragment app-env}} file_name = pathlib.Path(__file__).name app_env = flyte.app.AppEnvironment( name="streamlit-single-script", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit==1.41.1" ), args=["streamlit", "run", file_name, "--server.port", "8080", "--", "--server"], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": import sys if "--server" in sys.argv: main() else: flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app = flyte.serve(app_env) print(f"App URL: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit_single_script.py* **Key points** - **Interactive UI**: Streamlit provides widgets and visualizations out of the box - **Single file**: All UI logic and deployment code in one script - **Simple deployment**: Just specify the Streamlit command and port - **Rich ecosystem**: Access to Streamlit's extensive component library ## FastAPI app FastAPI is a modern, fast web framework for building APIs. Here's a minimal single-script FastAPI app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """A single-script FastAPI app example - the simplest FastAPI app.""" from fastapi import FastAPI import pathlib import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment fastapi-app}} app = FastAPI( title="Simple FastAPI App", description="A minimal single-script FastAPI application", version="1.0.0", ) @app.get("/") async def root(): return {"message": "Hello, World!"} @app.get("/health") async def health(): return {"status": "healthy"} # {{/docs-fragment fastapi-app}} # {{docs-fragment app-env}} app_env = FastAPIAppEnvironment( name="fastapi-single-script", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.serve(app_env) print(f"Deployed: {app_deployment.url}") print(f"API docs: {app_deployment.url}/docs") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi_single_script.py* **Key points** - **FastAPIAppEnvironment**: Automatically configures uvicorn and FastAPI - **Type hints**: FastAPI uses Python type hints for automatic validation - **Auto docs**: Interactive API documentation at `/docs` endpoint - **Async support**: Built-in support for async/await patterns ## Running single-script apps To run any of these examples: 1. **Save the script** to a file (e.g., `my_app.py`) 2. **Ensure you have a config file** (`./.flyte/config.yaml` or `./config.yaml`) 3. **Run the script**: ```bash python my_app.py ``` Or using `uv`: ```bash uv run my_app.py ``` The script will: - Initialize Flyte from your config - Deploy the app to your Union/Flyte instance - Print the app URL ## When to use single-script apps **Use single-script apps when:** - Building prototypes or proof-of-concepts - Creating simple services with minimal logic - Learning how Flyte apps work - Sharing complete, runnable examples - Building demos or tutorials **Consider multi-script apps when:** - Your app grows beyond a few hundred lines - You need to organize code into modules - You want to reuse components across apps - You're building production applications See **Apps > Build apps > Multi-script apps** for examples of organizing apps across multiple files. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps/multi-script-apps === Build a FastAPI or Streamlit app that spans several Python files. # Multi-script apps Real-world applications often span multiple files. This page shows how to build FastAPI and Streamlit apps with multiple Python files. ## FastAPI multi-script app ### Project structure ``` project/ โ”œโ”€โ”€ app.py # Main FastAPI app file โ””โ”€โ”€ module.py # Helper module ``` ### Example: Multi-file FastAPI app ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """Multi-file FastAPI app example.""" from fastapi import FastAPI from module import function # Import from another file import pathlib import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment app-definition}} app = FastAPI(title="Multi-file FastAPI Demo") app_env = FastAPIAppEnvironment( name="fastapi-multi-file", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, # FastAPIAppEnvironment automatically includes necessary files # But you can also specify explicitly: # include=["app.py", "module.py"], ) # {{/docs-fragment app-definition}} # {{docs-fragment endpoint}} @app.get("/") async def root(): return function() # Uses function from module.py # {{/docs-fragment endpoint}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(app_env) print(f"Deployed: {app_deployment[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/multi_file/app.py* ``` # {{docs-fragment helper-function}} def function(): """Helper function used by the FastAPI app.""" return {"message": "Hello from module.py!"} # {{/docs-fragment helper-function}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/multi_file/module.py* ### Automatic file discovery `FastAPIAppEnvironment` automatically discovers and includes the necessary files by analyzing your imports. However, if you have files that aren't automatically detected (like configuration files or data files), you can explicitly include them: ```python app_env = FastAPIAppEnvironment( name="fastapi-with-config", app=app, include=["app.py", "module.py", "config.yaml"], # Explicit includes # ... ) ``` ## Streamlit multi-script app ### Project structure ``` project/ โ”œโ”€โ”€ main.py # Main Streamlit app โ”œโ”€โ”€ utils.py # Utility functions โ””โ”€โ”€ components.py # Reusable components ``` ### Example: Multi-file Streamlit app ``` import os import streamlit as st from utils import generate_data # {{docs-fragment streamlit-app}} all_columns = ["Apples", "Orange", "Pineapple"] with st.container(border=True): columns = st.multiselect("Columns", all_columns, default=all_columns) all_data = st.cache_data(generate_data)(columns=all_columns, seed=101) data = all_data[columns] tab1, tab2 = st.tabs(["Chart", "Dataframe"]) tab1.line_chart(data, height=250) tab2.dataframe(data, height=250, use_container_width=True) st.write(f"Environment: {os.environ}") # {{/docs-fragment streamlit-app}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/main.py* ``` import numpy as np import pandas as pd # {{docs-fragment utils-function}} def generate_data(columns: list[str], seed: int = 42): rng = np.random.default_rng(seed) data = pd.DataFrame(rng.random(size=(20, len(columns))), columns=columns) return data # {{/docs-fragment utils-function}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/utils.py* ### Deploying multi-file Streamlit app ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A custom Streamlit app with multiple files.""" import pathlib import flyte import flyte.app # {{docs-fragment app-env}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit==1.41.1", "pandas==2.2.3", "numpy==2.2.3", ) app_env = flyte.app.AppEnvironment( name="streamlit-multi-file-app", image=image, args="streamlit run main.py --server.port 8080", port=8080, include=["main.py", "utils.py"], # Include your app files resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app = flyte.deploy(app_env) print(f"Deployed app: {app[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/multi_file_streamlit.py* ## Complex multi-file example Here's a more complex example with multiple modules: ### Project structure ``` project/ โ”œโ”€โ”€ app.py โ”œโ”€โ”€ models/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ””โ”€โ”€ user.py โ”œโ”€โ”€ services/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ””โ”€โ”€ auth.py โ””โ”€โ”€ utils/ โ”œโ”€โ”€ __init__.py โ””โ”€โ”€ helpers.py ``` ### Example code ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """Complex multi-file FastAPI app example.""" from pathlib import Path from fastapi import FastAPI from models.user import User from services.auth import authenticate from utils.helpers import format_response import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment complex-app}} app = FastAPI(title="Complex Multi-file App") @app.get("/users/{user_id}") async def get_user(user_id: int): user = User(id=user_id, name="John Doe") return format_response(user) # {{/docs-fragment complex-app}} # {{docs-fragment complex-env}} app_env = FastAPIAppEnvironment( name="complex-app", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "pydantic", ), # Include all necessary files include=[ "app.py", "models/", "services/", "utils/", ], resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment complex-env}} if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(app_env) print(f"Deployed: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/complex_multi_file/app.py* ``` # {{docs-fragment user-model}} from pydantic import BaseModel class User(BaseModel): id: int name: str # {{/docs-fragment user-model}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/complex_multi_file/models/user.py* ``` # {{docs-fragment auth-service}} def authenticate(token: str) -> bool: """Authenticate a user by token.""" # ... authentication logic ... return True # {{/docs-fragment auth-service}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/complex_multi_file/services/auth.py* ``` # {{docs-fragment helpers}} def format_response(data): """Format a response with standard structure.""" return {"data": data, "status": "success"} # {{/docs-fragment helpers}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/complex_multi_file/utils/helpers.py* ### Deploying complex app ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """Complex multi-file FastAPI app example.""" from pathlib import Path from fastapi import FastAPI from models.user import User from services.auth import authenticate from utils.helpers import format_response import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment complex-app}} app = FastAPI(title="Complex Multi-file App") @app.get("/users/{user_id}") async def get_user(user_id: int): user = User(id=user_id, name="John Doe") return format_response(user) # {{/docs-fragment complex-app}} # {{docs-fragment complex-env}} app_env = FastAPIAppEnvironment( name="complex-app", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "pydantic", ), # Include all necessary files include=[ "app.py", "models/", "services/", "utils/", ], resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment complex-env}} if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(app_env) print(f"Deployed: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/complex_multi_file/app.py* ## Best practices 1. **Use explicit includes**: For Streamlit apps, explicitly list all files in `include` 2. **Automatic discovery**: For FastAPI apps, `FastAPIAppEnvironment` handles most cases automatically 3. **Organize modules**: Use proper Python package structure with `__init__.py` files 4. **Test locally**: Test your multi-file app locally before deploying 5. **Include all dependencies**: Include all files that your app imports ## Troubleshooting **Import errors:** - Verify all files are included in the `include` parameter - Check that file paths are correct (relative to app definition file) - Ensure `__init__.py` files are included for packages **Module not found:** - Add missing files to the `include` list - Check that import paths match the file structure - Verify that the image includes all necessary packages **File not found at runtime:** - Ensure all referenced files are included - Check mount paths for file/directory inputs - Verify file paths are relative to the app root directory === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps/serving-graphs === Split a request across several apps that talk to each other inside the cluster. # Serving graphs A *serving graph* is a set of Flyte apps that talk to each other inside the cluster. Instead of putting every stage of a request into one process, you split the work across multiple `AppEnvironment`s that you deploy together: each one sized for its own bottleneck, with its own image and scaling policy. This pattern is useful for: - **Heterogeneous resource requirements**: CPU pre/postprocessing in front of a GPU forward pass - **Microservice architectures**: Independent components with distinct lifecycles - **A/B testing and canary rollouts**: A root app routes traffic across variant apps - **Proxy / gateway patterns**: One app fronts several backends ## Core concepts: a minimal two-app chain The simplest serving graph (`app2` proxies HTTP calls to `app1`) is enough to introduce every core concept: deploying multiple apps together, discovering an upstream app's endpoint, and sizing each app independently. Both apps share an image and live in the same Python file: ``` import logging import os import pathlib import typing import httpx from fastapi import FastAPI import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("fastapi", "uvicorn", "httpx") # {{/docs-fragment image}} # {{docs-fragment apps}} app1 = FastAPI( title="App 1", description="A FastAPI app that runs some computations", ) app2 = FastAPI( title="App 2", description="A FastAPI app that proxies requests to another FastAPI app", ) # {{/docs-fragment apps}} # {{docs-fragment env-direct}} env1 = FastAPIAppEnvironment( name="app1-is-called-by-app2", app=app1, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment env-direct}} # {{docs-fragment env-with-parameter}} env2 = FastAPIAppEnvironment( name="app2-calls-app1", app=app2, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, parameters=[ flyte.app.Parameter( name="app1_url", value=flyte.app.AppEndpoint(app_name="app1-is-called-by-app2"), env_var="APP1_URL", ), ], depends_on=[env1], env_vars={"LOG_LEVEL": "10"}, ) # {{/docs-fragment env-with-parameter}} @app1.get("/greeting/{name}") async def greeting(name: str) -> str: return f"Hello, {name}!" # {{docs-fragment endpoint-property-pattern}} @app2.get("/app1-endpoint") async def get_app1_endpoint() -> str: return env1.endpoint @app2.get("/greeting/{name}") async def greeting_proxy(name: str) -> typing.Any: async with httpx.AsyncClient() as client: response = await client.get(f"{env1.endpoint}/greeting/{name}") return response.json() # {{/docs-fragment endpoint-property-pattern}} # {{docs-fragment endpoint-env-var-pattern}} @app2.get("/app1-url") async def get_app1_url() -> str: return os.getenv("APP1_URL") # {{/docs-fragment endpoint-env-var-pattern}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(env2) print(f"Deployed FastAPI app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/two_app_chain.py* ``` import logging import os import pathlib import typing import httpx from fastapi import FastAPI import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("fastapi", "uvicorn", "httpx") # {{/docs-fragment image}} # {{docs-fragment apps}} app1 = FastAPI( title="App 1", description="A FastAPI app that runs some computations", ) app2 = FastAPI( title="App 2", description="A FastAPI app that proxies requests to another FastAPI app", ) # {{/docs-fragment apps}} # {{docs-fragment env-direct}} env1 = FastAPIAppEnvironment( name="app1-is-called-by-app2", app=app1, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment env-direct}} # {{docs-fragment env-with-parameter}} env2 = FastAPIAppEnvironment( name="app2-calls-app1", app=app2, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, parameters=[ flyte.app.Parameter( name="app1_url", value=flyte.app.AppEndpoint(app_name="app1-is-called-by-app2"), env_var="APP1_URL", ), ], depends_on=[env1], env_vars={"LOG_LEVEL": "10"}, ) # {{/docs-fragment env-with-parameter}} @app1.get("/greeting/{name}") async def greeting(name: str) -> str: return f"Hello, {name}!" # {{docs-fragment endpoint-property-pattern}} @app2.get("/app1-endpoint") async def get_app1_endpoint() -> str: return env1.endpoint @app2.get("/greeting/{name}") async def greeting_proxy(name: str) -> typing.Any: async with httpx.AsyncClient() as client: response = await client.get(f"{env1.endpoint}/greeting/{name}") return response.json() # {{/docs-fragment endpoint-property-pattern}} # {{docs-fragment endpoint-env-var-pattern}} @app2.get("/app1-url") async def get_app1_url() -> str: return os.getenv("APP1_URL") # {{/docs-fragment endpoint-env-var-pattern}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(env2) print(f"Deployed FastAPI app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/two_app_chain.py* ### Deploying multiple apps together with `depends_on` The callee env is straightforward; it has no upstream dependencies of its own: ``` import logging import os import pathlib import typing import httpx from fastapi import FastAPI import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("fastapi", "uvicorn", "httpx") # {{/docs-fragment image}} # {{docs-fragment apps}} app1 = FastAPI( title="App 1", description="A FastAPI app that runs some computations", ) app2 = FastAPI( title="App 2", description="A FastAPI app that proxies requests to another FastAPI app", ) # {{/docs-fragment apps}} # {{docs-fragment env-direct}} env1 = FastAPIAppEnvironment( name="app1-is-called-by-app2", app=app1, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment env-direct}} # {{docs-fragment env-with-parameter}} env2 = FastAPIAppEnvironment( name="app2-calls-app1", app=app2, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, parameters=[ flyte.app.Parameter( name="app1_url", value=flyte.app.AppEndpoint(app_name="app1-is-called-by-app2"), env_var="APP1_URL", ), ], depends_on=[env1], env_vars={"LOG_LEVEL": "10"}, ) # {{/docs-fragment env-with-parameter}} @app1.get("/greeting/{name}") async def greeting(name: str) -> str: return f"Hello, {name}!" # {{docs-fragment endpoint-property-pattern}} @app2.get("/app1-endpoint") async def get_app1_endpoint() -> str: return env1.endpoint @app2.get("/greeting/{name}") async def greeting_proxy(name: str) -> typing.Any: async with httpx.AsyncClient() as client: response = await client.get(f"{env1.endpoint}/greeting/{name}") return response.json() # {{/docs-fragment endpoint-property-pattern}} # {{docs-fragment endpoint-env-var-pattern}} @app2.get("/app1-url") async def get_app1_url() -> str: return os.getenv("APP1_URL") # {{/docs-fragment endpoint-env-var-pattern}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(env2) print(f"Deployed FastAPI app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/two_app_chain.py* The caller declares `depends_on=[env1]`, which tells Flyte that `env1` must be deployed alongside this one: ``` import logging import os import pathlib import typing import httpx from fastapi import FastAPI import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("fastapi", "uvicorn", "httpx") # {{/docs-fragment image}} # {{docs-fragment apps}} app1 = FastAPI( title="App 1", description="A FastAPI app that runs some computations", ) app2 = FastAPI( title="App 2", description="A FastAPI app that proxies requests to another FastAPI app", ) # {{/docs-fragment apps}} # {{docs-fragment env-direct}} env1 = FastAPIAppEnvironment( name="app1-is-called-by-app2", app=app1, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment env-direct}} # {{docs-fragment env-with-parameter}} env2 = FastAPIAppEnvironment( name="app2-calls-app1", app=app2, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, parameters=[ flyte.app.Parameter( name="app1_url", value=flyte.app.AppEndpoint(app_name="app1-is-called-by-app2"), env_var="APP1_URL", ), ], depends_on=[env1], env_vars={"LOG_LEVEL": "10"}, ) # {{/docs-fragment env-with-parameter}} @app1.get("/greeting/{name}") async def greeting(name: str) -> str: return f"Hello, {name}!" # {{docs-fragment endpoint-property-pattern}} @app2.get("/app1-endpoint") async def get_app1_endpoint() -> str: return env1.endpoint @app2.get("/greeting/{name}") async def greeting_proxy(name: str) -> typing.Any: async with httpx.AsyncClient() as client: response = await client.get(f"{env1.endpoint}/greeting/{name}") return response.json() # {{/docs-fragment endpoint-property-pattern}} # {{docs-fragment endpoint-env-var-pattern}} @app2.get("/app1-url") async def get_app1_url() -> str: return os.getenv("APP1_URL") # {{/docs-fragment endpoint-env-var-pattern}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(env2) print(f"Deployed FastAPI app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/two_app_chain.py* Calling `flyte.serve(env2)` then deploys the whole dependency closure transitively, so you only ever name the entry-point app: ``` import logging import os import pathlib import typing import httpx from fastapi import FastAPI import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("fastapi", "uvicorn", "httpx") # {{/docs-fragment image}} # {{docs-fragment apps}} app1 = FastAPI( title="App 1", description="A FastAPI app that runs some computations", ) app2 = FastAPI( title="App 2", description="A FastAPI app that proxies requests to another FastAPI app", ) # {{/docs-fragment apps}} # {{docs-fragment env-direct}} env1 = FastAPIAppEnvironment( name="app1-is-called-by-app2", app=app1, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment env-direct}} # {{docs-fragment env-with-parameter}} env2 = FastAPIAppEnvironment( name="app2-calls-app1", app=app2, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, parameters=[ flyte.app.Parameter( name="app1_url", value=flyte.app.AppEndpoint(app_name="app1-is-called-by-app2"), env_var="APP1_URL", ), ], depends_on=[env1], env_vars={"LOG_LEVEL": "10"}, ) # {{/docs-fragment env-with-parameter}} @app1.get("/greeting/{name}") async def greeting(name: str) -> str: return f"Hello, {name}!" # {{docs-fragment endpoint-property-pattern}} @app2.get("/app1-endpoint") async def get_app1_endpoint() -> str: return env1.endpoint @app2.get("/greeting/{name}") async def greeting_proxy(name: str) -> typing.Any: async with httpx.AsyncClient() as client: response = await client.get(f"{env1.endpoint}/greeting/{name}") return response.json() # {{/docs-fragment endpoint-property-pattern}} # {{docs-fragment endpoint-env-var-pattern}} @app2.get("/app1-url") async def get_app1_url() -> str: return os.getenv("APP1_URL") # {{/docs-fragment endpoint-env-var-pattern}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(env2) print(f"Deployed FastAPI app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/two_app_chain.py* `depends_on` is about deployment co-scheduling, not request-time ordering: at runtime each app is independent. ### Getting an upstream app's endpoint There are two ways for one app to discover another app's URL. Both resolve correctly across local, in-cluster, and external contexts. **Pattern A: `env.endpoint` (Python property).** When both apps live in the same Python module, the upstream env object is in scope and you can read `env.endpoint` directly. The example above uses this pattern in `app2`'s proxy endpoint: ``` import logging import os import pathlib import typing import httpx from fastapi import FastAPI import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("fastapi", "uvicorn", "httpx") # {{/docs-fragment image}} # {{docs-fragment apps}} app1 = FastAPI( title="App 1", description="A FastAPI app that runs some computations", ) app2 = FastAPI( title="App 2", description="A FastAPI app that proxies requests to another FastAPI app", ) # {{/docs-fragment apps}} # {{docs-fragment env-direct}} env1 = FastAPIAppEnvironment( name="app1-is-called-by-app2", app=app1, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment env-direct}} # {{docs-fragment env-with-parameter}} env2 = FastAPIAppEnvironment( name="app2-calls-app1", app=app2, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, parameters=[ flyte.app.Parameter( name="app1_url", value=flyte.app.AppEndpoint(app_name="app1-is-called-by-app2"), env_var="APP1_URL", ), ], depends_on=[env1], env_vars={"LOG_LEVEL": "10"}, ) # {{/docs-fragment env-with-parameter}} @app1.get("/greeting/{name}") async def greeting(name: str) -> str: return f"Hello, {name}!" # {{docs-fragment endpoint-property-pattern}} @app2.get("/app1-endpoint") async def get_app1_endpoint() -> str: return env1.endpoint @app2.get("/greeting/{name}") async def greeting_proxy(name: str) -> typing.Any: async with httpx.AsyncClient() as client: response = await client.get(f"{env1.endpoint}/greeting/{name}") return response.json() # {{/docs-fragment endpoint-property-pattern}} # {{docs-fragment endpoint-env-var-pattern}} @app2.get("/app1-url") async def get_app1_url() -> str: return os.getenv("APP1_URL") # {{/docs-fragment endpoint-env-var-pattern}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(env2) print(f"Deployed FastAPI app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/two_app_chain.py* **Pattern B: `flyte.app.AppEndpoint` as a parameter.** When the upstream env object isn't importable (different file, different process, looking it up by name), declare it as a `flyte.app.Parameter` and have Flyte inject the resolved URL via an environment variable. The `env2` definition above shows this. `app1_url` becomes available as `os.getenv("APP1_URL")` at runtime: ``` import logging import os import pathlib import typing import httpx from fastapi import FastAPI import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment image}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("fastapi", "uvicorn", "httpx") # {{/docs-fragment image}} # {{docs-fragment apps}} app1 = FastAPI( title="App 1", description="A FastAPI app that runs some computations", ) app2 = FastAPI( title="App 2", description="A FastAPI app that proxies requests to another FastAPI app", ) # {{/docs-fragment apps}} # {{docs-fragment env-direct}} env1 = FastAPIAppEnvironment( name="app1-is-called-by-app2", app=app1, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment env-direct}} # {{docs-fragment env-with-parameter}} env2 = FastAPIAppEnvironment( name="app2-calls-app1", app=app2, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, parameters=[ flyte.app.Parameter( name="app1_url", value=flyte.app.AppEndpoint(app_name="app1-is-called-by-app2"), env_var="APP1_URL", ), ], depends_on=[env1], env_vars={"LOG_LEVEL": "10"}, ) # {{/docs-fragment env-with-parameter}} @app1.get("/greeting/{name}") async def greeting(name: str) -> str: return f"Hello, {name}!" # {{docs-fragment endpoint-property-pattern}} @app2.get("/app1-endpoint") async def get_app1_endpoint() -> str: return env1.endpoint @app2.get("/greeting/{name}") async def greeting_proxy(name: str) -> typing.Any: async with httpx.AsyncClient() as client: response = await client.get(f"{env1.endpoint}/greeting/{name}") return response.json() # {{/docs-fragment endpoint-property-pattern}} # {{docs-fragment endpoint-env-var-pattern}} @app2.get("/app1-url") async def get_app1_url() -> str: return os.getenv("APP1_URL") # {{/docs-fragment endpoint-env-var-pattern}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(env2) print(f"Deployed FastAPI app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/two_app_chain.py* ### Sizing each node independently Each `AppEnvironment` carries its own image, resources, and scaling. That's the entire point of splitting: for example, the GPU side of an inference graph can stay narrow with `scaling=Scaling(replicas=(1, 2))` while the CPU side scales wide with `scaling=Scaling(replicas=(1, 8))`, with no shared autoscaling policy between them. The next example shows this in practice. ## Example: CPU / GPU inference split The canonical heterogeneous-resource pipeline: heavy CPU preprocessing in front of a fast GPU forward pass, talking to each other over HTTP inside the cluster. ```mermaid flowchart LR client["client"] --> cpu["cpu_app (ร—N replicas)
decode + resize
+ softmax"] cpu --> gpu["gpu_app (ร—M replicas)
ResNet18 forward only"] gpu --> cpu cpu --> client ``` In a typical vision/audio pipeline, the GPU forward pass takes milliseconds but is sandwiched between slow CPU work (image decode, resize, normalization, softmax, label lookup). If both stages share one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: cheap CPU wide, expensive GPU narrow. ### Disjoint images per node The two apps share a small base image and add their own disjoint stacks. The CPU app never imports `torch`; the GPU app never imports `PIL`: ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* ### GPU app: model.forward only The GPU app loads the model once at startup using FastAPI's lifespan, so model weights stay resident across requests: ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* The inference endpoint speaks raw `float32` bytes over `application/octet-stream`. For anything tensor-shaped this is the single biggest perf knob. JSON-serializing a 19MB batch dominates end-to-end latency: ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* The GPU environment requests a GPU and keeps replicas narrow: ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* ### CPU app: pre/postprocess + call GPU Preprocessing is deliberately CPU-bound (decode, denoise, resize, normalize): ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* The CPU app uses its lifespan to resolve the GPU endpoint via `gpu_env.endpoint`, fetch labels once at startup, and build one persistent `httpx.AsyncClient` per replica. Persistent clients avoid a TCP/TLS handshake per request, which matters at high request rates: ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* The `/classify` endpoint glues it all together. Heavy CPU work runs in this process; the GPU forward pass is delegated over HTTP using the raw-bytes wire format: ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* The CPU environment scales wide and declares `depends_on=[gpu_env]` so both sides deploy together: ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* ### Deploy `flyte.serve(cpu_env)` deploys both apps. The CPU app is the public entry point; the GPU app is reached only via the cluster-internal endpoint: ``` """ Serving graph โ€” CPU pre/post split from a GPU forward pass. This example shows the canonical "two-app" inference graph: heavy CPU work on one app, the GPU forward pass on another, talking to each other over HTTP inside the cluster. Why split? In a typical vision/audio/feature-engineering pipeline the GPU forward pass is fast (millis) but is sandwiched between slow CPU work (image decode, resize, denoise, NMS, label lookup, etc.). If you put both stages in one process you pay for an idle GPU during preprocessing. Splitting them lets each side scale independently: client โ”€โ”€โ–บ [cpu_app x N replicas] โ”€โ”€โ–บ [gpu_app x M replicas] โ”€โ”€โ–บ back preprocess + postprocess model.forward only cheap CPU, scale wide expensive GPU, scale narrow Wire format between the two apps is raw float32 bytes (not JSON) โ€” for anything tensor-shaped this is the single biggest perf knob. """ import io import ipaddress import logging import pathlib import socket from contextlib import asynccontextmanager import httpx import numpy as np from fastapi import FastAPI, HTTPException, Request, Response from PIL import Image, ImageFilter from pydantic import BaseModel import flyte import flyte.app from flyte.app.extras import FastAPIAppEnvironment # --------------------------------------------------------------------------- # Images # --------------------------------------------------------------------------- # Shared base with the deps both apps need (HTTP server + numpy). The CPU and # GPU images extend it with their own disjoint stacks โ€” the CPU app never # imports torch and the GPU app never imports PIL. Sharing the base layer # means the registry only stores one copy of fastapi/uvicorn/numpy. # {{docs-fragment images}} base_image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "numpy", ) cpu_image = base_image.with_pip_packages( "httpx", "pillow", ) gpu_image = base_image.with_pip_packages( "torch==2.7.1", "torchvision==0.22.1", ) # {{/docs-fragment images}} # --------------------------------------------------------------------------- # Shared tensor layout # --------------------------------------------------------------------------- INPUT_C, INPUT_H, INPUT_W = 3, 224, 224 NUM_CLASSES = 1000 TENSOR_DTYPE = np.float32 # =========================================================================== # GPU app โ€” model.forward only # =========================================================================== # {{docs-fragment gpu-lifespan}} @asynccontextmanager async def _gpu_lifespan(app: FastAPI): # Imported lazily so the CPU app never has to import torch. import torch from torchvision.models import ResNet18_Weights, resnet18 weights = ResNet18_Weights.IMAGENET1K_V1 model = resnet18(weights=weights).eval() device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": model = model.to("cuda") app.state.model = model app.state.device = device app.state.categories = list(weights.meta["categories"]) logging.getLogger(__name__).info("model loaded on %s", device) yield gpu_app = FastAPI( title="inference-gpu", description="ResNet18 forward pass.", lifespan=_gpu_lifespan, ) # {{/docs-fragment gpu-lifespan}} @gpu_app.get("/health") async def gpu_health() -> dict: return {"status": "ok", "device": gpu_app.state.device} @gpu_app.get("/labels") async def labels() -> list[str]: # Exposed so the CPU side can fetch labels once at startup instead of # hard-coding the ImageNet class list. return gpu_app.state.categories # {{docs-fragment gpu-infer}} @gpu_app.post("/infer") async def infer(request: Request) -> Response: """Run a batched forward pass. Request body: raw float32 bytes, shape (B, 3, 224, 224), C-contiguous. Response body: raw float32 bytes, shape (B, 1000) โ€” raw logits. We deliberately do NOT use JSON here. For a batch of 32 images the tensor is ~19MB; JSON-serializing that is the dominant cost end-to-end. """ import torch raw = await request.body() arr = np.frombuffer(raw, dtype=TENSOR_DTYPE) if arr.size % (INPUT_C * INPUT_H * INPUT_W) != 0: raise HTTPException(400, "payload size is not a multiple of one image tensor") batch = arr.reshape(-1, INPUT_C, INPUT_H, INPUT_W) x = torch.from_numpy(batch).to(gpu_app.state.device) with torch.inference_mode(): logits = gpu_app.state.model(x) out = logits.detach().to("cpu").numpy().astype(TENSOR_DTYPE, copy=False) return Response(content=out.tobytes(), media_type="application/octet-stream") # {{/docs-fragment gpu-infer}} # {{docs-fragment gpu-env}} gpu_env = FastAPIAppEnvironment( name="serving-graph-gpu", app=gpu_app, image=gpu_image, resources=flyte.Resources(cpu=2, memory="8Gi", gpu="A10G:1"), # GPU replicas are expensive; keep at least one warm so model weights stay # resident, and cap the max. Bump if a single replica saturates. scaling=flyte.app.Scaling(replicas=(1, 2)), requires_auth=True, ) # {{/docs-fragment gpu-env}} # =========================================================================== # CPU app โ€” pre/postprocess, calls the GPU app # =========================================================================== IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=TENSOR_DTYPE).reshape(3, 1, 1) IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=TENSOR_DTYPE).reshape(3, 1, 1) class ClassifyRequest(BaseModel): image_url: str top_k: int = 5 class Prediction(BaseModel): label: str score: float # {{docs-fragment cpu-preprocess}} def _preprocess(img_bytes: bytes) -> np.ndarray: """Decode โ†’ denoise โ†’ resize โ†’ normalize. CPU-bound, deliberately so. Real preprocessing stacks (detection, OCR, audio) do substantially more than this โ€” sliding window crops, color-space conversion, etc. The point is that none of it benefits from a GPU sitting next to it. """ img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img = img.filter(ImageFilter.GaussianBlur(radius=1.0)) img = img.resize((INPUT_W, INPUT_H), Image.BILINEAR) arr = np.asarray(img, dtype=TENSOR_DTYPE) / 255.0 arr = arr.transpose(2, 0, 1) # HWC โ†’ CHW arr = (arr - IMAGENET_MEAN) / IMAGENET_STD return np.ascontiguousarray(arr, dtype=TENSOR_DTYPE) # {{/docs-fragment cpu-preprocess}} def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: x = x - x.max(axis=axis, keepdims=True) e = np.exp(x) return e / e.sum(axis=axis, keepdims=True) # {{docs-fragment cpu-lifespan}} @asynccontextmanager async def _cpu_lifespan(app: FastAPI): # Resolved at serving time via the cluster-internal endpoint pattern, # so this stays correct across local/remote deploys without an env var. gpu_url = gpu_env.endpoint log = logging.getLogger(__name__) log.info("resolved GPU endpoint: %s", gpu_url) async with httpx.AsyncClient(timeout=30.0) as bootstrap: try: r = await bootstrap.get(f"{gpu_url}/labels") r.raise_for_status() except (httpx.HTTPError, OSError) as e: # Most common reason on a fresh deploy: GPU replica hasn't finished # pulling its image / loading weights yet. Crash-looping is fine โ€” # the next attempt will likely succeed โ€” but make the cause obvious. log.error("downstream GPU app at %s not ready: %s", gpu_url, e) raise app.state.labels = r.json() # One persistent client per replica โ€” avoids TCP/TLS handshake per request, # which matters once you're doing 100s of req/s. async with httpx.AsyncClient( base_url=gpu_url, timeout=httpx.Timeout(30.0, connect=5.0), limits=httpx.Limits(max_connections=64, max_keepalive_connections=32), ) as client: app.state.client = client yield cpu_app = FastAPI( title="inference-cpu", description="Pre/post around the GPU forward pass.", lifespan=_cpu_lifespan, ) # {{/docs-fragment cpu-lifespan}} @cpu_app.get("/health") async def cpu_health() -> dict: return {"status": "ok", "labels_loaded": len(cpu_app.state.labels)} # {{docs-fragment cpu-classify}} async def validate_public_image_url(image_url: str) -> str: try: parsed = httpx.URL(image_url) except Exception as exc: raise HTTPException(status_code=400, detail="Invalid image_url.") from exc if parsed.scheme not in {"http", "https"}: raise HTTPException(status_code=400, detail="image_url must use http or https.") host = parsed.host if not host: raise HTTPException(status_code=400, detail="image_url must include a hostname.") try: addr_info = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80)) except socket.gaierror as exc: raise HTTPException(status_code=400, detail="image_url host could not be resolved.") from exc for info in addr_info: ip_text = info[4][0] ip_obj = ipaddress.ip_address(ip_text) if not ip_obj.is_global: raise HTTPException(status_code=400, detail="image_url host resolves to a non-public address.") return str(parsed) @cpu_app.post("/classify", response_model=list[Prediction]) async def classify(req: ClassifyRequest) -> list[Prediction]: async with httpx.AsyncClient(timeout=30.0) as client: img_resp = await client.get(await validate_public_image_url(req.image_url)) img_resp.raise_for_status() tensor = _preprocess(img_resp.content) # heavy CPU batch = tensor[np.newaxis, ...] # add batch dim gpu_resp = await cpu_app.state.client.post( "/infer", content=batch.tobytes(), headers={"content-type": "application/octet-stream"}, ) gpu_resp.raise_for_status() logits = np.frombuffer(gpu_resp.content, dtype=TENSOR_DTYPE).reshape(1, NUM_CLASSES) probs = _softmax(logits, axis=-1)[0] # back to CPU work top_idx = np.argsort(-probs)[: req.top_k] return [Prediction(label=cpu_app.state.labels[i], score=float(probs[i])) for i in top_idx] # {{/docs-fragment cpu-classify}} # {{docs-fragment cpu-env}} cpu_env = FastAPIAppEnvironment( name="serving-graph-cpu", app=cpu_app, image=cpu_image, resources=flyte.Resources(cpu=4, memory="4Gi"), # Cheap, so scale wide. Use scale-to-zero (replicas=(0, 8)) for bursty # traffic; keep replicas=(1, 8) here to avoid cold starts in the demo. scaling=flyte.app.Scaling(replicas=(1, 8)), requires_auth=True, depends_on=[gpu_env], ) # {{/docs-fragment cpu-env}} # =========================================================================== # Deploy # =========================================================================== # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config( root_dir=pathlib.Path(__file__).parent, log_level=logging.INFO, ) app = flyte.serve(cpu_env) print(f"Deployed serving graph; public CPU endpoint: {app.url}") print("Try: curl -X POST $URL/classify -H 'content-type: application/json' \\") print( ' -d \'{"image_url": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"}\'' ) # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/image_classification.py* ## Example: A/B testing with Statsig A serving graph also lets you shape traffic. A root app routes each incoming request to one of two variant apps using a [Statsig](https://www.statsig.com/) feature gate, with consistent per-user bucketing. ```mermaid flowchart LR client["client"] --> root["root_app
(check_gate)"] root -->|"gate off"| a["app_a
fast-processing"] root -->|"gate on"| b["app_b
enhanced-processing"] ``` ### Statsig client singleton The variant routing logic needs a single Statsig client per process. Wrap it in a singleton so lifespan startup/shutdown is the only place that touches its lifecycle: ``` import os import typing from contextlib import asynccontextmanager import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment statsig-client}} class StatsigClient: """Singleton to manage Statsig client lifecycle.""" _instance: "StatsigClient | None" = None _statsig = None @classmethod def initialize(cls, api_key: str): """Initialize Statsig client (call during lifespan startup).""" if cls._instance is None: cls._instance = cls() # Import statsig at runtime (only available in container) from statsig_python_core import Statsig cls._statsig = Statsig(api_key) cls._statsig.initialize().wait() @classmethod def get_client(cls): """Get the initialized Statsig instance.""" if cls._statsig is None: raise RuntimeError("StatsigClient not initialized. Call initialize() first.") return cls._statsig @classmethod def shutdown(cls): """Shutdown Statsig client (call during lifespan shutdown).""" if cls._statsig is not None: cls._statsig.shutdown() cls._statsig = None cls._instance = None # {{/docs-fragment statsig-client}} # {{docs-fragment variant-apps}} # Image with statsig-python-core for A/B testing image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "httpx", "statsig-python-core") # App A - First variant app_a = FastAPI( title="App A", description="Variant A for A/B testing", ) # App B - Second variant app_b = FastAPI( title="App B", description="Variant B for A/B testing", ) # {{/docs-fragment variant-apps}} # {{docs-fragment root-lifespan}} @asynccontextmanager async def lifespan(_app: FastAPI): """Initialize and shutdown Statsig for A/B testing.""" # Startup: Initialize Statsig using singleton api_key = os.getenv("STATSIG_API_KEY", None) if api_key is None: raise RuntimeError(f"StatsigClient API Key not set. ENV vars {os.environ}") StatsigClient.initialize(api_key) yield # Shutdown: Cleanup Statsig StatsigClient.shutdown() # Root App - Performs A/B testing and routes to A or B root_app = FastAPI( title="Root App - A/B Testing", description="Routes requests to App A or App B based on Statsig A/B test", lifespan=lifespan, ) # {{/docs-fragment root-lifespan}} # {{docs-fragment variant-envs}} env_a = FastAPIAppEnvironment( name="app-a-variant", app=app_a, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) env_b = FastAPIAppEnvironment( name="app-b-variant", app=app_b, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment variant-envs}} # {{docs-fragment root-env}} env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[env_a, env_b], secrets=flyte.Secret("statsig-api-key", as_env_var="STATSIG_API_KEY"), ) # {{/docs-fragment root-env}} # {{docs-fragment variant-endpoints}} # App A endpoints @app_a.get("/process/{message}") async def process_a(message: str) -> dict[str, str]: return { "variant": "A", "message": f"App A processed: {message}", "algorithm": "fast-processing", } # App B endpoints @app_b.get("/process/{message}") async def process_b(message: str) -> dict[str, str]: return { "variant": "B", "message": f"App B processed: {message}", "algorithm": "enhanced-processing", } # {{/docs-fragment variant-endpoints}} # {{docs-fragment routing-endpoint}} # Root app A/B testing endpoint @root_app.get("/process/{message}") async def process_with_ab_test(message: str, user_key: str) -> dict[str, typing.Any]: """ Process a message using A/B testing to determine which app to call. Args: message: The message to process user_key: User identifier for A/B test bucketing (e.g., user_id, session_id) Returns: Response from either App A or App B, plus metadata about which variant was used """ # Import StatsigUser at runtime (only available in container) from statsig_python_core import StatsigUser # Get statsig client from singleton statsig = StatsigClient.get_client() # Create Statsig user with the provided key user = StatsigUser(user_id=user_key) # Check the feature gate "variant_b" to determine which variant # If gate is enabled, use App B; otherwise use App A use_variant_b = statsig.check_gate(user, "variant_b") # Call the appropriate app based on A/B test result async with httpx.AsyncClient() as client: if use_variant_b: endpoint = f"{env_b.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() else: endpoint = f"{env_a.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() # Add A/B test metadata to response return { "ab_test_result": { "user_key": user_key, "selected_variant": "B" if use_variant_b else "A", "gate_name": "variant_b", }, "response": result, } # {{/docs-fragment routing-endpoint}} @root_app.get("/endpoints") async def get_endpoints() -> dict[str, str]: """Get the endpoints for App A and App B.""" return { "app_a_endpoint": env_a.endpoint, "app_b_endpoint": env_b.endpoint, } @root_app.get("/") async def index(): """Serve the A/B testing demo HTML page.""" from fastapi.responses import HTMLResponse html_content = """ A/B Testing Demo - Statsig

๐ŸŽฏ A/B Testing Demo

Test Statsig-powered variant selection

๐Ÿ’ก Tip: Try different user keys to see how Statsig routes to different variants. The same user key will always get the same variant (consistent bucketing).
""" return HTMLResponse(content=html_content) # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env_root) print("Deployed A/B Testing Root App") print("\nUsage:") print(" Open your browser to '/' to access the interactive demo") print(" Or use curl: curl '/process/hello?user_key=user123'") print("\nNote: Set STATSIG_API_KEY secret to use real Statsig A/B testing.") print(" Create a feature gate named 'variant_b' in your Statsig dashboard.") # {{/docs-fragment deploy}} CODE18 import os import typing from contextlib import asynccontextmanager import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment statsig-client}} class StatsigClient: """Singleton to manage Statsig client lifecycle.""" _instance: "StatsigClient | None" = None _statsig = None @classmethod def initialize(cls, api_key: str): """Initialize Statsig client (call during lifespan startup).""" if cls._instance is None: cls._instance = cls() # Import statsig at runtime (only available in container) from statsig_python_core import Statsig cls._statsig = Statsig(api_key) cls._statsig.initialize().wait() @classmethod def get_client(cls): """Get the initialized Statsig instance.""" if cls._statsig is None: raise RuntimeError("StatsigClient not initialized. Call initialize() first.") return cls._statsig @classmethod def shutdown(cls): """Shutdown Statsig client (call during lifespan shutdown).""" if cls._statsig is not None: cls._statsig.shutdown() cls._statsig = None cls._instance = None # {{/docs-fragment statsig-client}} # {{docs-fragment variant-apps}} # Image with statsig-python-core for A/B testing image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "httpx", "statsig-python-core") # App A - First variant app_a = FastAPI( title="App A", description="Variant A for A/B testing", ) # App B - Second variant app_b = FastAPI( title="App B", description="Variant B for A/B testing", ) # {{/docs-fragment variant-apps}} # {{docs-fragment root-lifespan}} @asynccontextmanager async def lifespan(_app: FastAPI): """Initialize and shutdown Statsig for A/B testing.""" # Startup: Initialize Statsig using singleton api_key = os.getenv("STATSIG_API_KEY", None) if api_key is None: raise RuntimeError(f"StatsigClient API Key not set. ENV vars {os.environ}") StatsigClient.initialize(api_key) yield # Shutdown: Cleanup Statsig StatsigClient.shutdown() # Root App - Performs A/B testing and routes to A or B root_app = FastAPI( title="Root App - A/B Testing", description="Routes requests to App A or App B based on Statsig A/B test", lifespan=lifespan, ) # {{/docs-fragment root-lifespan}} # {{docs-fragment variant-envs}} env_a = FastAPIAppEnvironment( name="app-a-variant", app=app_a, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) env_b = FastAPIAppEnvironment( name="app-b-variant", app=app_b, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment variant-envs}} # {{docs-fragment root-env}} env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[env_a, env_b], secrets=flyte.Secret("statsig-api-key", as_env_var="STATSIG_API_KEY"), ) # {{/docs-fragment root-env}} # {{docs-fragment variant-endpoints}} # App A endpoints @app_a.get("/process/{message}") async def process_a(message: str) -> dict[str, str]: return { "variant": "A", "message": f"App A processed: {message}", "algorithm": "fast-processing", } # App B endpoints @app_b.get("/process/{message}") async def process_b(message: str) -> dict[str, str]: return { "variant": "B", "message": f"App B processed: {message}", "algorithm": "enhanced-processing", } # {{/docs-fragment variant-endpoints}} # {{docs-fragment routing-endpoint}} # Root app A/B testing endpoint @root_app.get("/process/{message}") async def process_with_ab_test(message: str, user_key: str) -> dict[str, typing.Any]: """ Process a message using A/B testing to determine which app to call. Args: message: The message to process user_key: User identifier for A/B test bucketing (e.g., user_id, session_id) Returns: Response from either App A or App B, plus metadata about which variant was used """ # Import StatsigUser at runtime (only available in container) from statsig_python_core import StatsigUser # Get statsig client from singleton statsig = StatsigClient.get_client() # Create Statsig user with the provided key user = StatsigUser(user_id=user_key) # Check the feature gate "variant_b" to determine which variant # If gate is enabled, use App B; otherwise use App A use_variant_b = statsig.check_gate(user, "variant_b") # Call the appropriate app based on A/B test result async with httpx.AsyncClient() as client: if use_variant_b: endpoint = f"{env_b.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() else: endpoint = f"{env_a.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() # Add A/B test metadata to response return { "ab_test_result": { "user_key": user_key, "selected_variant": "B" if use_variant_b else "A", "gate_name": "variant_b", }, "response": result, } # {{/docs-fragment routing-endpoint}} @root_app.get("/endpoints") async def get_endpoints() -> dict[str, str]: """Get the endpoints for App A and App B.""" return { "app_a_endpoint": env_a.endpoint, "app_b_endpoint": env_b.endpoint, } @root_app.get("/") async def index(): """Serve the A/B testing demo HTML page.""" from fastapi.responses import HTMLResponse html_content = """ A/B Testing Demo - Statsig

๐ŸŽฏ A/B Testing Demo

Test Statsig-powered variant selection

๐Ÿ’ก Tip: Try different user keys to see how Statsig routes to different variants. The same user key will always get the same variant (consistent bucketing).
""" return HTMLResponse(content=html_content) # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env_root) print("Deployed A/B Testing Root App") print("\nUsage:") print(" Open your browser to '/' to access the interactive demo") print(" Or use curl: curl '/process/hello?user_key=user123'") print("\nNote: Set STATSIG_API_KEY secret to use real Statsig A/B testing.") print(" Create a feature gate named 'variant_b' in your Statsig dashboard.") # {{/docs-fragment deploy}} CODE19 import os import typing from contextlib import asynccontextmanager import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment statsig-client}} class StatsigClient: """Singleton to manage Statsig client lifecycle.""" _instance: "StatsigClient | None" = None _statsig = None @classmethod def initialize(cls, api_key: str): """Initialize Statsig client (call during lifespan startup).""" if cls._instance is None: cls._instance = cls() # Import statsig at runtime (only available in container) from statsig_python_core import Statsig cls._statsig = Statsig(api_key) cls._statsig.initialize().wait() @classmethod def get_client(cls): """Get the initialized Statsig instance.""" if cls._statsig is None: raise RuntimeError("StatsigClient not initialized. Call initialize() first.") return cls._statsig @classmethod def shutdown(cls): """Shutdown Statsig client (call during lifespan shutdown).""" if cls._statsig is not None: cls._statsig.shutdown() cls._statsig = None cls._instance = None # {{/docs-fragment statsig-client}} # {{docs-fragment variant-apps}} # Image with statsig-python-core for A/B testing image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "httpx", "statsig-python-core") # App A - First variant app_a = FastAPI( title="App A", description="Variant A for A/B testing", ) # App B - Second variant app_b = FastAPI( title="App B", description="Variant B for A/B testing", ) # {{/docs-fragment variant-apps}} # {{docs-fragment root-lifespan}} @asynccontextmanager async def lifespan(_app: FastAPI): """Initialize and shutdown Statsig for A/B testing.""" # Startup: Initialize Statsig using singleton api_key = os.getenv("STATSIG_API_KEY", None) if api_key is None: raise RuntimeError(f"StatsigClient API Key not set. ENV vars {os.environ}") StatsigClient.initialize(api_key) yield # Shutdown: Cleanup Statsig StatsigClient.shutdown() # Root App - Performs A/B testing and routes to A or B root_app = FastAPI( title="Root App - A/B Testing", description="Routes requests to App A or App B based on Statsig A/B test", lifespan=lifespan, ) # {{/docs-fragment root-lifespan}} # {{docs-fragment variant-envs}} env_a = FastAPIAppEnvironment( name="app-a-variant", app=app_a, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) env_b = FastAPIAppEnvironment( name="app-b-variant", app=app_b, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment variant-envs}} # {{docs-fragment root-env}} env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[env_a, env_b], secrets=flyte.Secret("statsig-api-key", as_env_var="STATSIG_API_KEY"), ) # {{/docs-fragment root-env}} # {{docs-fragment variant-endpoints}} # App A endpoints @app_a.get("/process/{message}") async def process_a(message: str) -> dict[str, str]: return { "variant": "A", "message": f"App A processed: {message}", "algorithm": "fast-processing", } # App B endpoints @app_b.get("/process/{message}") async def process_b(message: str) -> dict[str, str]: return { "variant": "B", "message": f"App B processed: {message}", "algorithm": "enhanced-processing", } # {{/docs-fragment variant-endpoints}} # {{docs-fragment routing-endpoint}} # Root app A/B testing endpoint @root_app.get("/process/{message}") async def process_with_ab_test(message: str, user_key: str) -> dict[str, typing.Any]: """ Process a message using A/B testing to determine which app to call. Args: message: The message to process user_key: User identifier for A/B test bucketing (e.g., user_id, session_id) Returns: Response from either App A or App B, plus metadata about which variant was used """ # Import StatsigUser at runtime (only available in container) from statsig_python_core import StatsigUser # Get statsig client from singleton statsig = StatsigClient.get_client() # Create Statsig user with the provided key user = StatsigUser(user_id=user_key) # Check the feature gate "variant_b" to determine which variant # If gate is enabled, use App B; otherwise use App A use_variant_b = statsig.check_gate(user, "variant_b") # Call the appropriate app based on A/B test result async with httpx.AsyncClient() as client: if use_variant_b: endpoint = f"{env_b.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() else: endpoint = f"{env_a.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() # Add A/B test metadata to response return { "ab_test_result": { "user_key": user_key, "selected_variant": "B" if use_variant_b else "A", "gate_name": "variant_b", }, "response": result, } # {{/docs-fragment routing-endpoint}} @root_app.get("/endpoints") async def get_endpoints() -> dict[str, str]: """Get the endpoints for App A and App B.""" return { "app_a_endpoint": env_a.endpoint, "app_b_endpoint": env_b.endpoint, } @root_app.get("/") async def index(): """Serve the A/B testing demo HTML page.""" from fastapi.responses import HTMLResponse html_content = """ A/B Testing Demo - Statsig

๐ŸŽฏ A/B Testing Demo

Test Statsig-powered variant selection

๐Ÿ’ก Tip: Try different user keys to see how Statsig routes to different variants. The same user key will always get the same variant (consistent bucketing).
""" return HTMLResponse(content=html_content) # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env_root) print("Deployed A/B Testing Root App") print("\nUsage:") print(" Open your browser to '/' to access the interactive demo") print(" Or use curl: curl '/process/hello?user_key=user123'") print("\nNote: Set STATSIG_API_KEY secret to use real Statsig A/B testing.") print(" Create a feature gate named 'variant_b' in your Statsig dashboard.") # {{/docs-fragment deploy}} CODE20 import os import typing from contextlib import asynccontextmanager import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment statsig-client}} class StatsigClient: """Singleton to manage Statsig client lifecycle.""" _instance: "StatsigClient | None" = None _statsig = None @classmethod def initialize(cls, api_key: str): """Initialize Statsig client (call during lifespan startup).""" if cls._instance is None: cls._instance = cls() # Import statsig at runtime (only available in container) from statsig_python_core import Statsig cls._statsig = Statsig(api_key) cls._statsig.initialize().wait() @classmethod def get_client(cls): """Get the initialized Statsig instance.""" if cls._statsig is None: raise RuntimeError("StatsigClient not initialized. Call initialize() first.") return cls._statsig @classmethod def shutdown(cls): """Shutdown Statsig client (call during lifespan shutdown).""" if cls._statsig is not None: cls._statsig.shutdown() cls._statsig = None cls._instance = None # {{/docs-fragment statsig-client}} # {{docs-fragment variant-apps}} # Image with statsig-python-core for A/B testing image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "httpx", "statsig-python-core") # App A - First variant app_a = FastAPI( title="App A", description="Variant A for A/B testing", ) # App B - Second variant app_b = FastAPI( title="App B", description="Variant B for A/B testing", ) # {{/docs-fragment variant-apps}} # {{docs-fragment root-lifespan}} @asynccontextmanager async def lifespan(_app: FastAPI): """Initialize and shutdown Statsig for A/B testing.""" # Startup: Initialize Statsig using singleton api_key = os.getenv("STATSIG_API_KEY", None) if api_key is None: raise RuntimeError(f"StatsigClient API Key not set. ENV vars {os.environ}") StatsigClient.initialize(api_key) yield # Shutdown: Cleanup Statsig StatsigClient.shutdown() # Root App - Performs A/B testing and routes to A or B root_app = FastAPI( title="Root App - A/B Testing", description="Routes requests to App A or App B based on Statsig A/B test", lifespan=lifespan, ) # {{/docs-fragment root-lifespan}} # {{docs-fragment variant-envs}} env_a = FastAPIAppEnvironment( name="app-a-variant", app=app_a, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) env_b = FastAPIAppEnvironment( name="app-b-variant", app=app_b, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment variant-envs}} # {{docs-fragment root-env}} env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[env_a, env_b], secrets=flyte.Secret("statsig-api-key", as_env_var="STATSIG_API_KEY"), ) # {{/docs-fragment root-env}} # {{docs-fragment variant-endpoints}} # App A endpoints @app_a.get("/process/{message}") async def process_a(message: str) -> dict[str, str]: return { "variant": "A", "message": f"App A processed: {message}", "algorithm": "fast-processing", } # App B endpoints @app_b.get("/process/{message}") async def process_b(message: str) -> dict[str, str]: return { "variant": "B", "message": f"App B processed: {message}", "algorithm": "enhanced-processing", } # {{/docs-fragment variant-endpoints}} # {{docs-fragment routing-endpoint}} # Root app A/B testing endpoint @root_app.get("/process/{message}") async def process_with_ab_test(message: str, user_key: str) -> dict[str, typing.Any]: """ Process a message using A/B testing to determine which app to call. Args: message: The message to process user_key: User identifier for A/B test bucketing (e.g., user_id, session_id) Returns: Response from either App A or App B, plus metadata about which variant was used """ # Import StatsigUser at runtime (only available in container) from statsig_python_core import StatsigUser # Get statsig client from singleton statsig = StatsigClient.get_client() # Create Statsig user with the provided key user = StatsigUser(user_id=user_key) # Check the feature gate "variant_b" to determine which variant # If gate is enabled, use App B; otherwise use App A use_variant_b = statsig.check_gate(user, "variant_b") # Call the appropriate app based on A/B test result async with httpx.AsyncClient() as client: if use_variant_b: endpoint = f"{env_b.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() else: endpoint = f"{env_a.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() # Add A/B test metadata to response return { "ab_test_result": { "user_key": user_key, "selected_variant": "B" if use_variant_b else "A", "gate_name": "variant_b", }, "response": result, } # {{/docs-fragment routing-endpoint}} @root_app.get("/endpoints") async def get_endpoints() -> dict[str, str]: """Get the endpoints for App A and App B.""" return { "app_a_endpoint": env_a.endpoint, "app_b_endpoint": env_b.endpoint, } @root_app.get("/") async def index(): """Serve the A/B testing demo HTML page.""" from fastapi.responses import HTMLResponse html_content = """ A/B Testing Demo - Statsig

๐ŸŽฏ A/B Testing Demo

Test Statsig-powered variant selection

๐Ÿ’ก Tip: Try different user keys to see how Statsig routes to different variants. The same user key will always get the same variant (consistent bucketing).
""" return HTMLResponse(content=html_content) # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env_root) print("Deployed A/B Testing Root App") print("\nUsage:") print(" Open your browser to '/' to access the interactive demo") print(" Or use curl: curl '/process/hello?user_key=user123'") print("\nNote: Set STATSIG_API_KEY secret to use real Statsig A/B testing.") print(" Create a feature gate named 'variant_b' in your Statsig dashboard.") # {{/docs-fragment deploy}} CODE21 import os import typing from contextlib import asynccontextmanager import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment statsig-client}} class StatsigClient: """Singleton to manage Statsig client lifecycle.""" _instance: "StatsigClient | None" = None _statsig = None @classmethod def initialize(cls, api_key: str): """Initialize Statsig client (call during lifespan startup).""" if cls._instance is None: cls._instance = cls() # Import statsig at runtime (only available in container) from statsig_python_core import Statsig cls._statsig = Statsig(api_key) cls._statsig.initialize().wait() @classmethod def get_client(cls): """Get the initialized Statsig instance.""" if cls._statsig is None: raise RuntimeError("StatsigClient not initialized. Call initialize() first.") return cls._statsig @classmethod def shutdown(cls): """Shutdown Statsig client (call during lifespan shutdown).""" if cls._statsig is not None: cls._statsig.shutdown() cls._statsig = None cls._instance = None # {{/docs-fragment statsig-client}} # {{docs-fragment variant-apps}} # Image with statsig-python-core for A/B testing image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "httpx", "statsig-python-core") # App A - First variant app_a = FastAPI( title="App A", description="Variant A for A/B testing", ) # App B - Second variant app_b = FastAPI( title="App B", description="Variant B for A/B testing", ) # {{/docs-fragment variant-apps}} # {{docs-fragment root-lifespan}} @asynccontextmanager async def lifespan(_app: FastAPI): """Initialize and shutdown Statsig for A/B testing.""" # Startup: Initialize Statsig using singleton api_key = os.getenv("STATSIG_API_KEY", None) if api_key is None: raise RuntimeError(f"StatsigClient API Key not set. ENV vars {os.environ}") StatsigClient.initialize(api_key) yield # Shutdown: Cleanup Statsig StatsigClient.shutdown() # Root App - Performs A/B testing and routes to A or B root_app = FastAPI( title="Root App - A/B Testing", description="Routes requests to App A or App B based on Statsig A/B test", lifespan=lifespan, ) # {{/docs-fragment root-lifespan}} # {{docs-fragment variant-envs}} env_a = FastAPIAppEnvironment( name="app-a-variant", app=app_a, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) env_b = FastAPIAppEnvironment( name="app-b-variant", app=app_b, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment variant-envs}} # {{docs-fragment root-env}} env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[env_a, env_b], secrets=flyte.Secret("statsig-api-key", as_env_var="STATSIG_API_KEY"), ) # {{/docs-fragment root-env}} # {{docs-fragment variant-endpoints}} # App A endpoints @app_a.get("/process/{message}") async def process_a(message: str) -> dict[str, str]: return { "variant": "A", "message": f"App A processed: {message}", "algorithm": "fast-processing", } # App B endpoints @app_b.get("/process/{message}") async def process_b(message: str) -> dict[str, str]: return { "variant": "B", "message": f"App B processed: {message}", "algorithm": "enhanced-processing", } # {{/docs-fragment variant-endpoints}} # {{docs-fragment routing-endpoint}} # Root app A/B testing endpoint @root_app.get("/process/{message}") async def process_with_ab_test(message: str, user_key: str) -> dict[str, typing.Any]: """ Process a message using A/B testing to determine which app to call. Args: message: The message to process user_key: User identifier for A/B test bucketing (e.g., user_id, session_id) Returns: Response from either App A or App B, plus metadata about which variant was used """ # Import StatsigUser at runtime (only available in container) from statsig_python_core import StatsigUser # Get statsig client from singleton statsig = StatsigClient.get_client() # Create Statsig user with the provided key user = StatsigUser(user_id=user_key) # Check the feature gate "variant_b" to determine which variant # If gate is enabled, use App B; otherwise use App A use_variant_b = statsig.check_gate(user, "variant_b") # Call the appropriate app based on A/B test result async with httpx.AsyncClient() as client: if use_variant_b: endpoint = f"{env_b.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() else: endpoint = f"{env_a.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() # Add A/B test metadata to response return { "ab_test_result": { "user_key": user_key, "selected_variant": "B" if use_variant_b else "A", "gate_name": "variant_b", }, "response": result, } # {{/docs-fragment routing-endpoint}} @root_app.get("/endpoints") async def get_endpoints() -> dict[str, str]: """Get the endpoints for App A and App B.""" return { "app_a_endpoint": env_a.endpoint, "app_b_endpoint": env_b.endpoint, } @root_app.get("/") async def index(): """Serve the A/B testing demo HTML page.""" from fastapi.responses import HTMLResponse html_content = """ A/B Testing Demo - Statsig

๐ŸŽฏ A/B Testing Demo

Test Statsig-powered variant selection

๐Ÿ’ก Tip: Try different user keys to see how Statsig routes to different variants. The same user key will always get the same variant (consistent bucketing).
""" return HTMLResponse(content=html_content) # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env_root) print("Deployed A/B Testing Root App") print("\nUsage:") print(" Open your browser to '/' to access the interactive demo") print(" Or use curl: curl '/process/hello?user_key=user123'") print("\nNote: Set STATSIG_API_KEY secret to use real Statsig A/B testing.") print(" Create a feature gate named 'variant_b' in your Statsig dashboard.") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/ab_testing.py* The root env declares `depends_on=[env_a, env_b]` so all three deploy together, and pulls the Statsig API key from a Flyte secret: ``` import os import typing from contextlib import asynccontextmanager import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment statsig-client}} class StatsigClient: """Singleton to manage Statsig client lifecycle.""" _instance: "StatsigClient | None" = None _statsig = None @classmethod def initialize(cls, api_key: str): """Initialize Statsig client (call during lifespan startup).""" if cls._instance is None: cls._instance = cls() # Import statsig at runtime (only available in container) from statsig_python_core import Statsig cls._statsig = Statsig(api_key) cls._statsig.initialize().wait() @classmethod def get_client(cls): """Get the initialized Statsig instance.""" if cls._statsig is None: raise RuntimeError("StatsigClient not initialized. Call initialize() first.") return cls._statsig @classmethod def shutdown(cls): """Shutdown Statsig client (call during lifespan shutdown).""" if cls._statsig is not None: cls._statsig.shutdown() cls._statsig = None cls._instance = None # {{/docs-fragment statsig-client}} # {{docs-fragment variant-apps}} # Image with statsig-python-core for A/B testing image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "httpx", "statsig-python-core") # App A - First variant app_a = FastAPI( title="App A", description="Variant A for A/B testing", ) # App B - Second variant app_b = FastAPI( title="App B", description="Variant B for A/B testing", ) # {{/docs-fragment variant-apps}} # {{docs-fragment root-lifespan}} @asynccontextmanager async def lifespan(_app: FastAPI): """Initialize and shutdown Statsig for A/B testing.""" # Startup: Initialize Statsig using singleton api_key = os.getenv("STATSIG_API_KEY", None) if api_key is None: raise RuntimeError(f"StatsigClient API Key not set. ENV vars {os.environ}") StatsigClient.initialize(api_key) yield # Shutdown: Cleanup Statsig StatsigClient.shutdown() # Root App - Performs A/B testing and routes to A or B root_app = FastAPI( title="Root App - A/B Testing", description="Routes requests to App A or App B based on Statsig A/B test", lifespan=lifespan, ) # {{/docs-fragment root-lifespan}} # {{docs-fragment variant-envs}} env_a = FastAPIAppEnvironment( name="app-a-variant", app=app_a, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) env_b = FastAPIAppEnvironment( name="app-b-variant", app=app_b, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment variant-envs}} # {{docs-fragment root-env}} env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[env_a, env_b], secrets=flyte.Secret("statsig-api-key", as_env_var="STATSIG_API_KEY"), ) # {{/docs-fragment root-env}} # {{docs-fragment variant-endpoints}} # App A endpoints @app_a.get("/process/{message}") async def process_a(message: str) -> dict[str, str]: return { "variant": "A", "message": f"App A processed: {message}", "algorithm": "fast-processing", } # App B endpoints @app_b.get("/process/{message}") async def process_b(message: str) -> dict[str, str]: return { "variant": "B", "message": f"App B processed: {message}", "algorithm": "enhanced-processing", } # {{/docs-fragment variant-endpoints}} # {{docs-fragment routing-endpoint}} # Root app A/B testing endpoint @root_app.get("/process/{message}") async def process_with_ab_test(message: str, user_key: str) -> dict[str, typing.Any]: """ Process a message using A/B testing to determine which app to call. Args: message: The message to process user_key: User identifier for A/B test bucketing (e.g., user_id, session_id) Returns: Response from either App A or App B, plus metadata about which variant was used """ # Import StatsigUser at runtime (only available in container) from statsig_python_core import StatsigUser # Get statsig client from singleton statsig = StatsigClient.get_client() # Create Statsig user with the provided key user = StatsigUser(user_id=user_key) # Check the feature gate "variant_b" to determine which variant # If gate is enabled, use App B; otherwise use App A use_variant_b = statsig.check_gate(user, "variant_b") # Call the appropriate app based on A/B test result async with httpx.AsyncClient() as client: if use_variant_b: endpoint = f"{env_b.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() else: endpoint = f"{env_a.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() # Add A/B test metadata to response return { "ab_test_result": { "user_key": user_key, "selected_variant": "B" if use_variant_b else "A", "gate_name": "variant_b", }, "response": result, } # {{/docs-fragment routing-endpoint}} @root_app.get("/endpoints") async def get_endpoints() -> dict[str, str]: """Get the endpoints for App A and App B.""" return { "app_a_endpoint": env_a.endpoint, "app_b_endpoint": env_b.endpoint, } @root_app.get("/") async def index(): """Serve the A/B testing demo HTML page.""" from fastapi.responses import HTMLResponse html_content = """ A/B Testing Demo - Statsig

๐ŸŽฏ A/B Testing Demo

Test Statsig-powered variant selection

๐Ÿ’ก Tip: Try different user keys to see how Statsig routes to different variants. The same user key will always get the same variant (consistent bucketing).
""" return HTMLResponse(content=html_content) # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env_root) print("Deployed A/B Testing Root App") print("\nUsage:") print(" Open your browser to '/' to access the interactive demo") print(" Or use curl: curl '/process/hello?user_key=user123'") print("\nNote: Set STATSIG_API_KEY secret to use real Statsig A/B testing.") print(" Create a feature gate named 'variant_b' in your Statsig dashboard.") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/ab_testing.py* ### Routing endpoint The root app checks the `variant_b` feature gate against a user key and proxies to the matching variant using its `endpoint` property: ``` import os import typing from contextlib import asynccontextmanager import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment statsig-client}} class StatsigClient: """Singleton to manage Statsig client lifecycle.""" _instance: "StatsigClient | None" = None _statsig = None @classmethod def initialize(cls, api_key: str): """Initialize Statsig client (call during lifespan startup).""" if cls._instance is None: cls._instance = cls() # Import statsig at runtime (only available in container) from statsig_python_core import Statsig cls._statsig = Statsig(api_key) cls._statsig.initialize().wait() @classmethod def get_client(cls): """Get the initialized Statsig instance.""" if cls._statsig is None: raise RuntimeError("StatsigClient not initialized. Call initialize() first.") return cls._statsig @classmethod def shutdown(cls): """Shutdown Statsig client (call during lifespan shutdown).""" if cls._statsig is not None: cls._statsig.shutdown() cls._statsig = None cls._instance = None # {{/docs-fragment statsig-client}} # {{docs-fragment variant-apps}} # Image with statsig-python-core for A/B testing image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "httpx", "statsig-python-core") # App A - First variant app_a = FastAPI( title="App A", description="Variant A for A/B testing", ) # App B - Second variant app_b = FastAPI( title="App B", description="Variant B for A/B testing", ) # {{/docs-fragment variant-apps}} # {{docs-fragment root-lifespan}} @asynccontextmanager async def lifespan(_app: FastAPI): """Initialize and shutdown Statsig for A/B testing.""" # Startup: Initialize Statsig using singleton api_key = os.getenv("STATSIG_API_KEY", None) if api_key is None: raise RuntimeError(f"StatsigClient API Key not set. ENV vars {os.environ}") StatsigClient.initialize(api_key) yield # Shutdown: Cleanup Statsig StatsigClient.shutdown() # Root App - Performs A/B testing and routes to A or B root_app = FastAPI( title="Root App - A/B Testing", description="Routes requests to App A or App B based on Statsig A/B test", lifespan=lifespan, ) # {{/docs-fragment root-lifespan}} # {{docs-fragment variant-envs}} env_a = FastAPIAppEnvironment( name="app-a-variant", app=app_a, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) env_b = FastAPIAppEnvironment( name="app-b-variant", app=app_b, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment variant-envs}} # {{docs-fragment root-env}} env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[env_a, env_b], secrets=flyte.Secret("statsig-api-key", as_env_var="STATSIG_API_KEY"), ) # {{/docs-fragment root-env}} # {{docs-fragment variant-endpoints}} # App A endpoints @app_a.get("/process/{message}") async def process_a(message: str) -> dict[str, str]: return { "variant": "A", "message": f"App A processed: {message}", "algorithm": "fast-processing", } # App B endpoints @app_b.get("/process/{message}") async def process_b(message: str) -> dict[str, str]: return { "variant": "B", "message": f"App B processed: {message}", "algorithm": "enhanced-processing", } # {{/docs-fragment variant-endpoints}} # {{docs-fragment routing-endpoint}} # Root app A/B testing endpoint @root_app.get("/process/{message}") async def process_with_ab_test(message: str, user_key: str) -> dict[str, typing.Any]: """ Process a message using A/B testing to determine which app to call. Args: message: The message to process user_key: User identifier for A/B test bucketing (e.g., user_id, session_id) Returns: Response from either App A or App B, plus metadata about which variant was used """ # Import StatsigUser at runtime (only available in container) from statsig_python_core import StatsigUser # Get statsig client from singleton statsig = StatsigClient.get_client() # Create Statsig user with the provided key user = StatsigUser(user_id=user_key) # Check the feature gate "variant_b" to determine which variant # If gate is enabled, use App B; otherwise use App A use_variant_b = statsig.check_gate(user, "variant_b") # Call the appropriate app based on A/B test result async with httpx.AsyncClient() as client: if use_variant_b: endpoint = f"{env_b.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() else: endpoint = f"{env_a.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() # Add A/B test metadata to response return { "ab_test_result": { "user_key": user_key, "selected_variant": "B" if use_variant_b else "A", "gate_name": "variant_b", }, "response": result, } # {{/docs-fragment routing-endpoint}} @root_app.get("/endpoints") async def get_endpoints() -> dict[str, str]: """Get the endpoints for App A and App B.""" return { "app_a_endpoint": env_a.endpoint, "app_b_endpoint": env_b.endpoint, } @root_app.get("/") async def index(): """Serve the A/B testing demo HTML page.""" from fastapi.responses import HTMLResponse html_content = """ A/B Testing Demo - Statsig

๐ŸŽฏ A/B Testing Demo

Test Statsig-powered variant selection

๐Ÿ’ก Tip: Try different user keys to see how Statsig routes to different variants. The same user key will always get the same variant (consistent bucketing).
""" return HTMLResponse(content=html_content) # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env_root) print("Deployed A/B Testing Root App") print("\nUsage:") print(" Open your browser to '/' to access the interactive demo") print(" Or use curl: curl '/process/hello?user_key=user123'") print("\nNote: Set STATSIG_API_KEY secret to use real Statsig A/B testing.") print(" Create a feature gate named 'variant_b' in your Statsig dashboard.") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/ab_testing.py* Use stable identifiers (user ID, session ID) for `user_key` so the same user always lands in the same bucket. To swap `check_gate` for an experiment or dynamic config: CODE22 ### Deploy ``` import os import typing from contextlib import asynccontextmanager import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment statsig-client}} class StatsigClient: """Singleton to manage Statsig client lifecycle.""" _instance: "StatsigClient | None" = None _statsig = None @classmethod def initialize(cls, api_key: str): """Initialize Statsig client (call during lifespan startup).""" if cls._instance is None: cls._instance = cls() # Import statsig at runtime (only available in container) from statsig_python_core import Statsig cls._statsig = Statsig(api_key) cls._statsig.initialize().wait() @classmethod def get_client(cls): """Get the initialized Statsig instance.""" if cls._statsig is None: raise RuntimeError("StatsigClient not initialized. Call initialize() first.") return cls._statsig @classmethod def shutdown(cls): """Shutdown Statsig client (call during lifespan shutdown).""" if cls._statsig is not None: cls._statsig.shutdown() cls._statsig = None cls._instance = None # {{/docs-fragment statsig-client}} # {{docs-fragment variant-apps}} # Image with statsig-python-core for A/B testing image = flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "httpx", "statsig-python-core") # App A - First variant app_a = FastAPI( title="App A", description="Variant A for A/B testing", ) # App B - Second variant app_b = FastAPI( title="App B", description="Variant B for A/B testing", ) # {{/docs-fragment variant-apps}} # {{docs-fragment root-lifespan}} @asynccontextmanager async def lifespan(_app: FastAPI): """Initialize and shutdown Statsig for A/B testing.""" # Startup: Initialize Statsig using singleton api_key = os.getenv("STATSIG_API_KEY", None) if api_key is None: raise RuntimeError(f"StatsigClient API Key not set. ENV vars {os.environ}") StatsigClient.initialize(api_key) yield # Shutdown: Cleanup Statsig StatsigClient.shutdown() # Root App - Performs A/B testing and routes to A or B root_app = FastAPI( title="Root App - A/B Testing", description="Routes requests to App A or App B based on Statsig A/B test", lifespan=lifespan, ) # {{/docs-fragment root-lifespan}} # {{docs-fragment variant-envs}} env_a = FastAPIAppEnvironment( name="app-a-variant", app=app_a, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) env_b = FastAPIAppEnvironment( name="app-b-variant", app=app_b, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment variant-envs}} # {{docs-fragment root-env}} env_root = FastAPIAppEnvironment( name="root-ab-testing-app", app=root_app, image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[env_a, env_b], secrets=flyte.Secret("statsig-api-key", as_env_var="STATSIG_API_KEY"), ) # {{/docs-fragment root-env}} # {{docs-fragment variant-endpoints}} # App A endpoints @app_a.get("/process/{message}") async def process_a(message: str) -> dict[str, str]: return { "variant": "A", "message": f"App A processed: {message}", "algorithm": "fast-processing", } # App B endpoints @app_b.get("/process/{message}") async def process_b(message: str) -> dict[str, str]: return { "variant": "B", "message": f"App B processed: {message}", "algorithm": "enhanced-processing", } # {{/docs-fragment variant-endpoints}} # {{docs-fragment routing-endpoint}} # Root app A/B testing endpoint @root_app.get("/process/{message}") async def process_with_ab_test(message: str, user_key: str) -> dict[str, typing.Any]: """ Process a message using A/B testing to determine which app to call. Args: message: The message to process user_key: User identifier for A/B test bucketing (e.g., user_id, session_id) Returns: Response from either App A or App B, plus metadata about which variant was used """ # Import StatsigUser at runtime (only available in container) from statsig_python_core import StatsigUser # Get statsig client from singleton statsig = StatsigClient.get_client() # Create Statsig user with the provided key user = StatsigUser(user_id=user_key) # Check the feature gate "variant_b" to determine which variant # If gate is enabled, use App B; otherwise use App A use_variant_b = statsig.check_gate(user, "variant_b") # Call the appropriate app based on A/B test result async with httpx.AsyncClient() as client: if use_variant_b: endpoint = f"{env_b.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() else: endpoint = f"{env_a.endpoint}/process/{message}" response = await client.get(endpoint) result = response.json() # Add A/B test metadata to response return { "ab_test_result": { "user_key": user_key, "selected_variant": "B" if use_variant_b else "A", "gate_name": "variant_b", }, "response": result, } # {{/docs-fragment routing-endpoint}} @root_app.get("/endpoints") async def get_endpoints() -> dict[str, str]: """Get the endpoints for App A and App B.""" return { "app_a_endpoint": env_a.endpoint, "app_b_endpoint": env_b.endpoint, } @root_app.get("/") async def index(): """Serve the A/B testing demo HTML page.""" from fastapi.responses import HTMLResponse html_content = """ A/B Testing Demo - Statsig

๐ŸŽฏ A/B Testing Demo

Test Statsig-powered variant selection

๐Ÿ’ก Tip: Try different user keys to see how Statsig routes to different variants. The same user key will always get the same variant (consistent bucketing).
""" return HTMLResponse(content=html_content) # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() flyte.deploy(env_root) print("Deployed A/B Testing Root App") print("\nUsage:") print(" Open your browser to '/' to access the interactive demo") print(" Or use curl: curl '/process/hello?user_key=user123'") print("\nNote: Set STATSIG_API_KEY secret to use real Statsig A/B testing.") print(" Create a feature gate named 'variant_b' in your Statsig dashboard.") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/serving_graphs/ab_testing.py* **Setup before running:** 1. Get a Server Secret Key at [statsig.com](https://www.statsig.com/) โ†’ Settings โ†’ API Keys. 2. Create a feature gate named `variant_b` (e.g. 50% rollout). 3. Set the Flyte secret: CODE23 ## When to split into a serving graph Split when stages have: - **Different bottlenecks**: CPU vs GPU vs memory - **Different scaling needs**: bursty vs steady, wide vs narrow - **Different lifecycles**: model weights you don't want to reload, expensive cold starts - **Different routing concerns**: A/B, canary, proxy, gateway Don't split just to separate code; a single app with a few endpoints is simpler to operate. ## Best practices 1. **Use `depends_on`**: Always specify dependencies to ensure the dependency closure is deployed in one shot. 2. **Persistent HTTP clients**: Open one `httpx.AsyncClient` per replica in the app's lifespan rather than per request, to avoid TCP/TLS setup overhead. 3. **Pick the right wire format**: For tensor-shaped payloads, send raw bytes over `application/octet-stream` instead of JSON. 4. **Size each node independently**: GPU narrow, CPU wide; use scale-to-zero (`replicas=(0, N)`) for bursty downstream services. 5. **Authentication**: Use `requires_auth=True` on internal-only apps so they can't be reached from the public internet, and put public-facing auth on the entry-point app. 6. **Endpoint access**: Prefer `app_env.endpoint` for in-module references; use `flyte.app.AppEndpoint` parameters when the upstream env isn't importable. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps/hybrid-graphs === Have tasks call apps over HTTP and apps trigger runs through the SDK. # Hybrid app-task graphs Apps and tasks can interact with each other: tasks can call apps via HTTP, and apps can trigger task execution via the Flyte SDK. This page covers both patterns. ## Call app from task Tasks can call apps by making HTTP requests to the app's endpoint. This is useful when: - You need to use a long-running service during task execution - You want to call a model serving endpoint from a batch processing task - You need to interact with an API from a workflow ### Example: FastAPI app called from a task ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "httpx", # ] # /// """Example of a task calling an app.""" import pathlib import httpx from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment app = FastAPI(title="Add One", description="Adds one to the input", version="1.0.0") image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("fastapi", "uvicorn", "httpx") # {{docs-fragment app-definition}} app_env = FastAPIAppEnvironment( name="add-one-app", app=app, description="Adds one to the input", image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, ) # {{/docs-fragment app-definition}} # {{docs-fragment task-env}} task_env = flyte.TaskEnvironment( name="add_one_task_env", image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), depends_on=[app_env], # Deploying task_env also deploys app_env ) # {{/docs-fragment task-env}} # {{docs-fragment app-endpoint}} @app.get("/") async def add_one(x: int) -> dict[str, int]: """Main endpoint for the add-one app.""" return {"result": x + 1} # {{/docs-fragment app-endpoint}} # {{docs-fragment task}} @task_env.task async def add_one_task(x: int) -> int: print(f"Calling app at {app_env.endpoint}") async with httpx.AsyncClient() as client: response = await client.get(app_env.endpoint, params={"x": x}) response.raise_for_status() return response.json()["result"] # {{/docs-fragment task}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployments = flyte.deploy(task_env) print(f"Deployed task environment: {deployments}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/task_calling_app.py* Key points: - The task environment uses `depends_on=[app_env]`, so deploying `task_env` also deploys the app - Access the app endpoint via `app_env.endpoint` - Use standard HTTP client libraries (like `httpx`) to make requests ## Call task from app (webhooks / APIs) Apps can trigger task execution using the Flyte SDK. This is useful for: - Webhooks that trigger workflows - APIs that need to run batch jobs - Services that need to execute tasks asynchronously Webhooks are HTTP endpoints that trigger actions in response to external events. Flyte apps can serve as webhook endpoints that trigger task runs, workflows, or other operations. ### Example: Basic webhook app Here's a simple webhook that triggers Flyte tasks: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """A webhook that triggers Flyte tasks.""" import pathlib from fastapi import FastAPI, HTTPException, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from starlette import status import os from contextlib import asynccontextmanager import flyte import flyte.remote as remote from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment auth}} WEBHOOK_API_KEY = os.getenv("WEBHOOK_API_KEY", "test-api-key") security = HTTPBearer() async def verify_token( credentials: HTTPAuthorizationCredentials = Security(security), ) -> HTTPAuthorizationCredentials: """Verify the API key from the bearer token.""" if credentials.credentials != WEBHOOK_API_KEY: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) return credentials # {{/docs-fragment auth}} # {{docs-fragment lifespan}} @asynccontextmanager async def lifespan(app: FastAPI): """Initialize Flyte before accepting requests.""" await flyte.init_in_cluster.aio() yield # Cleanup if needed # {{/docs-fragment lifespan}} # {{docs-fragment app}} app = FastAPI( title="Flyte Webhook Runner", description="A webhook service that triggers Flyte task runs", version="1.0.0", lifespan=lifespan, ) @app.get("/health") async def health_check(): """Health check endpoint.""" return {"status": "healthy"} # {{/docs-fragment app}} # {{docs-fragment webhook-endpoint}} @app.post("/run-task/{project}/{domain}/{name}/{version}") async def run_task( project: str, domain: str, name: str, version: str, inputs: dict, credentials: HTTPAuthorizationCredentials = Security(verify_token), ): """ Trigger a Flyte task run via webhook. Returns information about the launched run. """ # Fetch the task task = remote.Task.get( project=project, domain=domain, name=name, version=version, ) # Run the task run = await flyte.run.aio(task, **inputs) return { "url": run.url, "id": run.name, "status": "started", } # {{/docs-fragment webhook-endpoint}} # {{docs-fragment env}} env = FastAPIAppEnvironment( name="webhook-runner", app=app, description="A webhook service that triggers Flyte task runs", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, # We handle auth in the app env_vars={"WEBHOOK_API_KEY": os.getenv("WEBHOOK_API_KEY", "test-api-key")}, ) # {{/docs-fragment env}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed webhook: {app_deployment[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/webhook/basic_webhook.py* Once deployed, you can trigger tasks via HTTP POST: ```bash curl -X POST "https://your-webhook-url/run-task/flytesnacks/development/my_task/v1" \ -H "Authorization: Bearer test-api-key" \ -H "Content-Type: application/json" \ -d '{"input_key": "input_value"}' ``` Response: ```json { "url": "https://console.union.ai/...", "id": "abc123", "status": "started" } ``` ### Advanced webhook patterns **Webhook with validation** Use Pydantic for input validation: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """A webhook with Pydantic validation.""" import pathlib from fastapi import FastAPI, HTTPException, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from starlette import status import os from contextlib import asynccontextmanager from pydantic import BaseModel import flyte import flyte.remote as remote from flyte.app.extras import FastAPIAppEnvironment WEBHOOK_API_KEY = os.getenv("WEBHOOK_API_KEY", "test-api-key") security = HTTPBearer() async def verify_token( credentials: HTTPAuthorizationCredentials = Security(security), ) -> HTTPAuthorizationCredentials: """Verify the API key from the bearer token.""" if credentials.credentials != WEBHOOK_API_KEY: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) return credentials @asynccontextmanager async def lifespan(app: FastAPI): """Initialize Flyte before accepting requests.""" await flyte.init_in_cluster.aio() yield app = FastAPI( title="Flyte Webhook Runner with Validation", description="A webhook service that triggers Flyte task runs with Pydantic validation", version="1.0.0", lifespan=lifespan, ) # {{docs-fragment validation-model}} class TaskInput(BaseModel): data: dict priority: int = 0 # {{/docs-fragment validation-model}} # {{docs-fragment validated-webhook}} @app.post("/run-task/{project}/{domain}/{name}/{version}") async def run_task( project: str, domain: str, name: str, version: str, inputs: TaskInput, # Validated input credentials: HTTPAuthorizationCredentials = Security(verify_token), ): task = remote.Task.get( project=project, domain=domain, name=name, version=version, ) run = await flyte.run.aio(task, **inputs.model_dump()) return { "run_id": run.name, "url": run.url, } # {{/docs-fragment validated-webhook}} env = FastAPIAppEnvironment( name="webhook-with-validation", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, env_vars={"WEBHOOK_API_KEY": os.getenv("WEBHOOK_API_KEY", "test-api-key")}, ) if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed webhook: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/webhook_validation.py* ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """A webhook with Pydantic validation.""" import pathlib from fastapi import FastAPI, HTTPException, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from starlette import status import os from contextlib import asynccontextmanager from pydantic import BaseModel import flyte import flyte.remote as remote from flyte.app.extras import FastAPIAppEnvironment WEBHOOK_API_KEY = os.getenv("WEBHOOK_API_KEY", "test-api-key") security = HTTPBearer() async def verify_token( credentials: HTTPAuthorizationCredentials = Security(security), ) -> HTTPAuthorizationCredentials: """Verify the API key from the bearer token.""" if credentials.credentials != WEBHOOK_API_KEY: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) return credentials @asynccontextmanager async def lifespan(app: FastAPI): """Initialize Flyte before accepting requests.""" await flyte.init_in_cluster.aio() yield app = FastAPI( title="Flyte Webhook Runner with Validation", description="A webhook service that triggers Flyte task runs with Pydantic validation", version="1.0.0", lifespan=lifespan, ) # {{docs-fragment validation-model}} class TaskInput(BaseModel): data: dict priority: int = 0 # {{/docs-fragment validation-model}} # {{docs-fragment validated-webhook}} @app.post("/run-task/{project}/{domain}/{name}/{version}") async def run_task( project: str, domain: str, name: str, version: str, inputs: TaskInput, # Validated input credentials: HTTPAuthorizationCredentials = Security(verify_token), ): task = remote.Task.get( project=project, domain=domain, name=name, version=version, ) run = await flyte.run.aio(task, **inputs.model_dump()) return { "run_id": run.name, "url": run.url, } # {{/docs-fragment validated-webhook}} env = FastAPIAppEnvironment( name="webhook-with-validation", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, env_vars={"WEBHOOK_API_KEY": os.getenv("WEBHOOK_API_KEY", "test-api-key")}, ) if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed webhook: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/webhook_validation.py* **Webhook with response waiting** Wait for task completion: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """A webhook that waits for task completion.""" import pathlib from fastapi import FastAPI, HTTPException, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from starlette import status import os from contextlib import asynccontextmanager import flyte import flyte.remote as remote from flyte.app.extras import FastAPIAppEnvironment WEBHOOK_API_KEY = os.getenv("WEBHOOK_API_KEY", "test-api-key") security = HTTPBearer() async def verify_token( credentials: HTTPAuthorizationCredentials = Security(security), ) -> HTTPAuthorizationCredentials: """Verify the API key from the bearer token.""" if credentials.credentials != WEBHOOK_API_KEY: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) return credentials @asynccontextmanager async def lifespan(app: FastAPI): """Initialize Flyte before accepting requests.""" await flyte.init_in_cluster.aio() yield app = FastAPI( title="Flyte Webhook Runner (Wait for Completion)", description="A webhook service that triggers Flyte task runs and waits for completion", version="1.0.0", lifespan=lifespan, ) # {{docs-fragment wait-webhook}} @app.post("/run-task-and-wait/{project}/{domain}/{name}/{version}") async def run_task_and_wait( project: str, domain: str, name: str, version: str, inputs: dict, credentials: HTTPAuthorizationCredentials = Security(verify_token), ): task = remote.Task.get( project=project, domain=domain, name=name, version=version, ) run = await flyte.run.aio(task, **inputs) await run.wait.aio() # Wait for completion return { "run_id": run.name, "url": run.url, "status": run.phase, "outputs": await run.outputs.aio(), } # {{/docs-fragment wait-webhook}} env = FastAPIAppEnvironment( name="webhook-wait-completion", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, env_vars={"WEBHOOK_API_KEY": os.getenv("WEBHOOK_API_KEY", "test-api-key")}, ) if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed webhook: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/webhook_wait.py* **Webhook with secret management** Use Flyte secrets for API keys: ```python env = FastAPIAppEnvironment( name="webhook-runner", app=app, secrets=flyte.Secret(key="webhook-api-key", as_env_var="WEBHOOK_API_KEY"), # ... ) ``` Then access in your app: ```python WEBHOOK_API_KEY = os.getenv("WEBHOOK_API_KEY") ``` ### Webhook security and best practices - **Authentication**: Always secure webhooks with authentication (API keys, tokens, etc.). - **Input validation**: Validate webhook inputs using Pydantic models. - **Error handling**: Handle errors gracefully and return meaningful error messages. - **Async operations**: Use async/await for I/O operations. - **Health checks**: Include health check endpoints. - **Logging**: Log webhook requests for debugging and auditing. - **Rate limiting**: Consider implementing rate limiting for production. Security considerations: - Store API keys in Flyte secrets, not in code. - Always use HTTPS in production. - Validate all inputs to prevent injection attacks. - Implement proper access control mechanisms. - Log all webhook invocations for security auditing. ### Example: GitHub webhook Here's an example webhook that triggers tasks based on GitHub events: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """A GitHub webhook that triggers Flyte tasks based on GitHub events.""" import pathlib import hmac import hashlib import os from contextlib import asynccontextmanager from fastapi import FastAPI, Request, Header, HTTPException import flyte import flyte.remote as remote from flyte.app.extras import FastAPIAppEnvironment @asynccontextmanager async def lifespan(app: FastAPI): """Initialize Flyte before accepting requests.""" await flyte.init_in_cluster.aio() yield app = FastAPI( title="GitHub Webhook Handler", description="Triggers Flyte tasks based on GitHub events", version="1.0.0", lifespan=lifespan, ) # {{docs-fragment github-webhook}} @app.post("/github-webhook") async def github_webhook( request: Request, x_hub_signature_256: str = Header(None), ): """Handle GitHub webhook events.""" body = await request.body() # Verify signature secret = os.getenv("GITHUB_WEBHOOK_SECRET") signature = hmac.new( secret.encode(), body, hashlib.sha256 ).hexdigest() expected_signature = f"sha256={signature}" if not hmac.compare_digest(x_hub_signature_256, expected_signature): raise HTTPException(status_code=403, detail="Invalid signature") # Process webhook event = await request.json() event_type = request.headers.get("X-GitHub-Event") if event_type == "push": # Trigger deployment task task = remote.Task.get( project="my-project", domain="development", name="deploy-task", version="v1", ) run = await flyte.run.aio(task, commit=event["after"]) return {"run_id": run.name, "url": run.url} return {"status": "ignored"} # {{/docs-fragment github-webhook}} # {{docs-fragment env}} env = FastAPIAppEnvironment( name="github-webhook", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, secrets=flyte.Secret(key="GITHUB_WEBHOOK_SECRET", as_env_var="GITHUB_WEBHOOK_SECRET"), ) # {{/docs-fragment env}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed GitHub webhook: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/github_webhook.py* ### Gradio agent UI For AI agents, a Gradio app lets you build an interactive UI that kicks off agent runs. The app uses `flyte.with_runcontext()` to run the agent task either locally or on a remote cluster, controlled by an environment variable. ```python import os import flyte import flyte.app from research_agent import agent RUN_MODE = os.getenv("RUN_MODE", "remote") serving_env = flyte.app.AppEnvironment( name="research-agent-ui", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "gradio", "langchain-core", "langchain-openai", "langgraph", ), secrets=flyte.Secret(key="OPENAI_API_KEY", as_env_var="OPENAI_API_KEY"), port=7860, ) def run_query(request: str): """Kick off the agent as a Flyte task.""" result = flyte.with_runcontext(mode=RUN_MODE).run(agent, request=request) result.wait() return result.outputs()[0] @serving_env.server def app_server(): create_demo().launch(server_name="0.0.0.0", server_port=7860) if __name__ == "__main__": create_demo().launch() ``` The `RUN_MODE` variable gives you a smooth development progression: 1. **Fully local**: `RUN_MODE=local python agent_app.py`. Everything runs in your local Python environment, great for rapid iteration. 2. **Local app, remote task**: `python agent_app.py`. The UI runs locally but the agent executes on the cluster with full compute resources. 3. **Full remote**: `flyte deploy agent_app.py serving_env`. Both the UI and agent run on the cluster. ## Best practices 1. **Use `depends_on`**: List the apps a task environment calls in its `depends_on`, so they're deployed along with it. 2. **Handle errors**: Implement proper error handling for HTTP requests. 3. **Use async clients**: Use async HTTP clients (`httpx.AsyncClient`) in async contexts. 4. **Initialize Flyte**: For apps calling tasks, initialize Flyte in the app's startup. 5. **Endpoint access**: Use `app_env.endpoint` or `AppEndpoint` parameter for accessing app URLs. 6. **Webhook security**: Secure webhooks with auth, validation, and HTTPS. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps/websocket-apps === Serve WebSocket endpoints for bidirectional, real-time communication. # WebSocket apps WebSockets enable bidirectional, real-time communication between clients and servers. Flyte apps can serve WebSocket endpoints for real-time applications like chat, live updates, or streaming data. ## Example: Basic WebSocket app Here's a simple FastAPI app with WebSocket support: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "websockets", # ] # /// """A FastAPI app with WebSocket support.""" import pathlib from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse import asyncio import json from datetime import UTC, datetime import flyte from flyte.app.extras import FastAPIAppEnvironment app = FastAPI( title="Flyte WebSocket Demo", description="A FastAPI app with WebSocket support", version="1.0.0", ) # {{docs-fragment connection-manager}} class ConnectionManager: """Manages WebSocket connections.""" def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): """Accept and register a new WebSocket connection.""" await websocket.accept() self.active_connections.append(websocket) print(f"Client connected. Total: {len(self.active_connections)}") def disconnect(self, websocket: WebSocket): """Remove a WebSocket connection.""" self.active_connections.remove(websocket) print(f"Client disconnected. Total: {len(self.active_connections)}") async def send_personal_message(self, message: str, websocket: WebSocket): """Send a message to a specific WebSocket connection.""" await websocket.send_text(message) async def broadcast(self, message: str): """Broadcast a message to all active connections.""" for connection in self.active_connections: try: await connection.send_text(message) except Exception as e: print(f"Error broadcasting: {e}") manager = ConnectionManager() # {{/docs-fragment connection-manager}} # {{docs-fragment websocket-endpoint}} @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): """WebSocket endpoint for real-time communication.""" await manager.connect(websocket) try: # Send welcome message await manager.send_personal_message( json.dumps({ "type": "system", "message": "Welcome! You are connected.", "timestamp": datetime.now(UTC).isoformat(), }), websocket, ) # Listen for messages while True: data = await websocket.receive_text() # Echo back to sender await manager.send_personal_message( json.dumps({ "type": "echo", "message": f"Echo: {data}", "timestamp": datetime.now(UTC).isoformat(), }), websocket, ) # Broadcast to all clients await manager.broadcast( json.dumps({ "type": "broadcast", "message": f"Broadcast: {data}", "timestamp": datetime.now(UTC).isoformat(), "connections": len(manager.active_connections), }) ) except WebSocketDisconnect: manager.disconnect(websocket) await manager.broadcast( json.dumps({ "type": "system", "message": "A client disconnected", "connections": len(manager.active_connections), }) ) # {{/docs-fragment websocket-endpoint}} # {{docs-fragment env}} env = FastAPIAppEnvironment( name="websocket-app", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "websockets", ), resources=flyte.Resources(cpu=1, memory="1Gi"), requires_auth=False, ) # {{/docs-fragment env}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed websocket app: {app_deployment[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/websocket/basic_websocket.py* ## WebSocket patterns **Echo server** ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "websockets", # ] # /// """WebSocket patterns: echo, broadcast, streaming, and chat.""" import asyncio import json import random from datetime import datetime, UTC from pathlib import Path from fastapi import FastAPI, WebSocket, WebSocketDisconnect import flyte from flyte.app.extras import FastAPIAppEnvironment app = FastAPI( title="WebSocket Patterns Demo", description="Demonstrates various WebSocket patterns", version="1.0.0", ) # {{docs-fragment echo-server}} @app.websocket("/echo") async def echo(websocket: WebSocket): await websocket.accept() try: while True: data = await websocket.receive_text() await websocket.send_text(f"Echo: {data}") except WebSocketDisconnect: pass # {{/docs-fragment echo-server}} # Connection manager for broadcast class ConnectionManager: def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: try: await connection.send_text(message) except Exception: pass manager = ConnectionManager() # {{docs-fragment broadcast-server}} @app.websocket("/broadcast") async def broadcast(websocket: WebSocket): await manager.connect(websocket) try: while True: data = await websocket.receive_text() await manager.broadcast(data) except WebSocketDisconnect: manager.disconnect(websocket) # {{/docs-fragment broadcast-server}} # {{docs-fragment streaming-server}} @app.websocket("/stream") async def stream_data(websocket: WebSocket): await websocket.accept() try: while True: # Generate or fetch data data = {"timestamp": datetime.now(UTC).isoformat(), "value": random.random()} await websocket.send_json(data) await asyncio.sleep(1) # Send update every second except WebSocketDisconnect: pass # {{/docs-fragment streaming-server}} # {{docs-fragment chat-room}} class ChatRoom: def __init__(self, name: str): self.name = name self.connections: list[WebSocket] = [] async def join(self, websocket: WebSocket): self.connections.append(websocket) async def leave(self, websocket: WebSocket): self.connections.remove(websocket) async def broadcast(self, message: str, sender: WebSocket): for connection in self.connections: if connection != sender: await connection.send_text(message) rooms: dict[str, ChatRoom] = {} @app.websocket("/chat/{room_name}") async def chat(websocket: WebSocket, room_name: str): await websocket.accept() if room_name not in rooms: rooms[room_name] = ChatRoom(room_name) room = rooms[room_name] await room.join(websocket) try: while True: data = await websocket.receive_text() await room.broadcast(data, websocket) except WebSocketDisconnect: await room.leave(websocket) # {{/docs-fragment chat-room}} env = FastAPIAppEnvironment( name="websocket-patterns", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "websockets", ), resources=flyte.Resources(cpu=1, memory="1Gi"), requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed WebSocket patterns app: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/websocket/websocket_patterns.py* **Broadcast server** ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "websockets", # ] # /// """WebSocket patterns: echo, broadcast, streaming, and chat.""" import asyncio import json import random from datetime import datetime, UTC from pathlib import Path from fastapi import FastAPI, WebSocket, WebSocketDisconnect import flyte from flyte.app.extras import FastAPIAppEnvironment app = FastAPI( title="WebSocket Patterns Demo", description="Demonstrates various WebSocket patterns", version="1.0.0", ) # {{docs-fragment echo-server}} @app.websocket("/echo") async def echo(websocket: WebSocket): await websocket.accept() try: while True: data = await websocket.receive_text() await websocket.send_text(f"Echo: {data}") except WebSocketDisconnect: pass # {{/docs-fragment echo-server}} # Connection manager for broadcast class ConnectionManager: def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: try: await connection.send_text(message) except Exception: pass manager = ConnectionManager() # {{docs-fragment broadcast-server}} @app.websocket("/broadcast") async def broadcast(websocket: WebSocket): await manager.connect(websocket) try: while True: data = await websocket.receive_text() await manager.broadcast(data) except WebSocketDisconnect: manager.disconnect(websocket) # {{/docs-fragment broadcast-server}} # {{docs-fragment streaming-server}} @app.websocket("/stream") async def stream_data(websocket: WebSocket): await websocket.accept() try: while True: # Generate or fetch data data = {"timestamp": datetime.now(UTC).isoformat(), "value": random.random()} await websocket.send_json(data) await asyncio.sleep(1) # Send update every second except WebSocketDisconnect: pass # {{/docs-fragment streaming-server}} # {{docs-fragment chat-room}} class ChatRoom: def __init__(self, name: str): self.name = name self.connections: list[WebSocket] = [] async def join(self, websocket: WebSocket): self.connections.append(websocket) async def leave(self, websocket: WebSocket): self.connections.remove(websocket) async def broadcast(self, message: str, sender: WebSocket): for connection in self.connections: if connection != sender: await connection.send_text(message) rooms: dict[str, ChatRoom] = {} @app.websocket("/chat/{room_name}") async def chat(websocket: WebSocket, room_name: str): await websocket.accept() if room_name not in rooms: rooms[room_name] = ChatRoom(room_name) room = rooms[room_name] await room.join(websocket) try: while True: data = await websocket.receive_text() await room.broadcast(data, websocket) except WebSocketDisconnect: await room.leave(websocket) # {{/docs-fragment chat-room}} env = FastAPIAppEnvironment( name="websocket-patterns", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "websockets", ), resources=flyte.Resources(cpu=1, memory="1Gi"), requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed WebSocket patterns app: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/websocket/websocket_patterns.py* **Real-time data streaming** ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "websockets", # ] # /// """WebSocket patterns: echo, broadcast, streaming, and chat.""" import asyncio import json import random from datetime import datetime, UTC from pathlib import Path from fastapi import FastAPI, WebSocket, WebSocketDisconnect import flyte from flyte.app.extras import FastAPIAppEnvironment app = FastAPI( title="WebSocket Patterns Demo", description="Demonstrates various WebSocket patterns", version="1.0.0", ) # {{docs-fragment echo-server}} @app.websocket("/echo") async def echo(websocket: WebSocket): await websocket.accept() try: while True: data = await websocket.receive_text() await websocket.send_text(f"Echo: {data}") except WebSocketDisconnect: pass # {{/docs-fragment echo-server}} # Connection manager for broadcast class ConnectionManager: def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: try: await connection.send_text(message) except Exception: pass manager = ConnectionManager() # {{docs-fragment broadcast-server}} @app.websocket("/broadcast") async def broadcast(websocket: WebSocket): await manager.connect(websocket) try: while True: data = await websocket.receive_text() await manager.broadcast(data) except WebSocketDisconnect: manager.disconnect(websocket) # {{/docs-fragment broadcast-server}} # {{docs-fragment streaming-server}} @app.websocket("/stream") async def stream_data(websocket: WebSocket): await websocket.accept() try: while True: # Generate or fetch data data = {"timestamp": datetime.now(UTC).isoformat(), "value": random.random()} await websocket.send_json(data) await asyncio.sleep(1) # Send update every second except WebSocketDisconnect: pass # {{/docs-fragment streaming-server}} # {{docs-fragment chat-room}} class ChatRoom: def __init__(self, name: str): self.name = name self.connections: list[WebSocket] = [] async def join(self, websocket: WebSocket): self.connections.append(websocket) async def leave(self, websocket: WebSocket): self.connections.remove(websocket) async def broadcast(self, message: str, sender: WebSocket): for connection in self.connections: if connection != sender: await connection.send_text(message) rooms: dict[str, ChatRoom] = {} @app.websocket("/chat/{room_name}") async def chat(websocket: WebSocket, room_name: str): await websocket.accept() if room_name not in rooms: rooms[room_name] = ChatRoom(room_name) room = rooms[room_name] await room.join(websocket) try: while True: data = await websocket.receive_text() await room.broadcast(data, websocket) except WebSocketDisconnect: await room.leave(websocket) # {{/docs-fragment chat-room}} env = FastAPIAppEnvironment( name="websocket-patterns", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "websockets", ), resources=flyte.Resources(cpu=1, memory="1Gi"), requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed WebSocket patterns app: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/websocket/websocket_patterns.py* **Chat application** ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "websockets", # ] # /// """WebSocket patterns: echo, broadcast, streaming, and chat.""" import asyncio import json import random from datetime import datetime, UTC from pathlib import Path from fastapi import FastAPI, WebSocket, WebSocketDisconnect import flyte from flyte.app.extras import FastAPIAppEnvironment app = FastAPI( title="WebSocket Patterns Demo", description="Demonstrates various WebSocket patterns", version="1.0.0", ) # {{docs-fragment echo-server}} @app.websocket("/echo") async def echo(websocket: WebSocket): await websocket.accept() try: while True: data = await websocket.receive_text() await websocket.send_text(f"Echo: {data}") except WebSocketDisconnect: pass # {{/docs-fragment echo-server}} # Connection manager for broadcast class ConnectionManager: def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: try: await connection.send_text(message) except Exception: pass manager = ConnectionManager() # {{docs-fragment broadcast-server}} @app.websocket("/broadcast") async def broadcast(websocket: WebSocket): await manager.connect(websocket) try: while True: data = await websocket.receive_text() await manager.broadcast(data) except WebSocketDisconnect: manager.disconnect(websocket) # {{/docs-fragment broadcast-server}} # {{docs-fragment streaming-server}} @app.websocket("/stream") async def stream_data(websocket: WebSocket): await websocket.accept() try: while True: # Generate or fetch data data = {"timestamp": datetime.now(UTC).isoformat(), "value": random.random()} await websocket.send_json(data) await asyncio.sleep(1) # Send update every second except WebSocketDisconnect: pass # {{/docs-fragment streaming-server}} # {{docs-fragment chat-room}} class ChatRoom: def __init__(self, name: str): self.name = name self.connections: list[WebSocket] = [] async def join(self, websocket: WebSocket): self.connections.append(websocket) async def leave(self, websocket: WebSocket): self.connections.remove(websocket) async def broadcast(self, message: str, sender: WebSocket): for connection in self.connections: if connection != sender: await connection.send_text(message) rooms: dict[str, ChatRoom] = {} @app.websocket("/chat/{room_name}") async def chat(websocket: WebSocket, room_name: str): await websocket.accept() if room_name not in rooms: rooms[room_name] = ChatRoom(room_name) room = rooms[room_name] await room.join(websocket) try: while True: data = await websocket.receive_text() await room.broadcast(data, websocket) except WebSocketDisconnect: await room.leave(websocket) # {{/docs-fragment chat-room}} env = FastAPIAppEnvironment( name="websocket-patterns", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "websockets", ), resources=flyte.Resources(cpu=1, memory="1Gi"), requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed WebSocket patterns app: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/websocket/websocket_patterns.py* ## Using WebSockets with Flyte tasks You can trigger Flyte tasks from WebSocket messages: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "websockets", # ] # /// """A WebSocket app that triggers Flyte tasks and streams updates.""" import json from pathlib import Path from contextlib import asynccontextmanager from fastapi import FastAPI, WebSocket, WebSocketDisconnect import flyte import flyte.remote as remote from flyte.app.extras import FastAPIAppEnvironment @asynccontextmanager async def lifespan(app: FastAPI): """Initialize Flyte before accepting requests.""" await flyte.init_in_cluster.aio() yield app = FastAPI( title="WebSocket Task Runner", description="Triggers Flyte tasks via WebSocket and streams updates", version="1.0.0", lifespan=lifespan, ) # {{docs-fragment task-runner-websocket}} @app.websocket("/task-runner") async def task_runner(websocket: WebSocket): await websocket.accept() try: while True: # Receive task request message = await websocket.receive_text() request = json.loads(message) # Trigger Flyte task task = remote.Task.get( project=request["project"], domain=request["domain"], name=request["task"], version=request["version"], ) run = await flyte.run.aio(task, **request["inputs"]) # Send run info back await websocket.send_json({ "run_id": run.name, "url": run.url, "status": "started", }) # Optionally stream updates async for update in run.stream(): await websocket.send_json({ "status": update.status, "message": update.message, }) except WebSocketDisconnect: pass # {{/docs-fragment task-runner-websocket}} env = FastAPIAppEnvironment( name="task-runner-websocket", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "websockets", ), resources=flyte.Resources(cpu=1, memory="1Gi"), requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed WebSocket task runner: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/websocket/task_runner_websocket.py* ## WebSocket client example Connect from Python: ```python import asyncio import websockets import json async def client(): uri = "ws://your-app-url/ws" async with websockets.connect(uri) as websocket: # Send message await websocket.send("Hello, Server!") # Receive message response = await websocket.recv() print(f"Received: {response}") asyncio.run(client()) ``` ## Best practices 1. **Connection management**: Track active connections and handle disconnections gracefully. 2. **Heartbeats**: Implement ping/pong for connection health monitoring. 3. **Rate limiting**: Consider rate limiting for production deployments. 4. **Error handling**: Handle WebSocket errors and connection drops. 5. **Authentication**: Implement authentication for secure WebSocket connections. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps/browser-apps === Serve Streamlit, Gradio, or custom dashboards that users reach directly in a browser. # Browser apps For browser-based apps (like Streamlit, Gradio, or custom HTML/JS dashboards), users interact directly through the web interface. The app URL is accessible in a browser, and users interact with the UI directly: no API calls needed from other services. ## Accessing browser-based apps To access a browser-based app: 1. Deploy the app using `flyte deploy` or `flyte serve` 2. Navigate to the app URL in a browser 3. Interact with the UI directly ## Common browser-based app types ### Streamlit apps Streamlit is ideal for data dashboards and ML prototypes. See **Apps > Native app integrations > Streamlit app** for details. ### Gradio apps Gradio is great for ML model demos and interactive interfaces. You can deploy a Gradio app by building a custom **Apps > Build apps > Single-script apps** with the `gradio` package installed in your image. ### Custom HTML/JS apps You can also serve custom HTML/JS applications using FastAPI's static file serving or any other web framework. ## Best practices 1. **Authentication**: For sensitive apps, enable authentication with `requires_auth=True`. 2. **Responsive design**: Design UIs that work on various screen sizes. 3. **Loading states**: Show loading indicators for long-running operations. 4. **Error handling**: Display user-friendly error messages. 5. **Resource management**: Configure appropriate CPU/memory resources based on expected usage. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps/secret-based-authentication === Protect a public FastAPI endpoint with an API key held in a Flyte secret. # Secret-based authentication This guide deploys a FastAPI app that uses API key authentication with Flyte secrets. This allows you to invoke the endpoint from the public internet securely without exposing API keys in your code. ## Create the secret Before defining and deploying the app, you need to create the `API_KEY` secret in Flyte. This secret will store your API key securely. Create the secret using the Flyte CLI: ```bash flyte create secret API_KEY --value ``` For example: ```bash flyte create secret API_KEY --value my-secret-api-key-12345 ``` > [!NOTE] > The secret name `API_KEY` must match the key specified in the `flyte.Secret()` call in your code. The secret will be available to your app as the environment variable specified in `as_env_var`. ## Define the FastAPI app Here's a simple FastAPI app that uses `HTTPAuthorizationCredentials` to authenticate requests using a secret stored in Flyte: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """Basic FastAPI authentication using dependency injection.""" from fastapi import FastAPI, HTTPException, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from starlette import status import os import pathlib import flyte from flyte.app.extras import FastAPIAppEnvironment # Get API key from environment variable (loaded from Flyte secret) # The secret must be created using: flyte create secret API_KEY API_KEY = os.getenv("API_KEY") security = HTTPBearer() async def verify_token( credentials: HTTPAuthorizationCredentials = Security(security), ) -> HTTPAuthorizationCredentials: """Verify the API key from the bearer token.""" if not API_KEY: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="API_KEY not configured", ) if credentials.credentials != API_KEY: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) return credentials app = FastAPI(title="Authenticated API") @app.get("/public") async def public_endpoint(): """Public endpoint that doesn't require authentication.""" return {"message": "This is public"} @app.get("/protected") async def protected_endpoint( credentials: HTTPAuthorizationCredentials = Security(verify_token), ): """Protected endpoint that requires authentication.""" return { "message": "This is protected", "user": credentials.credentials, } env = FastAPIAppEnvironment( name="authenticated-api", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, # We handle auth in the app secrets=flyte.Secret(key="API_KEY", as_env_var="API_KEY"), ) if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed: {app_deployment[0].summary_repr()}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/basic_auth.py* As you can see, we: 1. Define a `FastAPI` app 2. Create a `verify_token` function that verifies the API key from the Bearer token 3. Define endpoints that use the `verify_token` function to authenticate requests 4. Configure the `FastAPIAppEnvironment` with: - `requires_auth=False` - This allows the endpoint to be reached without going through Flyte's authentication, since we're handling authentication ourselves using the `API_KEY` secret - `secrets=flyte.Secret(key="API_KEY", as_env_var="API_KEY")` - This injects the secret value into the `API_KEY` environment variable at runtime The key difference from using `env_vars` is that secrets are stored securely in Flyte's secret store and injected at runtime, rather than being passed as plain environment variables. ## Deploy the FastAPI app Once the secret is created, you can deploy the FastAPI app. Make sure your `config.yaml` file is in the same directory as your script, then run: ```bash python basic_auth.py ``` Or use the Flyte CLI: ```bash flyte serve basic_auth.py env ``` To find the app's public URL, run `flyte get app` and use the `endpoint` value in the `authenticated-api` row. The URL that `flyte serve` prints opens the app in the UI. It isn't the public endpoint. ## Invoke the endpoint Once deployed, you can invoke the authenticated endpoint using curl: ```bash curl -X GET "https://your-app-url/protected" \ -H "Authorization: Bearer " ``` Replace `` with the actual API key value you used when creating the secret. For example, if you created the secret with value `my-secret-api-key-12345`: ```bash curl -X GET "https://your-app-url/protected" \ -H "Authorization: Bearer my-secret-api-key-12345" ``` You should receive a response: ```json { "message": "This is protected", "user": "my-secret-api-key-12345" } ``` ## Authentication for vLLM and SGLang apps Both vLLM and SGLang apps support API key authentication through their native `--api-key` argument. This allows you to secure your LLM endpoints while keeping them accessible from the public internet. ### Create the authentication secret Create a secret to store your API key: ```bash flyte create secret AUTH_SECRET --value ``` For example: ```bash flyte create secret AUTH_SECRET --value my-llm-api-key-12345 ``` ### Deploy vLLM app with authentication Here's how to deploy a vLLM app with API key authentication: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b45", # ] # /// """vLLM app with API key authentication.""" import pathlib from flyteplugins.vllm import VLLMAppEnvironment import flyte # The secret must be created using: flyte create secret AUTH_SECRET vllm_app = VLLMAppEnvironment( name="vllm-app-with-auth", model_hf_path="Qwen/Qwen3-0.6B", # HuggingFace model path model_id="qwen3-0.6b", # Model ID exposed by vLLM resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU required for LLM serving disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), # Disable Union's platform-level authentication so you can access the # endpoint from the public internet requires_auth=False, # Inject the secret as an environment variable secrets=flyte.Secret(key="AUTH_SECRET", as_env_var="AUTH_SECRET"), # Pass the API key to vLLM's --api-key argument # The $AUTH_SECRET will be replaced with the actual secret value at runtime extra_args=[ "--api-key", "$AUTH_SECRET", ], ) if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app = flyte.serve(vllm_app) print(f"Deployed vLLM app: {app.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/vllm/vllm_with_auth.py* Key points: 1. **`requires_auth=False`** - Disables Union's platform-level authentication so the endpoint can be accessed from the public internet 2. **`secrets=flyte.Secret(key="AUTH_SECRET", as_env_var="AUTH_SECRET")`** - Injects the secret as an environment variable 3. **`extra_args=["--api-key", "$AUTH_SECRET"]`** - Passes the API key to vLLM's `--api-key` argument. The `$AUTH_SECRET` will be replaced with the actual secret value at runtime Deploy the app: ```bash python vllm_with_auth.py ``` Or use the Flyte CLI: ```bash flyte serve vllm_with_auth.py vllm_app ``` ### Deploy SGLang app with authentication Here's how to deploy a SGLang app with API key authentication: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-sglang>=2.0.0b45", # ] # /// """SGLang app with API key authentication.""" import pathlib from flyteplugins.sglang import SGLangAppEnvironment import flyte # The secret must be created using: flyte create secret AUTH_SECRET sglang_app = SGLangAppEnvironment( name="sglang-with-auth", model_hf_path="Qwen/Qwen3-0.6B", # HuggingFace model path model_id="qwen3-0.6b", # Model ID exposed by SGLang resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU required for LLM serving disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), # Disable Union's platform-level authentication so you can access the # endpoint from the public internet requires_auth=False, # Inject the secret as an environment variable secrets=flyte.Secret(key="AUTH_SECRET", as_env_var="AUTH_SECRET"), # Pass the API key to SGLang's --api-key argument # The $AUTH_SECRET will be replaced with the actual secret value at runtime extra_args=[ "--api-key", "$AUTH_SECRET", ], ) if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app = flyte.serve(sglang_app) print(f"Deployed SGLang app: {app.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/sglang/sglang_with_auth.py* The configuration is similar to vLLM: 1. **`requires_auth=False`** - Disables Union's platform-level authentication 2. **`secrets=flyte.Secret(key="AUTH_SECRET", as_env_var="AUTH_SECRET")`** - Injects the secret as an environment variable 3. **`extra_args=["--api-key", "$AUTH_SECRET"]`** - Passes the API key to SGLang's `--api-key` argument Deploy the app: ```bash python sglang_with_auth.py ``` Or use the Flyte CLI: ```bash flyte serve sglang_with_auth.py sglang_app ``` ### Invoke authenticated LLM endpoints Once deployed, you can invoke the authenticated endpoints using the OpenAI-compatible API format. Both vLLM and SGLang expose OpenAI-compatible endpoints. For example, to make a chat completion request: ```bash curl -X POST "https://your-app-url/v1/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "model": "qwen3-0.6b", "messages": [ {"role": "user", "content": "Hello, how are you?"} ] }' ``` Replace `` with the actual API key value you used when creating the secret. For example, if you created the secret with value `my-llm-api-key-12345`: ```bash curl -X POST "https://your-app-url/v1/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer my-llm-api-key-12345" \ -d '{ "model": "qwen3-0.6b", "messages": [ {"role": "user", "content": "Hello, how are you?"} ] }' ``` You should receive a response with the model's completion. > [!NOTE] > The `$AUTH_SECRET` syntax in `extra_args` is automatically replaced with the actual secret value at runtime. This ensures the API key is never exposed in your code or configuration files. ## Accessing Swagger documentation The app also includes a public endpoint and Swagger UI documentation: - **Public endpoint**: `https://your-app-url/public` - **Swagger UI**: `https://your-app-url/docs` - **ReDoc**: `https://your-app-url/redoc` The Swagger UI will show an "Authorize" button where you can enter your Bearer token to test authenticated endpoints directly from the browser. ## Security best practices 1. **Use strong API keys**: Generate cryptographically secure random strings for your API keys 2. **Rotate keys regularly**: Periodically rotate your API keys for better security 3. **Scope secrets appropriately**: Use project/domain scoping when creating secrets if you want to limit access: ```bash flyte create secret --project my-project --domain development API_KEY --value my-secret-value ``` 4. **Never commit secrets**: Always use Flyte secrets for API keys, never hardcode them in your code 5. **Use HTTPS**: Always use HTTPS in production (Flyte apps are served over HTTPS by default) ## Troubleshooting **Authentication failing:** - Verify the secret exists: `flyte get secret API_KEY` - Check that the secret key name matches exactly (case-sensitive) - Ensure you're using the correct Bearer token value - Verify the `as_env_var` parameter matches the environment variable name in your code **Secret not found:** - Make sure you've created the secret before deploying the app - Check the secret scope (organization vs project/domain) matches your app's project/domain - Verify the secret name matches exactly (should be `API_KEY`) **App not starting:** - Check container logs for errors - Verify all dependencies are installed in the image - Ensure the secret is accessible in the app's project/domain **LLM app authentication not working:** - Verify the secret exists: `flyte get secret AUTH_SECRET` - Check that `$AUTH_SECRET` is correctly specified in `extra_args` (note the `$` prefix) - Ensure the secret name matches exactly (case-sensitive) in both the `flyte.Secret()` call and `extra_args` - For vLLM, verify the `--api-key` argument is correctly passed - For SGLang, verify the `--api-key` argument is correctly passed - Check that `requires_auth=False` is set to allow public access ## Next steps - Learn more about **Tasks > Configure tasks > Secrets** in Flyte - See **Apps > Build apps > Hybrid app-task graphs** for webhook examples and authentication patterns - Learn about **Inference > Self-hosted endpoints > vLLM** and **Inference > Self-hosted endpoints > SGLang** for serving LLMs === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/build-apps/connector-app === Extend Flyte with a custom task execution backend, such as an internal batch service. # Connector app A **connector** lets you extend Flyte with custom task execution backends (for example, submitting jobs to an internal batch service, a proprietary ML platform, or any external API). Rather than running your task code directly in a container, Flyte delegates execution to the connector, which polls the external system and reports status back to the orchestrator. Connectors are deployed as long-running services via `flyte.app.ConnectorEnvironment`, the same app deployment model used for FastAPI endpoints and model servers. ## When to build a custom connector Build a connector when: - Tasks need to submit work to an external system (e.g., a job scheduler, a cloud ML service) and poll for completion asynchronously - You want Flyte's orchestration, observability, and data lineage on top of a non-Kubernetes backend - Multiple tasks share the same external integration and you want to centralize that logic ## Project structure A connector app spans two concerns: the connector service (deployed once) and the task plugin (used in each workflow). A typical layout is: ``` my_project/ โ”œโ”€โ”€ app.py # Deploy the connector as a flyte app โ”œโ”€โ”€ main.py # Example task that uses the connector โ””โ”€โ”€ my_connector/ โ”œโ”€โ”€ __init__.py โ”œโ”€โ”€ connector.py # AsyncConnector implementation โ””โ”€โ”€ task.py # Task plugin (AsyncConnectorExecutorMixin) ``` ## Step 1: Implement the connector The connector implements four lifecycle methods: `create` (submit the job), `get` (poll status), `delete` (cancel), and `get_logs` (stream paginated log lines to the UI). ``` import time import uuid from dataclasses import dataclass from typing import Any, Dict, Optional from flyteidl2.connector.connector_pb2 import ( GetTaskLogsResponse, GetTaskLogsResponseBody, GetTaskLogsResponseHeader, ) from flyteidl2.core.execution_pb2 import TaskExecution from flyteidl2.logs.dataplane.payload_pb2 import LogLine, LogLineOriginator from google.protobuf.timestamp_pb2 import Timestamp from flyte import logger from flyte.connectors import AsyncConnector, ConnectorRegistry, Resource, ResourceMeta @dataclass class BatchJobMetadata(ResourceMeta): job_id: str created_at: float class BatchJobConnector(AsyncConnector): name = "Batch Job Connector" task_type_name = "batch_job" metadata_type = BatchJobMetadata async def create(self, task_template, inputs: Optional[Dict[str, Any]] = None, **kwargs) -> BatchJobMetadata: job_id = str(uuid.uuid4())[:8] logger.info(f"Submitted batch job {job_id}") return BatchJobMetadata(job_id=job_id, created_at=time.time()) async def get(self, resource_meta: BatchJobMetadata, **kwargs) -> Resource: elapsed = time.time() - resource_meta.created_at if elapsed < 5: return Resource(phase=TaskExecution.RUNNING, message="Job in progress") return Resource( phase=TaskExecution.SUCCEEDED, message="Job completed", outputs={"result": f"output-from-{resource_meta.job_id}"}, ) async def delete(self, resource_meta: BatchJobMetadata, **kwargs): logger.info(f"Cancelled job {resource_meta.job_id}") async def get_logs(self, resource_meta: BatchJobMetadata, token: str = "", **kwargs): def line(message: str, ts: float) -> LogLine: t = Timestamp() t.FromSeconds(int(ts)) return LogLine(timestamp=t, message=message, originator=LogLineOriginator.USER) start = resource_meta.created_at job_id = resource_meta.job_id pages = { "": GetTaskLogsResponseBody(lines=[ line(f"[INFO] Job {job_id} submitted", start), line(f"[INFO] Job {job_id} started", start + 1), ]), "page-2": GetTaskLogsResponseBody(lines=[ line(f"[INFO] Job {job_id} finished", start + 5), ]), } next_tokens = {"": "page-2", "page-2": ""} yield GetTaskLogsResponse(body=pages.get(token, GetTaskLogsResponseBody(lines=[]))) next_token = next_tokens.get(token, "") if next_token: yield GetTaskLogsResponse(header=GetTaskLogsResponseHeader(token=next_token)) ConnectorRegistry.register(BatchJobConnector()) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/connectors/batch_job/connector.py* Key points: - **`task_type_name`** must match the `_TASK_TYPE` on your task plugin (see Step 2) - **`ResourceMeta`** carries whatever state you need between `create` and subsequent `get` / `delete` calls (e.g., a job ID) - **`Resource.outputs`** maps output names to values; these become the task's return values - **`get_logs`** is an async generator that yields `GetTaskLogsResponse` messages. Yield a `body` with log lines, then optionally a `header` carrying the next-page token. Omit the final header to signal end of pagination. The UI displays these lines under the **Logs** tab of the task run. - Register the connector with `ConnectorRegistry.register()` at module level so it is discovered on startup Connector logs as shown in the UI: ![Connector logs shown in the UI Logs tab](../../../_static/images/user-guide/build-apps/connector-app/connector-logs-ui.png) ## Step 2: Create the task plugin The task plugin is the Python object your workflows use. It declares the task type, inputs, outputs, and any configuration; `AsyncConnectorExecutorMixin` wires it to the connector at execution time. ``` from dataclasses import dataclass from typing import Any, Dict, Optional, Type from flyte.connectors import AsyncConnectorExecutorMixin from flyte.extend import TaskTemplate from flyte.models import NativeInterface, SerializationContext @dataclass class BatchJobConfig: timeout_seconds: int = 300 class BatchJobTask(AsyncConnectorExecutorMixin, TaskTemplate): _TASK_TYPE = "batch_job" def __init__(self, name: str, plugin_config: BatchJobConfig, inputs: Optional[Dict[str, Type]] = None, outputs: Optional[Dict[str, Type]] = None, **kwargs): super().__init__( name=name, interface=NativeInterface( {k: (v, None) for k, v in inputs.items()} if inputs else {}, outputs or {}, ), task_type=self._TASK_TYPE, image=None, **kwargs, ) self.plugin_config = plugin_config def custom_config(self, sctx: SerializationContext) -> Optional[Dict[str, Any]]: return {"timeout_seconds": self.plugin_config.timeout_seconds} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/connectors/batch_job/task.py* Key points: - **`_TASK_TYPE`** ties this plugin to the connector that declares the same `task_type_name` - **`custom_config`** serializes plugin-specific settings into the task template; the connector receives these in `task_template.custom` during `create` - `image=None` is correct: the connector service, not the task container, executes this task ## Step 3: Test your connector locally Before deploying, you can exercise your connector entirely in your local Python process โ€” no connector service, no cluster, no build-and-deploy cycle. When you run a connector-backed task **locally**, `AsyncConnectorExecutorMixin` calls your connector's `create` and `get` methods directly in-process, polling until the task reaches a terminal phase, then returns its outputs. This lets you iterate on connector logic quickly. A run executes locally whenever no Flyte backend connection is configured, or when you force local mode explicitly. Point Flyte at the module that instantiates your task and run it: ```python # main.py import my_connector.connector # noqa: F401 registers the connector from my_connector.task import BatchJobConfig, BatchJobTask import flyte batch_job = BatchJobTask( name="my_batch_job", plugin_config=BatchJobConfig(timeout_seconds=60), inputs={"name": str}, outputs={"result": str}, ) flyte.TaskEnvironment.from_task("batch-job-env", batch_job) if __name__ == "__main__": flyte.init() # runs locally result = flyte.run(batch_job, name="hello") print(result.outputs()) ``` ```bash python main.py ``` Or force local mode from the CLI with `--local`: ```bash flyte run --local main.py batch_job --name hello ``` Because the connector runs in-process, you can set breakpoints in `create` and `get`, inspect intermediate state, and confirm your `ResourceMeta` round-trips โ€” all before you deploy. The connector module must be imported so its `ConnectorRegistry.register()` call runs. The task plugin in Step 2 doesn't import it, so `main.py` imports `my_connector.connector` itself. Without that import, the run fails with `FlyteConnectorNotFound`. The task must also belong to an environment. Without the `TaskEnvironment.from_task` call, the run fails with `Task my_batch_job has no parent environment name`. > [!NOTE] Local runs skip the connector service > Local execution calls your connector code directly; it does not start the gRPC connector service or route through a deployed `ConnectorEnvironment`. Once the connector is deployed (next step) and you run against a Flyte backend, the same task is routed to the running connector service instead. ## Step 4: Deploy the connector `ConnectorEnvironment` builds and deploys the connector as a long-running service. The `include` parameter lists the Python packages or modules to copy into the connector image. ```python # app.py from pathlib import Path import flyte import flyte.app image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("flyte[connector]") connector = flyte.app.ConnectorEnvironment( name="batch-job-connector", image=image, resources=flyte.Resources(cpu="1", memory="1Gi"), include=["my_connector"], ) if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) d = flyte.deploy(connector) print(d[0]) ``` Deploy with: ```bash python app.py ``` Or using the CLI: ```bash flyte deploy app.py connector ``` Flyte builds the image, pushes it, and starts the connector service. The service stays running and handles all `create` / `get` / `delete` calls for tasks with `task_type_name = "batch_job"`. > [!NOTE] Connectors are scoped to their project and domain > A connector only handles tasks that run in the same project and domain it is deployed to. For example, if you deploy the connector to the `flytesnacks` project and `development` domain, it handles only the tasks executing in `flytesnacks` / `development`. Tasks of the same `task_type_name` running in a different project or domain are not routed to it. Deploy a separate connector in each project-domain where you need it. ## Step 5: Register and run tasks Attach the task to a `TaskEnvironment`, then run the task against your Flyte backend: ```python # main.py from pathlib import Path from my_connector.task import BatchJobConfig, BatchJobTask import flyte batch_job = BatchJobTask( name="my_batch_job", plugin_config=BatchJobConfig(timeout_seconds=60), inputs={"name": str}, outputs={"result": str}, ) flyte.TaskEnvironment.from_task("batch-job-env", batch_job) if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) result = flyte.run(batch_job, name="hello") print(result.url) ``` `TaskEnvironment.from_task` creates an environment and attaches the task to it, which Flyte needs to serialize the task. The environment name plays no part in choosing a connector: Flyte routes the task by its task type and the project and domain it runs in. Run the task: ```bash python main.py # or flyte run main.py batch_job --name hello ``` ## How it all fits together ``` flyte run main.py batch_job โ”‚ โ–ผ Flyte executor sees task_type = "batch_job" โ”‚ โ–ผ Routes to the deployed connector service (batch-job-connector) โ”‚ โ”œโ”€ connector.create() โ†’ submits job, returns BatchJobMetadata โ”‚ โ”œโ”€ connector.get() โ†’ polls status (RUNNING / SUCCEEDED / FAILED) โ”‚ โ””โ”€ connector.delete() โ†’ called on cancellation ``` The connector service is the only component that needs network access to the external system. Your workflow code and Flyte's propeller never communicate with it directly. ## Secrets There are two ways to pass credentials to a connector. **Connector-level secrets** are shared across all tasks using the connector. Add them to `ConnectorEnvironment.secrets` and read them from `os.environ` inside the connector. See [Connectors](../../../integrations/_index#connector-level-secrets) for details. ### Per-task secrets (per-user credentials) When different users need to run the same connector with their own credentials, pass the secret *name* through the task plugin. Flyte fetches the secret value at execution time and injects it as a keyword argument into the connector's `create` and `get` methods. **1. Accept a secret name in the task plugin:** ```python # my_connector/task.py class BatchJobTask(AsyncConnectorExecutorMixin, TaskTemplate): _TASK_TYPE = "batch_job" def __init__( self, name: str, plugin_config: BatchJobConfig, inputs: Optional[Dict[str, Type]] = None, outputs: Optional[Dict[str, Type]] = None, api_key: Optional[str] = None, # name of the secret in Flyte's secret store **kwargs, ): super().__init__(...) self.plugin_config = plugin_config self.api_key = api_key def custom_config(self, sctx: SerializationContext) -> Optional[Dict[str, Any]]: config = {"timeout_seconds": self.plugin_config.timeout_seconds} if self.api_key is not None: config["secrets"] = {"api_key": self.api_key} # secret name, not value return config ``` **2. Receive the secret value as a kwarg in the connector:** Flyte reads the secret name from `task_template.custom.secrets`, fetches the value from the secrets store, and passes it as a keyword argument to `create` and `get`: ```python # my_connector/connector.py class BatchJobConnector(AsyncConnector): ... async def create( self, task_template, inputs=None, api_key: Optional[str] = None, # value injected by Flyte **kwargs, ) -> BatchJobMetadata: # use api_key to authenticate against the external service ... async def get( self, resource_meta: BatchJobMetadata, api_key: Optional[str] = None, **kwargs, ) -> Resource: ... ``` **3. Each user specifies their own secret name when defining the task:** ```python # alice's workflow batch_job = BatchJobTask( name="alice_batch_job", plugin_config=BatchJobConfig(timeout_seconds=60), inputs={"name": str}, outputs={"result": str}, api_key="alice-api-key", # Alice's secret, stored under this name in Flyte ) # bob's workflow batch_job = BatchJobTask( name="bob_batch_job", plugin_config=BatchJobConfig(timeout_seconds=60), inputs={"name": str}, outputs={"result": str}, api_key="bob-api-key", # Bob's own secret ) ``` See **Tasks > Configure tasks > Secrets** for how to store secrets in Flyte. ## Related - **Flyte SDK > flyte.app > ConnectorEnvironment** - **Flyte SDK > flyte.connectors > AsyncConnector** - **Tasks > Configure tasks > Task plugins** === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/native-app-integrations === Use pre-built environments for popular frameworks like Streamlit, FastAPI, vLLM, SGLang, and Ollama. # Native app integrations Flyte ships with a set of pre-built [`AppEnvironment`](../build-apps/_index) integrations that wrap popular frameworks and serving runtimes, so you can deploy common app types without writing the integration glue yourself. Each integration provides a ready-to-use environment class: just configure your app, image, resources, and scaling, and Flyte handles the rest. > [!TIP] > If you're new to apps in Flyte, start with **Get started > Core concepts > Apps** for an overview, then see [Build apps](../build-apps/_index) to learn how to build custom app environments from scratch. ## When to use a native integration Use a native integration when your app fits one of the supported frameworks and you want: - **A minimal, opinionated setup**: sensible defaults for the framework, no boilerplate - **First-class support**: features like model streaming, OpenAI-compatible APIs, and passthrough auth wired in for you - **Faster time-to-deploy**: focus on your app logic, not on packaging and serving plumbing For app types not covered here, build a custom [`AppEnvironment`](../build-apps/_index) using the patterns in the [Build apps](../build-apps/_index) section. ## Available integrations | Integration | Framework | Typical use case | |---|---|---| | **Apps > Native app integrations > Streamlit app** | [Streamlit](https://streamlit.io/) | Interactive dashboards and data apps | | **Apps > Native app integrations > FastAPI app** | [FastAPI](https://fastapi.tiangolo.com/) | REST APIs, webhooks, and backend services | | **Inference > Self-hosted endpoints > vLLM** | [vLLM](https://docs.vllm.ai/) | High-throughput LLM inference with an OpenAI-compatible API | | **Inference > Self-hosted endpoints > SGLang** | [SGLang](https://docs.sglang.io/) | Structured generation and LLM serving with an OpenAI-compatible API | | **Inference > Self-hosted endpoints > Ollama** | [Ollama](https://ollama.com/) | Lightweight local-style LLM serving with an OpenAI-compatible API | | **Apps > Native app integrations > Flyte webhook** | [FastAPI](https://fastapi.tiangolo.com/) | Pre-built HTTP endpoints for common Flyte control plane operations | See [Inference](../../inference/_index) for choosing between serving a model yourself and calling a hosted provider. ## Next steps - **Apps > Native app integrations > Streamlit app**: Build interactive Streamlit dashboards - **Apps > Native app integrations > FastAPI app**: Create REST APIs and backend services - **Inference > Self-hosted endpoints > vLLM**: Serve large language models with vLLM - **Inference > Self-hosted endpoints > SGLang**: Serve LLMs with SGLang for structured generation - **Inference > Self-hosted endpoints > Ollama**: Serve lightweight LLMs with Ollama - **Apps > Native app integrations > Flyte webhook**: Pre-built webhook for common Flyte operations {{< subpage-cards >}} ## Subpages - **Apps > Native app integrations > Streamlit app** - Deploy an interactive Streamlit dashboard as a long-running service. - **Apps > Native app integrations > FastAPI app** - Deploy a FastAPI application with FastAPIAppEnvironment. - **Apps > Native app integrations > Flyte webhook** - A prebuilt app exposing HTTP endpoints for common Flyte operations, with no FastAPI code to write. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/native-app-integrations/streamlit-app === Deploy an interactive Streamlit dashboard as a long-running service. # Streamlit app Streamlit is a popular framework for building interactive web applications and dashboards. Flyte makes it easy to deploy Streamlit apps as long-running services. ## Basic Streamlit app The simplest way to deploy a Streamlit app is to use the built-in Streamlit "hello" demo: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A basic Streamlit app using the built-in hello demo.""" # {{docs-fragment app-definition}} import flyte import flyte.app image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("streamlit==1.41.1") app_env = flyte.app.AppEnvironment( name="streamlit-hello", image=image, args="streamlit hello --server.port 8080", port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config() app = flyte.deploy(app_env) print(f"Deployed app: {app[0].summary_repr()}") # {{/docs-fragment app-definition}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/basic_streamlit.py* This just serves the built-in Streamlit "hello" demo. ## Single-file Streamlit app For a single-file Streamlit app, you can wrap the app code in a function and use the `args` parameter to specify the command to run the app. Note that the command is running the file itself, and uses the `--server` flag to start the server. This is useful when you have a relatively small and simple app that you want to deploy as a single file. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # ] # /// """A single-script Streamlit app example.""" import sys from pathlib import Path import streamlit as st import flyte import flyte.app # {{docs-fragment streamlit-app}} def main(): st.set_page_config(page_title="Simple Streamlit App", page_icon="๐Ÿš€") st.title("Hello from Streamlit!") st.write("This is a simple single-script Streamlit app.") name = st.text_input("What's your name?", "World") st.write(f"Hello, {name}!") if st.button("Click me!"): st.balloons() st.success("Button clicked!") # {{/docs-fragment streamlit-app}} file_name = Path(__file__).name # {{docs-fragment app-env}} app_env = flyte.app.AppEnvironment( name="streamlit-single-script", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("streamlit==1.41.1"), args=[ "streamlit", "run", file_name, "--server.port", "8080", "--", "--server", ], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": import logging import sys if "--server" in sys.argv: main() else: flyte.init_from_config( root_dir=Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(app_env) print(f"App URL: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/single_file_streamlit.py* Note that the `if __name__ == "__main__"` block is used to both serve the `AppEnvironment` *and* run the app code via the `streamlit run` command using the `--server` flag. ## Multi-file Streamlit app When your streamlit application grows more complex, you may want to split your app into multiple files. For a multi-file Streamlit app, use the `include` parameter to bundle your app files: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A custom Streamlit app with multiple files.""" import pathlib import flyte import flyte.app # {{docs-fragment app-env}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit==1.41.1", "pandas==2.2.3", "numpy==2.2.3", ) app_env = flyte.app.AppEnvironment( name="streamlit-multi-file-app", image=image, args="streamlit run main.py --server.port 8080", port=8080, include=["main.py", "utils.py"], # Include your app files resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app = flyte.deploy(app_env) print(f"Deployed app: {app[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/multi_file_streamlit.py* Where your project structure looks like this: ``` project/ โ”œโ”€โ”€ main.py # Main Streamlit app โ”œโ”€โ”€ utils.py # Utility functions โ””โ”€โ”€ components.py # Reusable components ``` Your `main.py` file would contain your Streamlit app code: ``` import os import streamlit as st from utils import generate_data # {{docs-fragment streamlit-app}} all_columns = ["Apples", "Orange", "Pineapple"] with st.container(border=True): columns = st.multiselect("Columns", all_columns, default=all_columns) all_data = st.cache_data(generate_data)(columns=all_columns, seed=101) data = all_data[columns] tab1, tab2 = st.tabs(["Chart", "Dataframe"]) tab1.line_chart(data, height=250) tab2.dataframe(data, height=250, use_container_width=True) st.write(f"Environment: {os.environ}") # {{/docs-fragment streamlit-app}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/main.py* ## Example: Data visualization dashboard Here's a complete example of a Streamlit dashboard, all in a single file. Define the streamlit app in the `main` function: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # "pandas", # "numpy", # ] # /// """A data visualization dashboard example using Streamlit.""" import sys from pathlib import Path import numpy as np import pandas as pd import streamlit as st import flyte import flyte.app # {{docs-fragment streamlit-app}} def main(): st.set_page_config(page_title="Sales Dashboard", page_icon="๐Ÿ“Š") st.title("Sales Dashboard") # Load data @st.cache_data def load_data(): return pd.DataFrame({ "date": pd.date_range("2024-01-01", periods=100, freq="D"), "sales": np.random.randint(1000, 5000, 100), }) data = load_data() # Sidebar filters st.sidebar.header("Filters") start_date = st.sidebar.date_input("Start date", value=data["date"].min()) end_date = st.sidebar.date_input("End date", value=data["date"].max()) # Filter data filtered_data = data[ (data["date"] >= pd.Timestamp(start_date)) & (data["date"] <= pd.Timestamp(end_date)) ] # Display metrics col1, col2, col3 = st.columns(3) with col1: st.metric("Total Sales", f"${filtered_data['sales'].sum():,.0f}") with col2: st.metric("Average Sales", f"${filtered_data['sales'].mean():,.0f}") with col3: st.metric("Days", len(filtered_data)) # Chart st.line_chart(filtered_data.set_index("date")["sales"]) # {{/docs-fragment streamlit-app}} # {{docs-fragment app-env}} file_name = Path(__file__).name app_env = flyte.app.AppEnvironment( name="sales-dashboard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit==1.41.1", "pandas==2.2.3", "numpy==2.2.3", ), args=["streamlit run", file_name, "--server.port", "8080", "--", "--server"], port=8080, resources=flyte.Resources(cpu="2", memory="2Gi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment serve}} if __name__ == "__main__": import logging import sys if "--server" in sys.argv: main() else: flyte.init_from_config( root_dir=Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(app_env) print(f"Dashboard URL: {app.url}") # {{/docs-fragment serve}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/data_visualization_dashboard.py* Define the `AppEnvironment` to serve the app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # "pandas", # "numpy", # ] # /// """A data visualization dashboard example using Streamlit.""" import sys from pathlib import Path import numpy as np import pandas as pd import streamlit as st import flyte import flyte.app # {{docs-fragment streamlit-app}} def main(): st.set_page_config(page_title="Sales Dashboard", page_icon="๐Ÿ“Š") st.title("Sales Dashboard") # Load data @st.cache_data def load_data(): return pd.DataFrame({ "date": pd.date_range("2024-01-01", periods=100, freq="D"), "sales": np.random.randint(1000, 5000, 100), }) data = load_data() # Sidebar filters st.sidebar.header("Filters") start_date = st.sidebar.date_input("Start date", value=data["date"].min()) end_date = st.sidebar.date_input("End date", value=data["date"].max()) # Filter data filtered_data = data[ (data["date"] >= pd.Timestamp(start_date)) & (data["date"] <= pd.Timestamp(end_date)) ] # Display metrics col1, col2, col3 = st.columns(3) with col1: st.metric("Total Sales", f"${filtered_data['sales'].sum():,.0f}") with col2: st.metric("Average Sales", f"${filtered_data['sales'].mean():,.0f}") with col3: st.metric("Days", len(filtered_data)) # Chart st.line_chart(filtered_data.set_index("date")["sales"]) # {{/docs-fragment streamlit-app}} # {{docs-fragment app-env}} file_name = Path(__file__).name app_env = flyte.app.AppEnvironment( name="sales-dashboard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit==1.41.1", "pandas==2.2.3", "numpy==2.2.3", ), args=["streamlit run", file_name, "--server.port", "8080", "--", "--server"], port=8080, resources=flyte.Resources(cpu="2", memory="2Gi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment serve}} if __name__ == "__main__": import logging import sys if "--server" in sys.argv: main() else: flyte.init_from_config( root_dir=Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(app_env) print(f"Dashboard URL: {app.url}") # {{/docs-fragment serve}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/data_visualization_dashboard.py* And finally the app serving logic: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # "pandas", # "numpy", # ] # /// """A data visualization dashboard example using Streamlit.""" import sys from pathlib import Path import numpy as np import pandas as pd import streamlit as st import flyte import flyte.app # {{docs-fragment streamlit-app}} def main(): st.set_page_config(page_title="Sales Dashboard", page_icon="๐Ÿ“Š") st.title("Sales Dashboard") # Load data @st.cache_data def load_data(): return pd.DataFrame({ "date": pd.date_range("2024-01-01", periods=100, freq="D"), "sales": np.random.randint(1000, 5000, 100), }) data = load_data() # Sidebar filters st.sidebar.header("Filters") start_date = st.sidebar.date_input("Start date", value=data["date"].min()) end_date = st.sidebar.date_input("End date", value=data["date"].max()) # Filter data filtered_data = data[ (data["date"] >= pd.Timestamp(start_date)) & (data["date"] <= pd.Timestamp(end_date)) ] # Display metrics col1, col2, col3 = st.columns(3) with col1: st.metric("Total Sales", f"${filtered_data['sales'].sum():,.0f}") with col2: st.metric("Average Sales", f"${filtered_data['sales'].mean():,.0f}") with col3: st.metric("Days", len(filtered_data)) # Chart st.line_chart(filtered_data.set_index("date")["sales"]) # {{/docs-fragment streamlit-app}} # {{docs-fragment app-env}} file_name = Path(__file__).name app_env = flyte.app.AppEnvironment( name="sales-dashboard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit==1.41.1", "pandas==2.2.3", "numpy==2.2.3", ), args=["streamlit run", file_name, "--server.port", "8080", "--", "--server"], port=8080, resources=flyte.Resources(cpu="2", memory="2Gi"), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment serve}} if __name__ == "__main__": import logging import sys if "--server" in sys.argv: main() else: flyte.init_from_config( root_dir=Path(__file__).parent, log_level=logging.DEBUG, ) app = flyte.serve(app_env) print(f"Dashboard URL: {app.url}") # {{/docs-fragment serve}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/streamlit/data_visualization_dashboard.py* ## Best practices 1. **Use `include` for custom apps**: Always include your app files when deploying custom Streamlit code 2. **Set the port correctly**: Ensure your Streamlit app uses `--server.port 8080` (or match your `port` setting) 3. **Cache data**: Use `@st.cache_data` for expensive computations to improve performance 4. **Resource sizing**: Adjust resources based on your app's needs (data size, computations) 5. **Public vs private**: Set `requires_auth=False` for public dashboards, `True` for internal tools ## Troubleshooting **App not loading:** - Verify the port matches (use `--server.port 8080`) - Check that all required files are included - Review container logs for errors **Missing dependencies:** - Ensure all required packages are in your image's pip packages - Check that file paths in `include` are correct **Performance issues:** - Increase CPU/memory resources - Use Streamlit's caching features (`@st.cache_data`, `@st.cache_resource`) - Optimize data processing === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/native-app-integrations/fastapi-app === Deploy a FastAPI application with FastAPIAppEnvironment. # FastAPI app FastAPI is a modern, fast web framework for building APIs. Flyte provides `FastAPIAppEnvironment` which makes it easy to deploy FastAPI applications. ## Basic FastAPI app Here's a simple FastAPI app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """A basic FastAPI app example.""" from fastapi import FastAPI import pathlib import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment fastapi-app}} app = FastAPI( title="My API", description="A simple FastAPI application", version="1.0.0", ) # {{/docs-fragment fastapi-app}} # {{docs-fragment fastapi-env}} env = FastAPIAppEnvironment( name="my-fastapi-app", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, ) # {{/docs-fragment fastapi-env}} # {{docs-fragment endpoints}} @app.get("/") async def root(): return {"message": "Hello, World!"} @app.get("/health") async def health_check(): return {"status": "healthy"} # {{/docs-fragment endpoints}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"Deployed: {app_deployment[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/basic_fastapi.py* Once deployed, you can: - Access the API at the generated URL - View interactive API docs at `/docs` (Swagger UI) - View alternative docs at `/redoc` ## Serving a machine learning model Here's an example of serving a scikit-learn model: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # "scikit-learn", # "joblib", # ] # /// """Example of serving a machine learning model with FastAPI.""" import os from contextlib import asynccontextmanager from pathlib import Path import joblib import flyte from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment from pydantic import BaseModel # {{docs-fragment ml-model}} app = FastAPI(title="ML Model API") # Define request/response models class PredictionRequest(BaseModel): feature1: float feature2: float feature3: float class PredictionResponse(BaseModel): prediction: float probability: float # Load model (you would typically load this from storage) model = None @asynccontextmanager async def lifespan(app: FastAPI): global model model_path = os.getenv("MODEL_PATH", "/app/models/model.joblib") # In production, load from your storage if os.path.exists(model_path): with open(model_path, "rb") as f: model = joblib.load(f) yield @app.post("/predict", response_model=PredictionResponse) async def predict(request: PredictionRequest): # Make prediction # prediction = model.predict([[request.feature1, request.feature2, request.feature3]]) # Dummy prediction for demo prediction = 0.85 probability = 0.92 return PredictionResponse( prediction=prediction, probability=probability, ) env = FastAPIAppEnvironment( name="ml-model-api", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "scikit-learn", "pydantic", "joblib", ), parameters=[ flyte.app.Parameter( name="model_file", value=flyte.io.File.from_existing_remote("s3://bucket/models/model.joblib"), mount="/app/models", env_var="MODEL_PATH", ), ], resources=flyte.Resources(cpu=2, memory="2Gi"), requires_auth=False, ) # {{/docs-fragment ml-model}} if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"API URL: {app_deployment[0].url}") print(f"Swagger docs: {app_deployment[0].url}/docs") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/ml_model_serving.py* ## Accessing Swagger documentation FastAPI automatically generates interactive API documentation. Once deployed: - **Swagger UI**: Access at `{app_url}/docs` - **ReDoc**: Access at `{app_url}/redoc` - **OpenAPI JSON**: Access at `{app_url}/openapi.json` The Swagger UI provides an interactive interface where you can: - See all available endpoints - Test API calls directly from the browser - View request/response schemas - See example payloads ## Example: REST API with multiple endpoints ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """Example REST API with multiple endpoints.""" from pathlib import Path from typing import List from fastapi import FastAPI, HTTPException from pydantic import BaseModel import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment rest-api}} app = FastAPI(title="Product API") # Data models class Product(BaseModel): id: int name: str price: float class ProductCreate(BaseModel): name: str price: float # In-memory database (use real database in production) products_db = [] @app.get("/products", response_model=List[Product]) async def get_products(): return products_db @app.get("/products/{product_id}", response_model=Product) async def get_product(product_id: int): product = next((p for p in products_db if p["id"] == product_id), None) if not product: raise HTTPException(status_code=404, detail="Product not found") return product @app.post("/products", response_model=Product) async def create_product(product: ProductCreate): new_product = { "id": len(products_db) + 1, "name": product.name, "price": product.price, } products_db.append(new_product) return new_product env = FastAPIAppEnvironment( name="product-api", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, ) # {{/docs-fragment rest-api}} if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) app_deployment = flyte.deploy(env) print(f"API URL: {app_deployment[0].url}") print(f"Swagger docs: {app_deployment[0].url}/docs") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/rest_api.py* ## Multi-file FastAPI app Here's an example of a multi-file FastAPI app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "fastapi", # ] # /// """Multi-file FastAPI app example.""" from fastapi import FastAPI from module import function # Import from another file import pathlib import flyte from flyte.app.extras import FastAPIAppEnvironment # {{docs-fragment app-definition}} app = FastAPI(title="Multi-file FastAPI Demo") app_env = FastAPIAppEnvironment( name="fastapi-multi-file", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", ), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=False, # FastAPIAppEnvironment automatically includes necessary files # But you can also specify explicitly: # include=["app.py", "module.py"], ) # {{/docs-fragment app-definition}} # {{docs-fragment endpoint}} @app.get("/") async def root(): return function() # Uses function from module.py # {{/docs-fragment endpoint}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_deployment = flyte.deploy(app_env) print(f"Deployed: {app_deployment[0].summary_repr()}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/multi_file/app.py* The helper module: ``` # {{docs-fragment helper-function}} def function(): """Helper function used by the FastAPI app.""" return {"message": "Hello from module.py!"} # {{/docs-fragment helper-function}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/multi_file/module.py* See **Apps > Build apps > Multi-script apps** for more details on building FastAPI apps with multiple files. ## Local-to-remote model serving A common ML pattern: train a model with a Flyte pipeline, then serve predictions from it. During local development, the app loads the model from a local file (e.g. `model.pt` saved by your training pipeline). When deployed remotely, Flyte's `Parameter` system automatically resolves the model from the latest training run output. ```python from contextlib import asynccontextmanager from pathlib import Path import os from fastapi import FastAPI import flyte from flyte.app import Parameter, RunOutput from flyte.app.extras import FastAPIAppEnvironment MODEL_PATH_ENV = "MODEL_PATH" @asynccontextmanager async def lifespan(app: FastAPI): """Load model on startup, either local file or remote run output.""" model_path = Path(os.environ.get(MODEL_PATH_ENV, "model.pt")) model = load_model(model_path) app.state.model = model yield app = FastAPI(title="MNIST Predictor", lifespan=lifespan) serving_env = FastAPIAppEnvironment( name="mnist-predictor", app=app, parameters=[ # Remote: resolves model from the latest train run and sets MODEL_PATH Parameter( name="model", value=RunOutput(task_name="ml_pipeline.pipeline", type="file", getter=(1,)), download=True, env_var=MODEL_PATH_ENV, ), ], image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "torch", "torchvision", ), resources=flyte.Resources(cpu=1, memory="4Gi"), ) @app.get("/predict") async def predict(index: int = 0) -> dict: return {"prediction": app.state.model(index)} if __name__ == "__main__": # Local: skip RunOutput resolution, lifespan falls back to local model.pt serving_env.parameters = [] local_app = flyte.with_servecontext(mode="local").serve(serving_env) local_app.activate(wait=True) ``` Locally, the app loads `model.pt` from disk: ```bash python serve_model.py ``` Remotely, Flyte resolves the model from the latest training run: ```bash flyte deploy serve_model.py serving_env ``` The key idea: `Parameter` with `RunOutput` bridges the gap between local and remote. Locally, the app falls back to a local file. Remotely, Flyte resolves the model artifact from the latest pipeline run automatically. ## Best practices 1. **Use Pydantic models**: Define request/response models for type safety and automatic validation 2. **Handle errors**: Use HTTPException for proper error responses 3. **Async operations**: Use async/await for I/O operations 4. **Environment variables**: Use environment variables for configuration 5. **Logging**: Add proper logging for debugging and monitoring 6. **Health checks**: Always include a `/health` endpoint 7. **API documentation**: FastAPI auto-generates docs, but add descriptions to your endpoints ## Advanced features FastAPI supports many features that work with Flyte: - **Dependencies**: Use FastAPI's dependency injection system - **Background tasks**: Run background tasks with BackgroundTasks - **WebSockets**: See **Apps > Build apps > WebSocket apps** for details - **Authentication**: Add authentication middleware (see **Apps > Build apps > Secret-based authentication**) - **CORS**: Configure CORS for cross-origin requests - **Rate limiting**: Add rate limiting middleware ## Troubleshooting **App not starting:** - Check that uvicorn can find your app module - Verify all dependencies are installed in the image - Check container logs for startup errors **Import errors:** - Ensure all imported modules are available - Use `include` parameter if you have custom modules - Check that file paths are correct **API not accessible:** - Verify `requires_auth` setting - Check that the app is listening on the correct port (8080) - Review network/firewall settings === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/native-app-integrations/flyte-webhook === A prebuilt app exposing HTTP endpoints for common Flyte operations, with no FastAPI code to write. # Flyte webhook `FlyteWebhookAppEnvironment` is a pre-built `FastAPIAppEnvironment` that exposes HTTP endpoints for common Union.ai operations. Instead of writing your own FastAPI routes to interact with the control plane, you get a ready-to-deploy webhook service with a single constructor call. ## Available endpoints The webhook provides endpoints for the following operations: | Group | Endpoints | Description | |---|---|---| | **core** | `GET /health`, `GET /me` | Health check and authenticated user info | | **task** | `POST /run-task/{domain}/{project}/{name}`, `GET /task/{domain}/{project}/{name}` | Run tasks and retrieve task metadata | | **run** | `GET /run/{name}`, `GET /run/{name}/io`, `POST /run/{name}/abort` | Get run status, inputs/outputs, and abort runs | | **app** | `GET /app/{name}`, `POST /app/{name}/activate`, `POST /app/{name}/deactivate`, `POST /app/{name}/call` | Manage apps and call other app endpoints | | **trigger** | `POST /trigger/{task_name}/{trigger_name}/activate`, `POST /trigger/{task_name}/{trigger_name}/deactivate` | Activate and deactivate triggers | | **build** | `POST /build-image` | Build container images | | **prefetch** | `POST /prefetch/hf-model`, `GET /prefetch/hf-model/{run_name}`, `GET /prefetch/hf-model/{run_name}/io`, `POST /prefetch/hf-model/{run_name}/abort` | Prefetch HuggingFace models | All endpoints except `/health`, `/docs`, and `/openapi.json` use passthrough authentication, forwarding the caller's credentials to the Union.ai control plane. ## Basic usage Create a webhook with all endpoints enabled: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "fastapi", # "uvicorn", # "httpx", # ] # /// """Examples showing how to use FlyteWebhookAppEnvironment.""" import logging import flyte import flyte.app from flyte.app.extras import FlyteWebhookAppEnvironment # {{docs-fragment basic-webhook}} webhook_env = FlyteWebhookAppEnvironment( name="my-webhook", title="My Flyte Webhook", description="A pre-built webhook service for Flyte operations", resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, scaling=flyte.app.Scaling(replicas=1), ) # {{/docs-fragment basic-webhook}} # {{docs-fragment endpoint-groups}} task_runner_webhook = FlyteWebhookAppEnvironment( name="task-runner-webhook", title="Task Runner Webhook", endpoint_groups=["core", "task", "run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment endpoint-groups}} # {{docs-fragment individual-endpoints}} minimal_webhook = FlyteWebhookAppEnvironment( name="minimal-webhook", title="Minimal Webhook", endpoints=["health", "run_task", "get_run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment individual-endpoints}} # {{docs-fragment task-allowlist}} restricted_webhook = FlyteWebhookAppEnvironment( name="restricted-webhook", title="Restricted Webhook", endpoint_groups=["core", "task", "run"], task_allowlist=[ "production/my-project/allowed-task", "my-project/another-task", "any-domain-task", ], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment task-allowlist}} # {{docs-fragment app-allowlist}} app_manager_webhook = FlyteWebhookAppEnvironment( name="app-manager-webhook", title="App Manager Webhook", endpoint_groups=["core", "app"], app_allowlist=["my-app", "another-app"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment app-allowlist}} # {{docs-fragment trigger-allowlist}} trigger_manager_webhook = FlyteWebhookAppEnvironment( name="trigger-manager-webhook", title="Trigger Manager Webhook", endpoint_groups=["core", "trigger"], trigger_allowlist=["my-task/my-trigger", "another-trigger"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment trigger-allowlist}} # {{docs-fragment deploy-webhook}} if __name__ == "__main__": import os import httpx flyte.init_from_config(log_level=logging.DEBUG) served_app = flyte.serve(webhook_env) url = served_app.url endpoint = served_app.endpoint print(f"Webhook is served on {url}") print(f"OpenAPI docs available at: {endpoint}/docs") served_app.activate(wait=True) # {{/docs-fragment deploy-webhook}} # {{docs-fragment call-webhook}} token = os.getenv("FLYTE_API_KEY") if not token: raise ValueError("FLYTE_API_KEY not set. Obtain with: flyte get api-key") headers = { "Authorization": f"Bearer {token}", "User-Agent": "flyte-webhook-client/1.0", } with httpx.Client(headers=headers) as client: # Health check (no auth required) health = client.get(f"{endpoint}/health") print(f"/health: {health.json()}") # Get current user info (requires auth) me = client.get(f"{endpoint}/me") print(f"/me: {me.json()}") # Run a task resp = client.post( f"{endpoint}/run-task/development/my-project/my-task", json={"x": 42, "y": "hello"}, ) result = resp.json() print(f"Run task: {result}") # Check run status run_name = result["name"] run = client.get(f"{endpoint}/run/{run_name}") print(f"Run status: {run.json()}") # {{/docs-fragment call-webhook}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/flyte_webhook_examples.py* Deploy and activate it: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "fastapi", # "uvicorn", # "httpx", # ] # /// """Examples showing how to use FlyteWebhookAppEnvironment.""" import logging import flyte import flyte.app from flyte.app.extras import FlyteWebhookAppEnvironment # {{docs-fragment basic-webhook}} webhook_env = FlyteWebhookAppEnvironment( name="my-webhook", title="My Flyte Webhook", description="A pre-built webhook service for Flyte operations", resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, scaling=flyte.app.Scaling(replicas=1), ) # {{/docs-fragment basic-webhook}} # {{docs-fragment endpoint-groups}} task_runner_webhook = FlyteWebhookAppEnvironment( name="task-runner-webhook", title="Task Runner Webhook", endpoint_groups=["core", "task", "run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment endpoint-groups}} # {{docs-fragment individual-endpoints}} minimal_webhook = FlyteWebhookAppEnvironment( name="minimal-webhook", title="Minimal Webhook", endpoints=["health", "run_task", "get_run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment individual-endpoints}} # {{docs-fragment task-allowlist}} restricted_webhook = FlyteWebhookAppEnvironment( name="restricted-webhook", title="Restricted Webhook", endpoint_groups=["core", "task", "run"], task_allowlist=[ "production/my-project/allowed-task", "my-project/another-task", "any-domain-task", ], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment task-allowlist}} # {{docs-fragment app-allowlist}} app_manager_webhook = FlyteWebhookAppEnvironment( name="app-manager-webhook", title="App Manager Webhook", endpoint_groups=["core", "app"], app_allowlist=["my-app", "another-app"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment app-allowlist}} # {{docs-fragment trigger-allowlist}} trigger_manager_webhook = FlyteWebhookAppEnvironment( name="trigger-manager-webhook", title="Trigger Manager Webhook", endpoint_groups=["core", "trigger"], trigger_allowlist=["my-task/my-trigger", "another-trigger"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment trigger-allowlist}} # {{docs-fragment deploy-webhook}} if __name__ == "__main__": import os import httpx flyte.init_from_config(log_level=logging.DEBUG) served_app = flyte.serve(webhook_env) url = served_app.url endpoint = served_app.endpoint print(f"Webhook is served on {url}") print(f"OpenAPI docs available at: {endpoint}/docs") served_app.activate(wait=True) # {{/docs-fragment deploy-webhook}} # {{docs-fragment call-webhook}} token = os.getenv("FLYTE_API_KEY") if not token: raise ValueError("FLYTE_API_KEY not set. Obtain with: flyte get api-key") headers = { "Authorization": f"Bearer {token}", "User-Agent": "flyte-webhook-client/1.0", } with httpx.Client(headers=headers) as client: # Health check (no auth required) health = client.get(f"{endpoint}/health") print(f"/health: {health.json()}") # Get current user info (requires auth) me = client.get(f"{endpoint}/me") print(f"/me: {me.json()}") # Run a task resp = client.post( f"{endpoint}/run-task/development/my-project/my-task", json={"x": 42, "y": "hello"}, ) result = resp.json() print(f"Run task: {result}") # Check run status run_name = result["name"] run = client.get(f"{endpoint}/run/{run_name}") print(f"Run status: {run.json()}") # {{/docs-fragment call-webhook}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/flyte_webhook_examples.py* Once running, the webhook exposes OpenAPI docs at `{endpoint}/docs` (Swagger UI) and `{endpoint}/redoc`. ## Filtering endpoints You can restrict which endpoints the webhook exposes using either **endpoint groups** or **individual endpoints**. ### Endpoint groups Enable groups of related endpoints with `endpoint_groups`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "fastapi", # "uvicorn", # "httpx", # ] # /// """Examples showing how to use FlyteWebhookAppEnvironment.""" import logging import flyte import flyte.app from flyte.app.extras import FlyteWebhookAppEnvironment # {{docs-fragment basic-webhook}} webhook_env = FlyteWebhookAppEnvironment( name="my-webhook", title="My Flyte Webhook", description="A pre-built webhook service for Flyte operations", resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, scaling=flyte.app.Scaling(replicas=1), ) # {{/docs-fragment basic-webhook}} # {{docs-fragment endpoint-groups}} task_runner_webhook = FlyteWebhookAppEnvironment( name="task-runner-webhook", title="Task Runner Webhook", endpoint_groups=["core", "task", "run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment endpoint-groups}} # {{docs-fragment individual-endpoints}} minimal_webhook = FlyteWebhookAppEnvironment( name="minimal-webhook", title="Minimal Webhook", endpoints=["health", "run_task", "get_run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment individual-endpoints}} # {{docs-fragment task-allowlist}} restricted_webhook = FlyteWebhookAppEnvironment( name="restricted-webhook", title="Restricted Webhook", endpoint_groups=["core", "task", "run"], task_allowlist=[ "production/my-project/allowed-task", "my-project/another-task", "any-domain-task", ], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment task-allowlist}} # {{docs-fragment app-allowlist}} app_manager_webhook = FlyteWebhookAppEnvironment( name="app-manager-webhook", title="App Manager Webhook", endpoint_groups=["core", "app"], app_allowlist=["my-app", "another-app"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment app-allowlist}} # {{docs-fragment trigger-allowlist}} trigger_manager_webhook = FlyteWebhookAppEnvironment( name="trigger-manager-webhook", title="Trigger Manager Webhook", endpoint_groups=["core", "trigger"], trigger_allowlist=["my-task/my-trigger", "another-trigger"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment trigger-allowlist}} # {{docs-fragment deploy-webhook}} if __name__ == "__main__": import os import httpx flyte.init_from_config(log_level=logging.DEBUG) served_app = flyte.serve(webhook_env) url = served_app.url endpoint = served_app.endpoint print(f"Webhook is served on {url}") print(f"OpenAPI docs available at: {endpoint}/docs") served_app.activate(wait=True) # {{/docs-fragment deploy-webhook}} # {{docs-fragment call-webhook}} token = os.getenv("FLYTE_API_KEY") if not token: raise ValueError("FLYTE_API_KEY not set. Obtain with: flyte get api-key") headers = { "Authorization": f"Bearer {token}", "User-Agent": "flyte-webhook-client/1.0", } with httpx.Client(headers=headers) as client: # Health check (no auth required) health = client.get(f"{endpoint}/health") print(f"/health: {health.json()}") # Get current user info (requires auth) me = client.get(f"{endpoint}/me") print(f"/me: {me.json()}") # Run a task resp = client.post( f"{endpoint}/run-task/development/my-project/my-task", json={"x": 42, "y": "hello"}, ) result = resp.json() print(f"Run task: {result}") # Check run status run_name = result["name"] run = client.get(f"{endpoint}/run/{run_name}") print(f"Run status: {run.json()}") # {{/docs-fragment call-webhook}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/flyte_webhook_examples.py* Available groups: `all`, `core`, `task`, `run`, `app`, `trigger`, `build`, `prefetch`. ### Individual endpoints For finer control, specify exact endpoints with `endpoints`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "fastapi", # "uvicorn", # "httpx", # ] # /// """Examples showing how to use FlyteWebhookAppEnvironment.""" import logging import flyte import flyte.app from flyte.app.extras import FlyteWebhookAppEnvironment # {{docs-fragment basic-webhook}} webhook_env = FlyteWebhookAppEnvironment( name="my-webhook", title="My Flyte Webhook", description="A pre-built webhook service for Flyte operations", resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, scaling=flyte.app.Scaling(replicas=1), ) # {{/docs-fragment basic-webhook}} # {{docs-fragment endpoint-groups}} task_runner_webhook = FlyteWebhookAppEnvironment( name="task-runner-webhook", title="Task Runner Webhook", endpoint_groups=["core", "task", "run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment endpoint-groups}} # {{docs-fragment individual-endpoints}} minimal_webhook = FlyteWebhookAppEnvironment( name="minimal-webhook", title="Minimal Webhook", endpoints=["health", "run_task", "get_run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment individual-endpoints}} # {{docs-fragment task-allowlist}} restricted_webhook = FlyteWebhookAppEnvironment( name="restricted-webhook", title="Restricted Webhook", endpoint_groups=["core", "task", "run"], task_allowlist=[ "production/my-project/allowed-task", "my-project/another-task", "any-domain-task", ], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment task-allowlist}} # {{docs-fragment app-allowlist}} app_manager_webhook = FlyteWebhookAppEnvironment( name="app-manager-webhook", title="App Manager Webhook", endpoint_groups=["core", "app"], app_allowlist=["my-app", "another-app"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment app-allowlist}} # {{docs-fragment trigger-allowlist}} trigger_manager_webhook = FlyteWebhookAppEnvironment( name="trigger-manager-webhook", title="Trigger Manager Webhook", endpoint_groups=["core", "trigger"], trigger_allowlist=["my-task/my-trigger", "another-trigger"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment trigger-allowlist}} # {{docs-fragment deploy-webhook}} if __name__ == "__main__": import os import httpx flyte.init_from_config(log_level=logging.DEBUG) served_app = flyte.serve(webhook_env) url = served_app.url endpoint = served_app.endpoint print(f"Webhook is served on {url}") print(f"OpenAPI docs available at: {endpoint}/docs") served_app.activate(wait=True) # {{/docs-fragment deploy-webhook}} # {{docs-fragment call-webhook}} token = os.getenv("FLYTE_API_KEY") if not token: raise ValueError("FLYTE_API_KEY not set. Obtain with: flyte get api-key") headers = { "Authorization": f"Bearer {token}", "User-Agent": "flyte-webhook-client/1.0", } with httpx.Client(headers=headers) as client: # Health check (no auth required) health = client.get(f"{endpoint}/health") print(f"/health: {health.json()}") # Get current user info (requires auth) me = client.get(f"{endpoint}/me") print(f"/me: {me.json()}") # Run a task resp = client.post( f"{endpoint}/run-task/development/my-project/my-task", json={"x": 42, "y": "hello"}, ) result = resp.json() print(f"Run task: {result}") # Check run status run_name = result["name"] run = client.get(f"{endpoint}/run/{run_name}") print(f"Run status: {run.json()}") # {{/docs-fragment call-webhook}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/flyte_webhook_examples.py* > [!NOTE] > You cannot specify both `endpoint_groups` and `endpoints` at the same time. Use > one or the other. ## Allow-listing Restrict which resources the webhook can access using allow-lists. ### Task allow-list Limit which tasks can be run or queried through the webhook: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "fastapi", # "uvicorn", # "httpx", # ] # /// """Examples showing how to use FlyteWebhookAppEnvironment.""" import logging import flyte import flyte.app from flyte.app.extras import FlyteWebhookAppEnvironment # {{docs-fragment basic-webhook}} webhook_env = FlyteWebhookAppEnvironment( name="my-webhook", title="My Flyte Webhook", description="A pre-built webhook service for Flyte operations", resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, scaling=flyte.app.Scaling(replicas=1), ) # {{/docs-fragment basic-webhook}} # {{docs-fragment endpoint-groups}} task_runner_webhook = FlyteWebhookAppEnvironment( name="task-runner-webhook", title="Task Runner Webhook", endpoint_groups=["core", "task", "run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment endpoint-groups}} # {{docs-fragment individual-endpoints}} minimal_webhook = FlyteWebhookAppEnvironment( name="minimal-webhook", title="Minimal Webhook", endpoints=["health", "run_task", "get_run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment individual-endpoints}} # {{docs-fragment task-allowlist}} restricted_webhook = FlyteWebhookAppEnvironment( name="restricted-webhook", title="Restricted Webhook", endpoint_groups=["core", "task", "run"], task_allowlist=[ "production/my-project/allowed-task", "my-project/another-task", "any-domain-task", ], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment task-allowlist}} # {{docs-fragment app-allowlist}} app_manager_webhook = FlyteWebhookAppEnvironment( name="app-manager-webhook", title="App Manager Webhook", endpoint_groups=["core", "app"], app_allowlist=["my-app", "another-app"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment app-allowlist}} # {{docs-fragment trigger-allowlist}} trigger_manager_webhook = FlyteWebhookAppEnvironment( name="trigger-manager-webhook", title="Trigger Manager Webhook", endpoint_groups=["core", "trigger"], trigger_allowlist=["my-task/my-trigger", "another-trigger"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment trigger-allowlist}} # {{docs-fragment deploy-webhook}} if __name__ == "__main__": import os import httpx flyte.init_from_config(log_level=logging.DEBUG) served_app = flyte.serve(webhook_env) url = served_app.url endpoint = served_app.endpoint print(f"Webhook is served on {url}") print(f"OpenAPI docs available at: {endpoint}/docs") served_app.activate(wait=True) # {{/docs-fragment deploy-webhook}} # {{docs-fragment call-webhook}} token = os.getenv("FLYTE_API_KEY") if not token: raise ValueError("FLYTE_API_KEY not set. Obtain with: flyte get api-key") headers = { "Authorization": f"Bearer {token}", "User-Agent": "flyte-webhook-client/1.0", } with httpx.Client(headers=headers) as client: # Health check (no auth required) health = client.get(f"{endpoint}/health") print(f"/health: {health.json()}") # Get current user info (requires auth) me = client.get(f"{endpoint}/me") print(f"/me: {me.json()}") # Run a task resp = client.post( f"{endpoint}/run-task/development/my-project/my-task", json={"x": 42, "y": "hello"}, ) result = resp.json() print(f"Run task: {result}") # Check run status run_name = result["name"] run = client.get(f"{endpoint}/run/{run_name}") print(f"Run status: {run.json()}") # {{/docs-fragment call-webhook}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/flyte_webhook_examples.py* Task identifiers support three formats: - `domain/project/name`: exact match - `project/name`: matches any domain - `name`: matches any domain and project ### App allow-list Limit which apps can be managed through the webhook: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "fastapi", # "uvicorn", # "httpx", # ] # /// """Examples showing how to use FlyteWebhookAppEnvironment.""" import logging import flyte import flyte.app from flyte.app.extras import FlyteWebhookAppEnvironment # {{docs-fragment basic-webhook}} webhook_env = FlyteWebhookAppEnvironment( name="my-webhook", title="My Flyte Webhook", description="A pre-built webhook service for Flyte operations", resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, scaling=flyte.app.Scaling(replicas=1), ) # {{/docs-fragment basic-webhook}} # {{docs-fragment endpoint-groups}} task_runner_webhook = FlyteWebhookAppEnvironment( name="task-runner-webhook", title="Task Runner Webhook", endpoint_groups=["core", "task", "run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment endpoint-groups}} # {{docs-fragment individual-endpoints}} minimal_webhook = FlyteWebhookAppEnvironment( name="minimal-webhook", title="Minimal Webhook", endpoints=["health", "run_task", "get_run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment individual-endpoints}} # {{docs-fragment task-allowlist}} restricted_webhook = FlyteWebhookAppEnvironment( name="restricted-webhook", title="Restricted Webhook", endpoint_groups=["core", "task", "run"], task_allowlist=[ "production/my-project/allowed-task", "my-project/another-task", "any-domain-task", ], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment task-allowlist}} # {{docs-fragment app-allowlist}} app_manager_webhook = FlyteWebhookAppEnvironment( name="app-manager-webhook", title="App Manager Webhook", endpoint_groups=["core", "app"], app_allowlist=["my-app", "another-app"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment app-allowlist}} # {{docs-fragment trigger-allowlist}} trigger_manager_webhook = FlyteWebhookAppEnvironment( name="trigger-manager-webhook", title="Trigger Manager Webhook", endpoint_groups=["core", "trigger"], trigger_allowlist=["my-task/my-trigger", "another-trigger"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment trigger-allowlist}} # {{docs-fragment deploy-webhook}} if __name__ == "__main__": import os import httpx flyte.init_from_config(log_level=logging.DEBUG) served_app = flyte.serve(webhook_env) url = served_app.url endpoint = served_app.endpoint print(f"Webhook is served on {url}") print(f"OpenAPI docs available at: {endpoint}/docs") served_app.activate(wait=True) # {{/docs-fragment deploy-webhook}} # {{docs-fragment call-webhook}} token = os.getenv("FLYTE_API_KEY") if not token: raise ValueError("FLYTE_API_KEY not set. Obtain with: flyte get api-key") headers = { "Authorization": f"Bearer {token}", "User-Agent": "flyte-webhook-client/1.0", } with httpx.Client(headers=headers) as client: # Health check (no auth required) health = client.get(f"{endpoint}/health") print(f"/health: {health.json()}") # Get current user info (requires auth) me = client.get(f"{endpoint}/me") print(f"/me: {me.json()}") # Run a task resp = client.post( f"{endpoint}/run-task/development/my-project/my-task", json={"x": 42, "y": "hello"}, ) result = resp.json() print(f"Run task: {result}") # Check run status run_name = result["name"] run = client.get(f"{endpoint}/run/{run_name}") print(f"Run status: {run.json()}") # {{/docs-fragment call-webhook}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/flyte_webhook_examples.py* ### Trigger allow-list Limit which triggers can be activated or deactivated: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "fastapi", # "uvicorn", # "httpx", # ] # /// """Examples showing how to use FlyteWebhookAppEnvironment.""" import logging import flyte import flyte.app from flyte.app.extras import FlyteWebhookAppEnvironment # {{docs-fragment basic-webhook}} webhook_env = FlyteWebhookAppEnvironment( name="my-webhook", title="My Flyte Webhook", description="A pre-built webhook service for Flyte operations", resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, scaling=flyte.app.Scaling(replicas=1), ) # {{/docs-fragment basic-webhook}} # {{docs-fragment endpoint-groups}} task_runner_webhook = FlyteWebhookAppEnvironment( name="task-runner-webhook", title="Task Runner Webhook", endpoint_groups=["core", "task", "run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment endpoint-groups}} # {{docs-fragment individual-endpoints}} minimal_webhook = FlyteWebhookAppEnvironment( name="minimal-webhook", title="Minimal Webhook", endpoints=["health", "run_task", "get_run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment individual-endpoints}} # {{docs-fragment task-allowlist}} restricted_webhook = FlyteWebhookAppEnvironment( name="restricted-webhook", title="Restricted Webhook", endpoint_groups=["core", "task", "run"], task_allowlist=[ "production/my-project/allowed-task", "my-project/another-task", "any-domain-task", ], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment task-allowlist}} # {{docs-fragment app-allowlist}} app_manager_webhook = FlyteWebhookAppEnvironment( name="app-manager-webhook", title="App Manager Webhook", endpoint_groups=["core", "app"], app_allowlist=["my-app", "another-app"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment app-allowlist}} # {{docs-fragment trigger-allowlist}} trigger_manager_webhook = FlyteWebhookAppEnvironment( name="trigger-manager-webhook", title="Trigger Manager Webhook", endpoint_groups=["core", "trigger"], trigger_allowlist=["my-task/my-trigger", "another-trigger"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment trigger-allowlist}} # {{docs-fragment deploy-webhook}} if __name__ == "__main__": import os import httpx flyte.init_from_config(log_level=logging.DEBUG) served_app = flyte.serve(webhook_env) url = served_app.url endpoint = served_app.endpoint print(f"Webhook is served on {url}") print(f"OpenAPI docs available at: {endpoint}/docs") served_app.activate(wait=True) # {{/docs-fragment deploy-webhook}} # {{docs-fragment call-webhook}} token = os.getenv("FLYTE_API_KEY") if not token: raise ValueError("FLYTE_API_KEY not set. Obtain with: flyte get api-key") headers = { "Authorization": f"Bearer {token}", "User-Agent": "flyte-webhook-client/1.0", } with httpx.Client(headers=headers) as client: # Health check (no auth required) health = client.get(f"{endpoint}/health") print(f"/health: {health.json()}") # Get current user info (requires auth) me = client.get(f"{endpoint}/me") print(f"/me: {me.json()}") # Run a task resp = client.post( f"{endpoint}/run-task/development/my-project/my-task", json={"x": 42, "y": "hello"}, ) result = resp.json() print(f"Run task: {result}") # Check run status run_name = result["name"] run = client.get(f"{endpoint}/run/{run_name}") print(f"Run status: {run.json()}") # {{/docs-fragment call-webhook}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/flyte_webhook_examples.py* Trigger identifiers support two formats: - `task_name/trigger_name`: exact match - `trigger_name`: matches any task ## Calling the webhook Authenticate requests with a Union.ai API key passed as a Bearer token: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "fastapi", # "uvicorn", # "httpx", # ] # /// """Examples showing how to use FlyteWebhookAppEnvironment.""" import logging import flyte import flyte.app from flyte.app.extras import FlyteWebhookAppEnvironment # {{docs-fragment basic-webhook}} webhook_env = FlyteWebhookAppEnvironment( name="my-webhook", title="My Flyte Webhook", description="A pre-built webhook service for Flyte operations", resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, scaling=flyte.app.Scaling(replicas=1), ) # {{/docs-fragment basic-webhook}} # {{docs-fragment endpoint-groups}} task_runner_webhook = FlyteWebhookAppEnvironment( name="task-runner-webhook", title="Task Runner Webhook", endpoint_groups=["core", "task", "run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment endpoint-groups}} # {{docs-fragment individual-endpoints}} minimal_webhook = FlyteWebhookAppEnvironment( name="minimal-webhook", title="Minimal Webhook", endpoints=["health", "run_task", "get_run"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment individual-endpoints}} # {{docs-fragment task-allowlist}} restricted_webhook = FlyteWebhookAppEnvironment( name="restricted-webhook", title="Restricted Webhook", endpoint_groups=["core", "task", "run"], task_allowlist=[ "production/my-project/allowed-task", "my-project/another-task", "any-domain-task", ], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment task-allowlist}} # {{docs-fragment app-allowlist}} app_manager_webhook = FlyteWebhookAppEnvironment( name="app-manager-webhook", title="App Manager Webhook", endpoint_groups=["core", "app"], app_allowlist=["my-app", "another-app"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment app-allowlist}} # {{docs-fragment trigger-allowlist}} trigger_manager_webhook = FlyteWebhookAppEnvironment( name="trigger-manager-webhook", title="Trigger Manager Webhook", endpoint_groups=["core", "trigger"], trigger_allowlist=["my-task/my-trigger", "another-trigger"], resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, ) # {{/docs-fragment trigger-allowlist}} # {{docs-fragment deploy-webhook}} if __name__ == "__main__": import os import httpx flyte.init_from_config(log_level=logging.DEBUG) served_app = flyte.serve(webhook_env) url = served_app.url endpoint = served_app.endpoint print(f"Webhook is served on {url}") print(f"OpenAPI docs available at: {endpoint}/docs") served_app.activate(wait=True) # {{/docs-fragment deploy-webhook}} # {{docs-fragment call-webhook}} token = os.getenv("FLYTE_API_KEY") if not token: raise ValueError("FLYTE_API_KEY not set. Obtain with: flyte get api-key") headers = { "Authorization": f"Bearer {token}", "User-Agent": "flyte-webhook-client/1.0", } with httpx.Client(headers=headers) as client: # Health check (no auth required) health = client.get(f"{endpoint}/health") print(f"/health: {health.json()}") # Get current user info (requires auth) me = client.get(f"{endpoint}/me") print(f"/me: {me.json()}") # Run a task resp = client.post( f"{endpoint}/run-task/development/my-project/my-task", json={"x": 42, "y": "hello"}, ) result = resp.json() print(f"Run task: {result}") # Check run status run_name = result["name"] run = client.get(f"{endpoint}/run/{run_name}") print(f"Run status: {run.json()}") # {{/docs-fragment call-webhook}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/flyte_webhook_examples.py* ## Authentication `FlyteWebhookAppEnvironment` uses `FastAPIPassthroughAuthMiddleware`, which extracts the caller's auth token from the `Authorization` header and sets up a Union.ai context so that every control plane call (e.g. `remote.Task.get`, `flyte.run`) runs with the caller's identity. The `/health`, `/docs`, `/openapi.json`, and `/redoc` endpoints are excluded from authentication. ## Self-reference protection App endpoints (`get_app`, `activate_app`, `deactivate_app`, `call_app`) prevent the webhook from targeting itself. Attempting to activate, deactivate, or call the webhook's own name returns a `400 Bad Request` error. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/serve-and-deploy-apps === Use `flyte serve` for fast iteration or `flyte deploy` for production deployments. # Serve and deploy apps Flyte provides two main ways to deploy apps: **serve** (for development) and **deploy** (for production). This section covers both methods and their differences. ## Serve vs deploy ### `flyte serve` Serving is designed for development and iteration: - **Dynamic parameter modification**: You can override app parameters when serving - **Quick iteration**: Faster feedback loop for development - **Interactive**: Better suited for testing and experimentation ### `flyte deploy` Deployment is designed for production use: - **Immutable**: Apps are deployed with fixed configurations - **Production-ready**: Optimized for stability and reproducibility ## Using Python SDK ### Serve ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Serve and deploy examples for the _index.md documentation.""" import flyte import flyte.app # {{docs-fragment serve-example}} app_env = flyte.app.AppEnvironment( name="my-app", image=flyte.app.Image.from_debian_base().with_pip_packages("streamlit==1.41.1"), args=["streamlit", "hello", "--server.port", "8080"], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), ) if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(app_env) print(f"Served at: {app.url}") # {{/docs-fragment serve-example}} # {{docs-fragment deploy-example}} app_env = flyte.app.AppEnvironment( name="my-app", image=flyte.app.Image.from_debian_base().with_pip_packages("streamlit==1.41.1"), args=["streamlit", "hello", "--server.port", "8080"], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), ) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) # Access deployed app URL from the deployment for deployed_env in deployments[0].envs.values(): print(f"Deployed: {deployed_env.deployed_app.url}") # {{/docs-fragment deploy-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/serve_and_deploy_examples.py* ### Deploy ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Serve and deploy examples for the _index.md documentation.""" import flyte import flyte.app # {{docs-fragment serve-example}} app_env = flyte.app.AppEnvironment( name="my-app", image=flyte.app.Image.from_debian_base().with_pip_packages("streamlit==1.41.1"), args=["streamlit", "hello", "--server.port", "8080"], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), ) if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(app_env) print(f"Served at: {app.url}") # {{/docs-fragment serve-example}} # {{docs-fragment deploy-example}} app_env = flyte.app.AppEnvironment( name="my-app", image=flyte.app.Image.from_debian_base().with_pip_packages("streamlit==1.41.1"), args=["streamlit", "hello", "--server.port", "8080"], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), ) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) # Access deployed app URL from the deployment for deployed_env in deployments[0].envs.values(): print(f"Deployed: {deployed_env.deployed_app.url}") # {{/docs-fragment deploy-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/serve_and_deploy_examples.py* ## Using the CLI ### Serve ```bash flyte serve path/to/app.py app_env ``` ### Deploy ```bash flyte deploy path/to/app.py app_env ``` ## Next steps - **Apps > Serve and deploy apps > How app serving works**: Understanding the serve process and configuration options - **Apps > Serve and deploy apps > How app deployment works**: Understanding the deploy process and configuration options - **Apps > Serve and deploy apps > Activating and deactivating apps**: Managing app lifecycle - **Get started > Core concepts > Basic project: RAG**: Build a RAG embedding pipeline and semantic search app with Streamlit - **Inference > Prefetching models**: Download and shard HuggingFace models for vLLM and SGLang {{< subpage-cards >}} ## Subpages - **Apps > Serve and deploy apps > How app serving works** - What flyte.serve does, and why its faster feedback loop suits development. - **Apps > Serve and deploy apps > How app custom domains work** - Point a custom domain at an app. - **Apps > Serve and deploy apps > How app deployment works** - What flyte.deploy does, and why versioned immutable deployments are the production path. - **Apps > Serve and deploy apps > Activating and deactivating apps** - Turn a deployed app on and off, and what activation means for each deploy method. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/serve-and-deploy-apps/how-app-serving-works === What flyte.serve does, and why its faster feedback loop suits development. # How app serving works Serving is the recommended way to deploy apps during development. It provides a faster feedback loop and allows you to dynamically modify parameters. ## Overview When you serve an app, the following happens: 1. **Code bundling**: Your app code is bundled and prepared 2. **Image building**: Container images are built (if needed) 3. **Deployment**: The app is deployed to your Flyte cluster 4. **Activation**: The app is automatically activated and ready to use 5. **URL generation**: A URL is generated for accessing the app ## Using the Python SDK The simplest way to serve an app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Serve examples for the how-app-serving-works.md documentation.""" import logging import flyte import flyte.app # {{docs-fragment basic-serve}} app_env = flyte.app.AppEnvironment( name="my-dev-app", parameters=[flyte.app.Parameter(name="model_path", value="s3://bucket/models/model.pkl")], # ... ) if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(app_env) print(f"App served at: {app.url}") # {{/docs-fragment basic-serve}} # {{docs-fragment override-parameters}} app = flyte.with_servecontext( input_values={ "my-dev-app": { "model_path": "s3://bucket/models/test-model.pkl", } } ).serve(app_env) # {{/docs-fragment override-parameters}} # {{docs-fragment advanced-serving}} app = flyte.with_servecontext( version="v1.0.0", project="my-project", domain="development", env_vars={"LOG_LEVEL": "DEBUG"}, input_values={"app-name": {"input": "value"}}, cluster_pool="dev-pool", log_level=logging.INFO, log_format="json", dry_run=False, ).serve(app_env) # {{/docs-fragment advanced-serving}} # {{docs-fragment return-value}} app = flyte.serve(app_env) print(f"URL: {app.url}") print(f"Endpoint: {app.endpoint}") print(f"Status: {app.deployment_status}") # {{/docs-fragment return-value}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/serve_examples.py* ## Overriding parameters One key advantage of serving is the ability to override parameters dynamically: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Serve examples for the how-app-serving-works.md documentation.""" import logging import flyte import flyte.app # {{docs-fragment basic-serve}} app_env = flyte.app.AppEnvironment( name="my-dev-app", parameters=[flyte.app.Parameter(name="model_path", value="s3://bucket/models/model.pkl")], # ... ) if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(app_env) print(f"App served at: {app.url}") # {{/docs-fragment basic-serve}} # {{docs-fragment override-parameters}} app = flyte.with_servecontext( input_values={ "my-dev-app": { "model_path": "s3://bucket/models/test-model.pkl", } } ).serve(app_env) # {{/docs-fragment override-parameters}} # {{docs-fragment advanced-serving}} app = flyte.with_servecontext( version="v1.0.0", project="my-project", domain="development", env_vars={"LOG_LEVEL": "DEBUG"}, input_values={"app-name": {"input": "value"}}, cluster_pool="dev-pool", log_level=logging.INFO, log_format="json", dry_run=False, ).serve(app_env) # {{/docs-fragment advanced-serving}} # {{docs-fragment return-value}} app = flyte.serve(app_env) print(f"URL: {app.url}") print(f"Endpoint: {app.endpoint}") print(f"Status: {app.deployment_status}") # {{/docs-fragment return-value}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/serve_examples.py* This is useful for: - Testing different configurations - Using different models or data sources - A/B testing during development ## Advanced serving options Use `with_servecontext()` for more control over the serving process: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Serve examples for the how-app-serving-works.md documentation.""" import logging import flyte import flyte.app # {{docs-fragment basic-serve}} app_env = flyte.app.AppEnvironment( name="my-dev-app", parameters=[flyte.app.Parameter(name="model_path", value="s3://bucket/models/model.pkl")], # ... ) if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(app_env) print(f"App served at: {app.url}") # {{/docs-fragment basic-serve}} # {{docs-fragment override-parameters}} app = flyte.with_servecontext( input_values={ "my-dev-app": { "model_path": "s3://bucket/models/test-model.pkl", } } ).serve(app_env) # {{/docs-fragment override-parameters}} # {{docs-fragment advanced-serving}} app = flyte.with_servecontext( version="v1.0.0", project="my-project", domain="development", env_vars={"LOG_LEVEL": "DEBUG"}, input_values={"app-name": {"input": "value"}}, cluster_pool="dev-pool", log_level=logging.INFO, log_format="json", dry_run=False, ).serve(app_env) # {{/docs-fragment advanced-serving}} # {{docs-fragment return-value}} app = flyte.serve(app_env) print(f"URL: {app.url}") print(f"Endpoint: {app.endpoint}") print(f"Status: {app.deployment_status}") # {{/docs-fragment return-value}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/serve_examples.py* ## Using CLI You can also serve apps from the command line: ```bash flyte serve path/to/app.py app ``` Where `app` is the variable name of the `AppEnvironment` object. ## Return value `flyte.serve()` returns an `App` object with: - `url`: The app's URL - `endpoint`: The app's endpoint URL - `deployment_status`: Current status of the app - `name`: App name ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Serve examples for the how-app-serving-works.md documentation.""" import logging import flyte import flyte.app # {{docs-fragment basic-serve}} app_env = flyte.app.AppEnvironment( name="my-dev-app", parameters=[flyte.app.Parameter(name="model_path", value="s3://bucket/models/model.pkl")], # ... ) if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(app_env) print(f"App served at: {app.url}") # {{/docs-fragment basic-serve}} # {{docs-fragment override-parameters}} app = flyte.with_servecontext( input_values={ "my-dev-app": { "model_path": "s3://bucket/models/test-model.pkl", } } ).serve(app_env) # {{/docs-fragment override-parameters}} # {{docs-fragment advanced-serving}} app = flyte.with_servecontext( version="v1.0.0", project="my-project", domain="development", env_vars={"LOG_LEVEL": "DEBUG"}, input_values={"app-name": {"input": "value"}}, cluster_pool="dev-pool", log_level=logging.INFO, log_format="json", dry_run=False, ).serve(app_env) # {{/docs-fragment advanced-serving}} # {{docs-fragment return-value}} app = flyte.serve(app_env) print(f"URL: {app.url}") print(f"Endpoint: {app.endpoint}") print(f"Status: {app.deployment_status}") # {{/docs-fragment return-value}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/serve_examples.py* ## Best practices 1. **Use for development**: App serving is ideal for development and testing. 2. **Override parameters**: Take advantage of parameter overrides for testing different configurations. 3. **Quick iteration**: Use `serve` for rapid development cycles. 4. **Switch to deploy**: Use **Apps > Serve and deploy apps > How app deployment works** for production deployments. ## Troubleshooting **App not activating:** - Check cluster connectivity - Verify app configuration is correct - Review container logs for errors **Parameter overrides not working:** - Verify parameter names match exactly - Check that parameters are defined in the app environment - Ensure you're using the `parameter_values` parameter correctly **Slow serving:** - Images may need to be built (first time is slower). - Large code bundles can slow down deployment. - Check network connectivity to the cluster. === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/serve-and-deploy-apps/how-app-custom-domain-works === Point a custom domain at an app. # How app custom domains work Below is a snippet of how to set a custom domain for your app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # ] # /// """A basic streamlit app that uses a custom domain.""" import flyte import flyte.app # {{docs-fragment custom-domain}} image = flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("streamlit==1.41.1") # The `App` declaration. # Uses the `ImageSpec` declared above. # In this case we do not need to supply any app code # as we are using the built-in Streamlit `hello` app. app_env = flyte.app.AppEnvironment( name="streamlit-hello-custom-domain", image=image, args=["streamlit", "hello", "--server.port", "8080"], resources=flyte.Resources(cpu="1", memory="1Gi"), domain=flyte.app.Domain(subdomain="custom-subdomain"), ) if __name__ == "__main__": flyte.init_from_config() d = flyte.deploy(app_env) print(d[0]) # {{/docs-fragment custom-domain}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/create_custom_domain.py* === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/serve-and-deploy-apps/how-app-deployment-works === What flyte.deploy does, and why versioned immutable deployments are the production path. # How app deployment works Deployment is the recommended way to deploy apps to production. It creates versioned, immutable app deployments. ## Overview When you deploy an app, the following happens: 1. **Code bundling**: Your app code is bundled and prepared 2. **Image building**: Container images are built (if needed) 3. **Deployment**: The app is deployed to your Flyte cluster 4. **Activation**: The app is automatically activated and ready to use ## Using the Python SDK Deploy an app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Deploy examples for the how-app-deployment-works.md documentation.""" import flyte import flyte.app from flyte.remote import App # {{docs-fragment basic-deploy}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... ) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment basic-deploy}} # {{docs-fragment deployment-plan}} app1_env = flyte.app.AppEnvironment(name="backend", ...) app2_env = flyte.app.AppEnvironment(name="frontend", depends_on=[app1_env], ...) # Deploying app2_env will also deploy app1_env deployments = flyte.deploy(app2_env) # deployments contains both app1_env and app2_env assert len(deployments) == 2 # {{/docs-fragment deployment-plan}} # {{docs-fragment clone-with}} app_env = flyte.app.AppEnvironment(name="my-app", ...) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env.clone_with(app_env.name, resources=flyte.Resources(cpu="2", memory="2Gi")) ) for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment clone-with}} # {{docs-fragment activation-deactivation}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) app = App.get(name=app_env.name) # deactivate the app app.deactivate() # activate the app app.activate() # {{/docs-fragment activation-deactivation}} # {{docs-fragment full-deployment}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env, dryrun=False, version="v1.0.0", interactive_mode=False, copy_style="loaded_modules", ) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): app = deployed_env.deployed_app print(f"Deployed: {deployed_env.env.name}") print(f"URL: {app.url}") # Activate the app app.activate() print(f"Activated: {app.name}") # {{/docs-fragment full-deployment}} # {{docs-fragment deployment-status}} deployments = flyte.deploy(app_env) for deployment in deployments: for deployed_env in deployment.envs.values(): if hasattr(deployed_env, 'deployed_app'): # Access deployed environment env = deployed_env.env app = deployed_env.deployed_app # Access deployment info print(f"Name: {env.name}") print(f"URL: {app.url}") print(f"Status: {app.deployment_status}") # {{/docs-fragment deployment-status}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/deploy_examples.py* `flyte.deploy()` returns a list of `Deployment` objects. Each `Deployment` contains a dictionary of `DeployedEnvironment` objects (one for each environment deployed, including environment dependencies). For apps, the `DeployedEnvironment` is a `DeployedAppEnvironment` which has a `deployed_app` property of type `App`. ## Deployment plan Flyte automatically creates a deployment plan that includes: - The app you're deploying - All **Apps > Configure apps > Apps depending on other environments** (via `depends_on`) The app and the environments it reaches through `depends_on` go into a single plan, and the environments in a plan deploy concurrently. For example, if `frontend` depends on `backend`, `flyte.deploy(frontend)` deploys both and returns a list with one `Deployment`, whose `envs` contains both `frontend` and `backend`. ## Overriding app configuration at deployment time If you need to override the app configuration at deployment time, you can use the `clone_with` method to create a new app environment with the desired overrides. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Deploy examples for the how-app-deployment-works.md documentation.""" import flyte import flyte.app from flyte.remote import App # {{docs-fragment basic-deploy}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... ) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment basic-deploy}} # {{docs-fragment deployment-plan}} app1_env = flyte.app.AppEnvironment(name="backend", ...) app2_env = flyte.app.AppEnvironment(name="frontend", depends_on=[app1_env], ...) # Deploying app2_env will also deploy app1_env deployments = flyte.deploy(app2_env) # deployments contains both app1_env and app2_env assert len(deployments) == 2 # {{/docs-fragment deployment-plan}} # {{docs-fragment clone-with}} app_env = flyte.app.AppEnvironment(name="my-app", ...) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env.clone_with(app_env.name, resources=flyte.Resources(cpu="2", memory="2Gi")) ) for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment clone-with}} # {{docs-fragment activation-deactivation}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) app = App.get(name=app_env.name) # deactivate the app app.deactivate() # activate the app app.activate() # {{/docs-fragment activation-deactivation}} # {{docs-fragment full-deployment}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env, dryrun=False, version="v1.0.0", interactive_mode=False, copy_style="loaded_modules", ) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): app = deployed_env.deployed_app print(f"Deployed: {deployed_env.env.name}") print(f"URL: {app.url}") # Activate the app app.activate() print(f"Activated: {app.name}") # {{/docs-fragment full-deployment}} # {{docs-fragment deployment-status}} deployments = flyte.deploy(app_env) for deployment in deployments: for deployed_env in deployment.envs.values(): if hasattr(deployed_env, 'deployed_app'): # Access deployed environment env = deployed_env.env app = deployed_env.deployed_app # Access deployment info print(f"Name: {env.name}") print(f"URL: {app.url}") print(f"Status: {app.deployment_status}") # {{/docs-fragment deployment-status}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/deploy_examples.py* ## Activation/deactivation Deploying an app activates it. To deactivate a deployed app, or activate it again, use `deactivate()` and `activate()` on the `App`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Deploy examples for the how-app-deployment-works.md documentation.""" import flyte import flyte.app from flyte.remote import App # {{docs-fragment basic-deploy}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... ) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment basic-deploy}} # {{docs-fragment deployment-plan}} app1_env = flyte.app.AppEnvironment(name="backend", ...) app2_env = flyte.app.AppEnvironment(name="frontend", depends_on=[app1_env], ...) # Deploying app2_env will also deploy app1_env deployments = flyte.deploy(app2_env) # deployments contains both app1_env and app2_env assert len(deployments) == 2 # {{/docs-fragment deployment-plan}} # {{docs-fragment clone-with}} app_env = flyte.app.AppEnvironment(name="my-app", ...) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env.clone_with(app_env.name, resources=flyte.Resources(cpu="2", memory="2Gi")) ) for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment clone-with}} # {{docs-fragment activation-deactivation}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) app = App.get(name=app_env.name) # deactivate the app app.deactivate() # activate the app app.activate() # {{/docs-fragment activation-deactivation}} # {{docs-fragment full-deployment}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env, dryrun=False, version="v1.0.0", interactive_mode=False, copy_style="loaded_modules", ) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): app = deployed_env.deployed_app print(f"Deployed: {deployed_env.env.name}") print(f"URL: {app.url}") # Activate the app app.activate() print(f"Activated: {app.name}") # {{/docs-fragment full-deployment}} # {{docs-fragment deployment-status}} deployments = flyte.deploy(app_env) for deployment in deployments: for deployed_env in deployment.envs.values(): if hasattr(deployed_env, 'deployed_app'): # Access deployed environment env = deployed_env.env app = deployed_env.deployed_app # Access deployment info print(f"Name: {env.name}") print(f"URL: {app.url}") print(f"Status: {app.deployment_status}") # {{/docs-fragment deployment-status}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/deploy_examples.py* See **Apps > Serve and deploy apps > Activating and deactivating apps** for more details. ## Using the CLI Deploy from the command line: ```bash flyte deploy path/to/app.py app ``` Where `app` is the variable name of the `AppEnvironment` object. You can also specify the following options. They go before the file path: ```bash flyte deploy \ --version v1.0.0 \ --project my-project \ --domain production \ --dry-run \ path/to/app.py app ``` ## Example: Full deployment configuration ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Deploy examples for the how-app-deployment-works.md documentation.""" import flyte import flyte.app from flyte.remote import App # {{docs-fragment basic-deploy}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... ) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment basic-deploy}} # {{docs-fragment deployment-plan}} app1_env = flyte.app.AppEnvironment(name="backend", ...) app2_env = flyte.app.AppEnvironment(name="frontend", depends_on=[app1_env], ...) # Deploying app2_env will also deploy app1_env deployments = flyte.deploy(app2_env) # deployments contains both app1_env and app2_env assert len(deployments) == 2 # {{/docs-fragment deployment-plan}} # {{docs-fragment clone-with}} app_env = flyte.app.AppEnvironment(name="my-app", ...) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env.clone_with(app_env.name, resources=flyte.Resources(cpu="2", memory="2Gi")) ) for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment clone-with}} # {{docs-fragment activation-deactivation}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) app = App.get(name=app_env.name) # deactivate the app app.deactivate() # activate the app app.activate() # {{/docs-fragment activation-deactivation}} # {{docs-fragment full-deployment}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env, dryrun=False, version="v1.0.0", interactive_mode=False, copy_style="loaded_modules", ) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): app = deployed_env.deployed_app print(f"Deployed: {deployed_env.env.name}") print(f"URL: {app.url}") # Activate the app app.activate() print(f"Activated: {app.name}") # {{/docs-fragment full-deployment}} # {{docs-fragment deployment-status}} deployments = flyte.deploy(app_env) for deployment in deployments: for deployed_env in deployment.envs.values(): if hasattr(deployed_env, 'deployed_app'): # Access deployed environment env = deployed_env.env app = deployed_env.deployed_app # Access deployment info print(f"Name: {env.name}") print(f"URL: {app.url}") print(f"Status: {app.deployment_status}") # {{/docs-fragment deployment-status}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/deploy_examples.py* ## Best practices 1. **Use for production**: Deploy is designed for production use. 2. **Version everything**: Always specify versions for reproducibility. 3. **Test first**: Test with serve before deploying to production. 4. **Manage dependencies**: Use `depends_on` to manage app dependencies. 5. **Activation strategy**: Have a strategy for activating/deactivating apps. 6. **Use dry-run**: Test deployments with `dry_run=True` first (`--dry-run` on the CLI). `dry_run` needs `flyte` v2.8.0 or later; earlier versions take `dryrun`. From v2.8.0, `dryrun` is a deprecated alias that still works but raises a `FutureWarning`. The example above still uses it. 7. **Separate environments**: Use different projects/domains for different environments. 8. **Parameter management**: Consider using environment-specific parameter values. ## Deployment status and return value `flyte.deploy()` returns a list of `Deployment` objects. Each `Deployment` contains a dictionary of `DeployedEnvironment` objects: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Deploy examples for the how-app-deployment-works.md documentation.""" import flyte import flyte.app from flyte.remote import App # {{docs-fragment basic-deploy}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... ) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment basic-deploy}} # {{docs-fragment deployment-plan}} app1_env = flyte.app.AppEnvironment(name="backend", ...) app2_env = flyte.app.AppEnvironment(name="frontend", depends_on=[app1_env], ...) # Deploying app2_env will also deploy app1_env deployments = flyte.deploy(app2_env) # deployments contains both app1_env and app2_env assert len(deployments) == 2 # {{/docs-fragment deployment-plan}} # {{docs-fragment clone-with}} app_env = flyte.app.AppEnvironment(name="my-app", ...) if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env.clone_with(app_env.name, resources=flyte.Resources(cpu="2", memory="2Gi")) ) for deployment in deployments: for deployed_env in deployment.envs.values(): print(f"Deployed: {deployed_env.env.name}") print(f"URL: {deployed_env.deployed_app.url}") # {{/docs-fragment clone-with}} # {{docs-fragment activation-deactivation}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy(app_env) app = App.get(name=app_env.name) # deactivate the app app.deactivate() # activate the app app.activate() # {{/docs-fragment activation-deactivation}} # {{docs-fragment full-deployment}} if __name__ == "__main__": flyte.init_from_config() deployments = flyte.deploy( app_env, dryrun=False, version="v1.0.0", interactive_mode=False, copy_style="loaded_modules", ) # Access deployed apps from deployments for deployment in deployments: for deployed_env in deployment.envs.values(): app = deployed_env.deployed_app print(f"Deployed: {deployed_env.env.name}") print(f"URL: {app.url}") # Activate the app app.activate() print(f"Activated: {app.name}") # {{/docs-fragment full-deployment}} # {{docs-fragment deployment-status}} deployments = flyte.deploy(app_env) for deployment in deployments: for deployed_env in deployment.envs.values(): if hasattr(deployed_env, 'deployed_app'): # Access deployed environment env = deployed_env.env app = deployed_env.deployed_app # Access deployment info print(f"Name: {env.name}") print(f"URL: {app.url}") print(f"Status: {app.deployment_status}") # {{/docs-fragment deployment-status}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/deploy_examples.py* For apps, each `DeployedAppEnvironment` includes: - `env`: The `AppEnvironment` that was deployed - `deployed_app`: The `App` object with properties like `url`, `endpoint`, `name`, and `deployment_status` ## Troubleshooting **Deployment fails:** - Check that all dependencies are available - Verify image builds succeed - Review deployment logs **App not accessible:** - Ensure the app is activated - Check cluster connectivity - Verify app configuration **Version conflicts:** - Use unique versions for each deployment - Check existing app versions - Clean up old versions if needed === PAGE: https://www.union.ai/docs/v2/union/user-guide/apps/serve-and-deploy-apps/activating-and-deactivating-apps === Turn a deployed app on and off, and what activation means for each deploy method. # Activating and deactivating apps Apps deployed with `flyte.deploy()` and apps served with `flyte.serve()` are activated automatically. Use `deactivate()` and `activate()` to turn a deployed app off and on. ## Activation ### Activate an app When you get an app by name, you get the current app instance: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Activation examples for the activating-and-deactivating-apps.md documentation.""" import flyte import flyte.app from flyte.remote import App app_env = flyte.app.AppEnvironment( name="my-app", # ... ) # {{docs-fragment activate-after-deployment}} # Deploy the app deployments = flyte.deploy(app_env) # Activate the app app = App.get(name=app_env.name) app.activate() print(f"Activated app: {app.name}") print(f"URL: {app.url}") # {{/docs-fragment activate-after-deployment}} # {{docs-fragment activate-app}} app = App.get(name="my-app") app.activate() # {{/docs-fragment activate-app}} # {{docs-fragment check-activation-status}} app = App.get(name="my-app") print(f"Active: {app.is_active()}") print(f"Revision: {app.revision}") # {{/docs-fragment check-activation-status}} # {{docs-fragment deactivation}} app = App.get(name="my-app") app.deactivate() print(f"Deactivated app: {app.name}") # {{/docs-fragment deactivation}} # {{docs-fragment typical-deployment-workflow}} # 1. Deploy new version deployments = flyte.deploy( app_env, version="v2.0.0", ) # 2. Get the deployed app new_app = App.get(name="my-app") # Test endpoints, etc. # 3. Activate the new version new_app.activate() print(f"Deployed and activated version {new_app.revision}") # {{/docs-fragment typical-deployment-workflow}} # {{docs-fragment blue-green-deployment}} # Deploy new version without deactivating old new_deployments = flyte.deploy( app_env, version="v2.0.0", ) new_app = App.get(name="my-app") # Test new version # ... testing ... # Switch traffic to new version new_app.activate() print(f"Activated revision {new_app.revision}") # {{/docs-fragment blue-green-deployment}} # {{docs-fragment automatic-activation}} # Automatically activated app = flyte.serve(app_env) print(f"Active: {app.is_active()}") # True # {{/docs-fragment automatic-activation}} # {{docs-fragment complete-example}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... configuration ... ) if __name__ == "__main__": flyte.init_from_config() # Deploy deployments = flyte.deploy( app_env, version="v1.0.0", project="my-project", domain="production", ) # Get the deployed app app = App.get(name="my-prod-app") # Activate app.activate() print(f"Deployed and activated: {app.name}") print(f"Revision: {app.revision}") print(f"URL: {app.url}") print(f"Active: {app.is_active()}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/activation_examples.py* ### Check activation status Check if an app is active: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Activation examples for the activating-and-deactivating-apps.md documentation.""" import flyte import flyte.app from flyte.remote import App app_env = flyte.app.AppEnvironment( name="my-app", # ... ) # {{docs-fragment activate-after-deployment}} # Deploy the app deployments = flyte.deploy(app_env) # Activate the app app = App.get(name=app_env.name) app.activate() print(f"Activated app: {app.name}") print(f"URL: {app.url}") # {{/docs-fragment activate-after-deployment}} # {{docs-fragment activate-app}} app = App.get(name="my-app") app.activate() # {{/docs-fragment activate-app}} # {{docs-fragment check-activation-status}} app = App.get(name="my-app") print(f"Active: {app.is_active()}") print(f"Revision: {app.revision}") # {{/docs-fragment check-activation-status}} # {{docs-fragment deactivation}} app = App.get(name="my-app") app.deactivate() print(f"Deactivated app: {app.name}") # {{/docs-fragment deactivation}} # {{docs-fragment typical-deployment-workflow}} # 1. Deploy new version deployments = flyte.deploy( app_env, version="v2.0.0", ) # 2. Get the deployed app new_app = App.get(name="my-app") # Test endpoints, etc. # 3. Activate the new version new_app.activate() print(f"Deployed and activated version {new_app.revision}") # {{/docs-fragment typical-deployment-workflow}} # {{docs-fragment blue-green-deployment}} # Deploy new version without deactivating old new_deployments = flyte.deploy( app_env, version="v2.0.0", ) new_app = App.get(name="my-app") # Test new version # ... testing ... # Switch traffic to new version new_app.activate() print(f"Activated revision {new_app.revision}") # {{/docs-fragment blue-green-deployment}} # {{docs-fragment automatic-activation}} # Automatically activated app = flyte.serve(app_env) print(f"Active: {app.is_active()}") # True # {{/docs-fragment automatic-activation}} # {{docs-fragment complete-example}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... configuration ... ) if __name__ == "__main__": flyte.init_from_config() # Deploy deployments = flyte.deploy( app_env, version="v1.0.0", project="my-project", domain="production", ) # Get the deployed app app = App.get(name="my-prod-app") # Activate app.activate() print(f"Deployed and activated: {app.name}") print(f"Revision: {app.revision}") print(f"URL: {app.url}") print(f"Active: {app.is_active()}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/activation_examples.py* ## Deactivation Deactivate an app when you no longer need it: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Activation examples for the activating-and-deactivating-apps.md documentation.""" import flyte import flyte.app from flyte.remote import App app_env = flyte.app.AppEnvironment( name="my-app", # ... ) # {{docs-fragment activate-after-deployment}} # Deploy the app deployments = flyte.deploy(app_env) # Activate the app app = App.get(name=app_env.name) app.activate() print(f"Activated app: {app.name}") print(f"URL: {app.url}") # {{/docs-fragment activate-after-deployment}} # {{docs-fragment activate-app}} app = App.get(name="my-app") app.activate() # {{/docs-fragment activate-app}} # {{docs-fragment check-activation-status}} app = App.get(name="my-app") print(f"Active: {app.is_active()}") print(f"Revision: {app.revision}") # {{/docs-fragment check-activation-status}} # {{docs-fragment deactivation}} app = App.get(name="my-app") app.deactivate() print(f"Deactivated app: {app.name}") # {{/docs-fragment deactivation}} # {{docs-fragment typical-deployment-workflow}} # 1. Deploy new version deployments = flyte.deploy( app_env, version="v2.0.0", ) # 2. Get the deployed app new_app = App.get(name="my-app") # Test endpoints, etc. # 3. Activate the new version new_app.activate() print(f"Deployed and activated version {new_app.revision}") # {{/docs-fragment typical-deployment-workflow}} # {{docs-fragment blue-green-deployment}} # Deploy new version without deactivating old new_deployments = flyte.deploy( app_env, version="v2.0.0", ) new_app = App.get(name="my-app") # Test new version # ... testing ... # Switch traffic to new version new_app.activate() print(f"Activated revision {new_app.revision}") # {{/docs-fragment blue-green-deployment}} # {{docs-fragment automatic-activation}} # Automatically activated app = flyte.serve(app_env) print(f"Active: {app.is_active()}") # True # {{/docs-fragment automatic-activation}} # {{docs-fragment complete-example}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... configuration ... ) if __name__ == "__main__": flyte.init_from_config() # Deploy deployments = flyte.deploy( app_env, version="v1.0.0", project="my-project", domain="production", ) # Get the deployed app app = App.get(name="my-prod-app") # Activate app.activate() print(f"Deployed and activated: {app.name}") print(f"Revision: {app.revision}") print(f"URL: {app.url}") print(f"Active: {app.is_active()}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/activation_examples.py* ## Lifecycle management ### Typical deployment workflow ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Activation examples for the activating-and-deactivating-apps.md documentation.""" import flyte import flyte.app from flyte.remote import App app_env = flyte.app.AppEnvironment( name="my-app", # ... ) # {{docs-fragment activate-after-deployment}} # Deploy the app deployments = flyte.deploy(app_env) # Activate the app app = App.get(name=app_env.name) app.activate() print(f"Activated app: {app.name}") print(f"URL: {app.url}") # {{/docs-fragment activate-after-deployment}} # {{docs-fragment activate-app}} app = App.get(name="my-app") app.activate() # {{/docs-fragment activate-app}} # {{docs-fragment check-activation-status}} app = App.get(name="my-app") print(f"Active: {app.is_active()}") print(f"Revision: {app.revision}") # {{/docs-fragment check-activation-status}} # {{docs-fragment deactivation}} app = App.get(name="my-app") app.deactivate() print(f"Deactivated app: {app.name}") # {{/docs-fragment deactivation}} # {{docs-fragment typical-deployment-workflow}} # 1. Deploy new version deployments = flyte.deploy( app_env, version="v2.0.0", ) # 2. Get the deployed app new_app = App.get(name="my-app") # Test endpoints, etc. # 3. Activate the new version new_app.activate() print(f"Deployed and activated version {new_app.revision}") # {{/docs-fragment typical-deployment-workflow}} # {{docs-fragment blue-green-deployment}} # Deploy new version without deactivating old new_deployments = flyte.deploy( app_env, version="v2.0.0", ) new_app = App.get(name="my-app") # Test new version # ... testing ... # Switch traffic to new version new_app.activate() print(f"Activated revision {new_app.revision}") # {{/docs-fragment blue-green-deployment}} # {{docs-fragment automatic-activation}} # Automatically activated app = flyte.serve(app_env) print(f"Active: {app.is_active()}") # True # {{/docs-fragment automatic-activation}} # {{docs-fragment complete-example}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... configuration ... ) if __name__ == "__main__": flyte.init_from_config() # Deploy deployments = flyte.deploy( app_env, version="v1.0.0", project="my-project", domain="production", ) # Get the deployed app app = App.get(name="my-prod-app") # Activate app.activate() print(f"Deployed and activated: {app.name}") print(f"Revision: {app.revision}") print(f"URL: {app.url}") print(f"Active: {app.is_active()}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/activation_examples.py* ### Blue-green deployment For zero-downtime deployments: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Activation examples for the activating-and-deactivating-apps.md documentation.""" import flyte import flyte.app from flyte.remote import App app_env = flyte.app.AppEnvironment( name="my-app", # ... ) # {{docs-fragment activate-after-deployment}} # Deploy the app deployments = flyte.deploy(app_env) # Activate the app app = App.get(name=app_env.name) app.activate() print(f"Activated app: {app.name}") print(f"URL: {app.url}") # {{/docs-fragment activate-after-deployment}} # {{docs-fragment activate-app}} app = App.get(name="my-app") app.activate() # {{/docs-fragment activate-app}} # {{docs-fragment check-activation-status}} app = App.get(name="my-app") print(f"Active: {app.is_active()}") print(f"Revision: {app.revision}") # {{/docs-fragment check-activation-status}} # {{docs-fragment deactivation}} app = App.get(name="my-app") app.deactivate() print(f"Deactivated app: {app.name}") # {{/docs-fragment deactivation}} # {{docs-fragment typical-deployment-workflow}} # 1. Deploy new version deployments = flyte.deploy( app_env, version="v2.0.0", ) # 2. Get the deployed app new_app = App.get(name="my-app") # Test endpoints, etc. # 3. Activate the new version new_app.activate() print(f"Deployed and activated version {new_app.revision}") # {{/docs-fragment typical-deployment-workflow}} # {{docs-fragment blue-green-deployment}} # Deploy new version without deactivating old new_deployments = flyte.deploy( app_env, version="v2.0.0", ) new_app = App.get(name="my-app") # Test new version # ... testing ... # Switch traffic to new version new_app.activate() print(f"Activated revision {new_app.revision}") # {{/docs-fragment blue-green-deployment}} # {{docs-fragment automatic-activation}} # Automatically activated app = flyte.serve(app_env) print(f"Active: {app.is_active()}") # True # {{/docs-fragment automatic-activation}} # {{docs-fragment complete-example}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... configuration ... ) if __name__ == "__main__": flyte.init_from_config() # Deploy deployments = flyte.deploy( app_env, version="v1.0.0", project="my-project", domain="production", ) # Get the deployed app app = App.get(name="my-prod-app") # Activate app.activate() print(f"Deployed and activated: {app.name}") print(f"Revision: {app.revision}") print(f"URL: {app.url}") print(f"Active: {app.is_active()}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/activation_examples.py* ## Using CLI ### Activate ```bash flyte update app --activate my-app ``` ### Deactivate ```bash flyte update app --deactivate my-app ``` ### Check status ```bash flyte get app my-app ``` Use `--project` and `--domain` to target a specific **Get started > Core concepts > Projects and domains**. For all available options, see the **Flyte CLI**. ## Best practices 1. **Test before deploying**: Test with serve or a dry run before deploying 2. **Version management**: Keep track of which version is active 4. **Blue-green deployments**: Use blue-green for zero-downtime 5. **Monitor**: Monitor apps after activation 6. **Cleanup**: Deactivate and remove old versions periodically ## Automatic activation with serve Apps served with `flyte.serve()` are automatically activated: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Activation examples for the activating-and-deactivating-apps.md documentation.""" import flyte import flyte.app from flyte.remote import App app_env = flyte.app.AppEnvironment( name="my-app", # ... ) # {{docs-fragment activate-after-deployment}} # Deploy the app deployments = flyte.deploy(app_env) # Activate the app app = App.get(name=app_env.name) app.activate() print(f"Activated app: {app.name}") print(f"URL: {app.url}") # {{/docs-fragment activate-after-deployment}} # {{docs-fragment activate-app}} app = App.get(name="my-app") app.activate() # {{/docs-fragment activate-app}} # {{docs-fragment check-activation-status}} app = App.get(name="my-app") print(f"Active: {app.is_active()}") print(f"Revision: {app.revision}") # {{/docs-fragment check-activation-status}} # {{docs-fragment deactivation}} app = App.get(name="my-app") app.deactivate() print(f"Deactivated app: {app.name}") # {{/docs-fragment deactivation}} # {{docs-fragment typical-deployment-workflow}} # 1. Deploy new version deployments = flyte.deploy( app_env, version="v2.0.0", ) # 2. Get the deployed app new_app = App.get(name="my-app") # Test endpoints, etc. # 3. Activate the new version new_app.activate() print(f"Deployed and activated version {new_app.revision}") # {{/docs-fragment typical-deployment-workflow}} # {{docs-fragment blue-green-deployment}} # Deploy new version without deactivating old new_deployments = flyte.deploy( app_env, version="v2.0.0", ) new_app = App.get(name="my-app") # Test new version # ... testing ... # Switch traffic to new version new_app.activate() print(f"Activated revision {new_app.revision}") # {{/docs-fragment blue-green-deployment}} # {{docs-fragment automatic-activation}} # Automatically activated app = flyte.serve(app_env) print(f"Active: {app.is_active()}") # True # {{/docs-fragment automatic-activation}} # {{docs-fragment complete-example}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... configuration ... ) if __name__ == "__main__": flyte.init_from_config() # Deploy deployments = flyte.deploy( app_env, version="v1.0.0", project="my-project", domain="production", ) # Get the deployed app app = App.get(name="my-prod-app") # Activate app.activate() print(f"Deployed and activated: {app.name}") print(f"Revision: {app.revision}") print(f"URL: {app.url}") print(f"Active: {app.is_active()}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/activation_examples.py* This is convenient for development. For production, use `flyte.deploy()`, which also activates the app, and use `deactivate()` and `activate()` to control it afterwards. ## Example: Complete deployment and activation ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """Activation examples for the activating-and-deactivating-apps.md documentation.""" import flyte import flyte.app from flyte.remote import App app_env = flyte.app.AppEnvironment( name="my-app", # ... ) # {{docs-fragment activate-after-deployment}} # Deploy the app deployments = flyte.deploy(app_env) # Activate the app app = App.get(name=app_env.name) app.activate() print(f"Activated app: {app.name}") print(f"URL: {app.url}") # {{/docs-fragment activate-after-deployment}} # {{docs-fragment activate-app}} app = App.get(name="my-app") app.activate() # {{/docs-fragment activate-app}} # {{docs-fragment check-activation-status}} app = App.get(name="my-app") print(f"Active: {app.is_active()}") print(f"Revision: {app.revision}") # {{/docs-fragment check-activation-status}} # {{docs-fragment deactivation}} app = App.get(name="my-app") app.deactivate() print(f"Deactivated app: {app.name}") # {{/docs-fragment deactivation}} # {{docs-fragment typical-deployment-workflow}} # 1. Deploy new version deployments = flyte.deploy( app_env, version="v2.0.0", ) # 2. Get the deployed app new_app = App.get(name="my-app") # Test endpoints, etc. # 3. Activate the new version new_app.activate() print(f"Deployed and activated version {new_app.revision}") # {{/docs-fragment typical-deployment-workflow}} # {{docs-fragment blue-green-deployment}} # Deploy new version without deactivating old new_deployments = flyte.deploy( app_env, version="v2.0.0", ) new_app = App.get(name="my-app") # Test new version # ... testing ... # Switch traffic to new version new_app.activate() print(f"Activated revision {new_app.revision}") # {{/docs-fragment blue-green-deployment}} # {{docs-fragment automatic-activation}} # Automatically activated app = flyte.serve(app_env) print(f"Active: {app.is_active()}") # True # {{/docs-fragment automatic-activation}} # {{docs-fragment complete-example}} app_env = flyte.app.AppEnvironment( name="my-prod-app", # ... configuration ... ) if __name__ == "__main__": flyte.init_from_config() # Deploy deployments = flyte.deploy( app_env, version="v1.0.0", project="my-project", domain="production", ) # Get the deployed app app = App.get(name="my-prod-app") # Activate app.activate() print(f"Deployed and activated: {app.name}") print(f"Revision: {app.revision}") print(f"URL: {app.url}") print(f"Active: {app.is_active()}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/activation_examples.py* ## Troubleshooting **App not accessible after activation:** - Verify activation succeeded - Check app logs for startup errors - Verify cluster connectivity - Check that the app is listening on the correct port **Activation fails:** - Check that the app was deployed successfully - Verify app configuration is correct - Check cluster resources - Review deployment logs **Cannot deactivate:** - Ensure you have proper permissions - Check if there are dependencies preventing deactivation - Verify the app name and version === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers === Run tasks automatically on a schedule, or save named launch configurations to fire on demand. # Triggers A trigger is a named, pre-bound way to run a task. It carries the inputs, env vars, queue, notifications, and other run settings that a run started through it should use. A trigger can also carry an *automation* that fires it on its own, such as a schedule. A trigger with no automation is fired on demand only. ```python import flyte from datetime import datetime env = flyte.TaskEnvironment(name="trigger_env") @env.task(triggers=flyte.Trigger.hourly("trigger_time")) def hourly_task(trigger_time: datetime, x: int = 1) -> str: return f"Hourly example executed at {trigger_time.isoformat()} with x={x}" ``` Deploy the task with `flyte deploy` and the trigger starts creating runs every hour. > **๐Ÿ“ Note** > > In Flyte 1 these were configured with a `LaunchPlan` (the `flytekit.LaunchPlan` API) and `CronSchedule`. Flyte 2 replaces them with `flyte.Trigger` and `flyte.Cron`. ## Types of automation The `automation` argument of `flyte.Trigger` decides what fires it. Each kind can also bind a value into one of the task's inputs. | Kind | Automation | Fires when | Binds into inputs | Details | |---|---|---|---|---| | Scheduled | `flyte.Cron("0 9 * * *", timezone=...)` | A cron expression matches | `flyte.TriggerTime` | **Triggers > Schedule triggers** | | Scheduled | `flyte.FixedRate(60, start_time=...)` | Every N minutes | `flyte.TriggerTime` | **Triggers > Schedule triggers** | | Scheduled | `flyte.Trigger.hourly()`, `daily()`, `weekly()`, `monthly()` | Predefined cron shortcuts | `flyte.TriggerTime` | **Triggers > Schedule triggers > Predefined schedule triggers** | | Reactive | `flyte.OnArtifact("model")` | Any new version of an artifact is published | `flyte.TriggeredArtifact` | **Triggers > Trigger on new artifact versions** | | Reactive | `flyte.OnArtifact("model", version="v2")` | That exact version is published | `flyte.TriggeredArtifact` | **Triggers > Trigger on new artifact versions** | | Reactive | `flyte.OnArtifact("raw_events", region="us")` | A new version lands in a matching partition | `flyte.TriggeredArtifact`, `flyte.TriggeredPartition` | **Triggers > Trigger on partitions** | | Manual | None | Only when fired from the UI or with `flyte.run(trigger)` | None | **Triggers > Manual triggers and firing on demand** | Every trigger, whatever its automation, can also be **Triggers > Manual triggers and firing on demand > Firing a trigger on demand**. ## In this section ### **Triggers > Configure a trigger** Define a `flyte.Trigger` on a task, bind its inputs, and attach several triggers to one task. ### **Triggers > Schedule triggers** Run a task on a cron expression or a fixed interval with `flyte.Cron`, `flyte.FixedRate`, or a predefined schedule. ### **Triggers > When scheduled runs start** When the first run of a cron or fixed-rate trigger happens, depending on activation and `start_time`. ### **Triggers > Manual triggers and firing on demand** Save named launch configurations for a task with triggers that have no automation, and fire any trigger from the UI or Python. ### **Triggers > Trigger on new artifact versions** Run a task automatically whenever a new version of an artifact lands, using `flyte.OnArtifact`. It fires no matter who published the version. ### **Triggers > Trigger on partitions** Fire an artifact trigger only for matching partitions with `flyte.OnArtifact`, and pass the partition values into the task with `flyte.TriggeredPartition`. ### **Triggers > Notifications** Send Slack, email, Teams, or webhook notifications when a run started by a trigger ends. ### **Triggers > Deploy and manage triggers** Deploy triggers with their task, activate or deactivate them, and delete them. ## Subpages - **Triggers > Configure a trigger** - Define a `flyte.Trigger` on a task, bind its inputs, and attach several triggers to one task. - **Triggers > Schedule triggers** - Run a task on a cron expression or a fixed interval with `flyte.Cron`, `flyte.FixedRate`, or a predefined schedule. - **Triggers > When scheduled runs start** - When the first run of a cron or fixed-rate trigger happens, depending on activation and `start_time`. - **Triggers > Manual triggers and firing on demand** - Save named launch configurations for a task with triggers that have no automation, and fire any trigger from the UI or Python. - **Triggers > Trigger on new artifact versions** - Run a task automatically whenever a new version of an artifact lands, using `flyte.OnArtifact`. It fires no matter who published the version. - **Triggers > Trigger on partitions** - Fire an artifact trigger only for matching partitions with `flyte.OnArtifact`, and pass the partition values into the task with `flyte.TriggeredPartition`. - **Triggers > Notifications** - Send Slack, email, Teams, or webhook notifications when a run started by a trigger ends. - **Triggers > Deploy and manage triggers** - Deploy triggers with their task, activate or deactivate them, and delete them. === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers/configure-triggers === Define a `flyte.Trigger` on a task, bind its inputs, and attach several triggers to one task. # Configure a trigger Say a `refresh_dashboard` task serves two teams. The US team wants it every morning over the last day of data, and finance wants a 30-day run on the first of each month. You don't need two copies of the task or a wrapper script. Attach two triggers, each with its own schedule and inputs: ```python import flyte env = flyte.TaskEnvironment(name="dashboards") morning_us = flyte.Trigger( "morning-us", flyte.Cron("0 7 * * *", timezone="America/New_York"), inputs={"region": "us", "days": 1}, ) monthly_all = flyte.Trigger( "monthly-all", flyte.Cron("0 0 1 * *"), inputs={"region": "all", "days": 30}, ) @env.task(triggers=[morning_us, monthly_all]) async def refresh_dashboard(region: str, days: int = 7) -> str: ... ``` A trigger is a named, pre-bound way to run a task. It carries the inputs and run settings, and optionally an automation that fires it. This page covers how to define one. See **Triggers > Schedule triggers** for the schedule options. ## Triggers are set in the task decorator A trigger is created by setting the `triggers` parameter in the task decorator to a `flyte.Trigger` object or a list of such objects (triggers are not settable at the `TaskEnvironment` definition or `task.override` levels). Here is a simple example: ``` import flyte from datetime import datetime, timezone env = flyte.TaskEnvironment(name="trigger_env") @env.task(triggers=flyte.Trigger.hourly("trigger_time")) # Every hour, passing the fire time as trigger_time def hourly_task(trigger_time: datetime, x: int = 1) -> str: return f"Hourly example executed at {trigger_time.isoformat()} with x={x}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* Here we use a predefined schedule trigger to run the `hourly_task` every hour. Other predefined triggers can be used similarly (see **Triggers > Schedule triggers > Predefined schedule triggers**). If you want full control over the trigger behavior, you can define a trigger using the `flyte.Trigger` class directly. ## `flyte.Trigger` For complete parameter documentation, see the **Flyte SDK > flyte > Trigger**, **Flyte SDK > flyte > Cron**, and **Flyte SDK > flyte > FixedRate** API references. The `Trigger` class allows you to define custom triggers with full control over scheduling and execution behavior. It has the following signature: ``` flyte.Trigger( name, automation=None, description="", auto_activate=True, inputs=None, env_vars=None, interruptible=None, overwrite_cache=False, queue=None, labels=None, annotations=None ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* Only `name` is required. The `automation` parameter decides what fires the trigger: `flyte.Cron` or `flyte.FixedRate` for a schedule, `flyte.OnArtifact` for a new artifact version, or `None` (the default) for a trigger that is only fired on demand. Everything else describes the run that the trigger creates. Here's a comprehensive example showing all parameters: ``` comprehensive_trigger = flyte.Trigger( name="monthly_financial_report", automation=flyte.Cron("0 6 1 * *", timezone="America/New_York"), description="Monthly financial report generation for executive team", auto_activate=True, inputs={ "report_date": flyte.TriggerTime, "report_type": "executive_summary", "include_forecasts": True }, env_vars={ "REPORT_OUTPUT_FORMAT": "PDF", "EMAIL_NOTIFICATIONS": "true" }, interruptible=False, # Critical report, use dedicated resources overwrite_cache=True, # Always fresh data queue="financial-reports", labels={ "team": "finance", "criticality": "high", "automation": "scheduled" }, annotations={ "compliance.company.com/sox-required": "true", "backup.company.com/retain-days": "2555" # 7 years } ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ## The `inputs` parameter The `inputs` parameter allows you to provide default values for your task's parameters when the trigger fires. This is essential for parameterizing your automated executions and passing trigger-specific data to your tasks. ### Basic usage ``` trigger_with_inputs = flyte.Trigger( "data_processing", flyte.Cron("0 6 * * *"), # Daily at 6 AM inputs={ "batch_size": 1000, "environment": "production", "debug_mode": False } ) @env.task(triggers=trigger_with_inputs) def process_data(batch_size: int, environment: str, debug_mode: bool = True) -> str: return f"Processing {batch_size} items in {environment} mode" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ### Using `flyte.TriggerTime` The special `flyte.TriggerTime` value is used in the `inputs` to indicate the task parameter into which Flyte will inject the trigger execution timestamp. It is only available on schedule triggers (`flyte.Cron` or `flyte.FixedRate`), since a trigger without a schedule has no fire time: ``` timestamp_trigger = flyte.Trigger( "daily_report", flyte.Cron("0 0 * * *"), # Daily at midnight inputs={ "report_date": flyte.TriggerTime, # Receives trigger execution time "report_type": "daily_summary" } ) @env.task(triggers=timestamp_trigger) def generate_report(report_date: datetime, report_type: str) -> str: return f"Generated {report_type} for {report_date.strftime('%Y-%m-%d')}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ### Required vs optional parameters > [!IMPORTANT] > If your task has parameters without default values, you **must** provide values for them in the trigger inputs, otherwise the trigger will fail to execute. ```python # โŒ This will fail - missing required parameter 'data_source' bad_trigger = flyte.Trigger( "bad_trigger", flyte.Cron("0 0 * * *") # Missing inputs for required parameter 'data_source' ) @env.task(triggers=bad_trigger) def bad_trigger_taska(data_source: str, batch_size: int = 100) -> str: return f"Processing from {data_source} with batch size {batch_size}" # โœ… This works - all required parameters provided good_trigger = flyte.Trigger( "good_trigger", flyte.Cron("0 0 * * *"), inputs={ "data_source": "prod_database", # Required parameter "batch_size": 500 # Override default } ) @env.task(triggers=good_trigger) def good_trigger_task(data_source: str, batch_size: int = 100) -> str: return f"Processing from {data_source} with batch size {batch_size}" ``` ### Complex input types You can pass various data types through trigger inputs: ``` complex_trigger = flyte.Trigger( "ml_training", flyte.Cron("0 2 * * 1"), # Weekly on Monday at 2 AM inputs={ "model_config": { "learning_rate": 0.01, "batch_size": 32, "epochs": 100 }, "feature_columns": ["age", "income", "location"], "validation_split": 0.2, "training_date": flyte.TriggerTime } ) @env.task(triggers=complex_trigger) def train_model( model_config: dict, feature_columns: list[str], validation_split: float, training_date: datetime ) -> str: return f"Training model with {len(feature_columns)} features on {training_date}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ## Multiple triggers per task You can attach multiple triggers to a single task by providing a list of triggers. This allows you to run the same task on different schedules or with different configurations: ``` @env.task(triggers=[ flyte.Trigger.hourly("trigger_time"), # Predefined trigger flyte.Trigger.daily("trigger_time"), # Another predefined trigger flyte.Trigger( # Custom trigger every 6 hours "custom", flyte.Cron("0 */6 * * *"), inputs={"trigger_time": flyte.TriggerTime}, ), ]) def multi_trigger_task(trigger_time: datetime) -> str: # Different logic based on execution timing if trigger_time.hour == 0: # Daily run at midnight return f"Daily comprehensive processing at {trigger_time}" else: # Hourly or custom runs return f"Regular processing at {trigger_time.strftime('%H:%M')}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* You can mix and match trigger types, combining predefined triggers with those that use `flyte.Cron`, and `flyte.FixedRate` automations (see **Triggers > Schedule triggers**). === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers/schedules === Run a task on a cron expression or a fixed interval with `flyte.Cron`, `flyte.FixedRate`, or a predefined schedule. # Schedule triggers A sales report should land every day at 9 AM Pacific, and the task needs to know which day it is reporting on. A cron schedule fires the run, and `flyte.TriggerTime` passes the fire time into the task: ```python from datetime import datetime import flyte env = flyte.TaskEnvironment(name="reports") daily_report = flyte.Trigger( "daily-report", flyte.Cron("0 9 * * *", timezone="America/Los_Angeles"), inputs={"run_at": flyte.TriggerTime}, ) @env.task(triggers=daily_report) async def sales_report(run_at: datetime) -> str: # run_at is in UTC ... ``` Three kinds of schedule are available: a cron expression (`flyte.Cron`), a fixed interval (`flyte.FixedRate`), and predefined shortcuts such as `flyte.Trigger.daily()`. For when the first run happens after you deploy, see **Triggers > When scheduled runs start**. ## Fixed-rate schedules with `flyte.FixedRate` You can define a fixed-rate schedule trigger by setting the `automation` parameter of the `flyte.Trigger` to an instance of `flyte.FixedRate`. The `flyte.FixedRate` has the following signature: ``` flyte.FixedRate( interval_minutes, start_time=None ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ### Examples ``` # Every 90 minutes, starting when deployed every_90_min = flyte.Trigger( "data_processing", flyte.FixedRate(interval_minutes=90) ) # Every 6 hours (360 minutes), starting at a specific time specific_start = flyte.Trigger( "batch_job", flyte.FixedRate( interval_minutes=360, # 6 hours start_time=datetime(2025, 12, 1, 9, 0, 0) # Start Dec 1st at 9 AM ) ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ## Cron schedules with `flyte.Cron` You can define a Cron-based schedule trigger by setting the `automation` parameter to an instance of `flyte.Cron`. The `flyte.Cron` has the following signature: ``` flyte.Cron( cron_expression, timezone=None ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ### Examples ``` # Every day at 6 AM UTC daily_trigger = flyte.Trigger( "daily_report", flyte.Cron("0 6 * * *") ) # Every weekday at 9:30 AM Eastern Time weekday_trigger = flyte.Trigger( "business_hours_task", flyte.Cron("30 9 * * 1-5", timezone="America/New_York") ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* #### Cron expressions Here are some common cron expressions you can use: | Expression | Description | |----------------|--------------------------------------| | `0 0 * * *` | Every day at midnight | | `0 9 * * 1-5` | Every weekday at 9 AM | | `30 14 * * 6` | Every Saturday at 2:30 PM | | `0 0 1 * *` | First day of every month at midnight | | `0 0 25 * *` | 25th day of every month at midnight | | `0 0 * * 0` | Every Sunday at midnight | | `*/10 * * * *` | Every 10 minutes | | `0 */2 * * *` | Every 2 hours | For a full guide on Cron syntax, refer to [Crontab Guru](https://crontab.guru/). ## Predefined schedule triggers For common scheduling needs, Flyte provides predefined trigger methods that create Cron-based schedules without requiring you to specify cron expressions manually. These are convenient shortcuts for frequently used scheduling patterns. ### Available predefined triggers ``` minutely_trigger = flyte.Trigger.minutely() # Every minute hourly_trigger = flyte.Trigger.hourly() # Every hour daily_trigger = flyte.Trigger.daily() # Every day at midnight weekly_trigger = flyte.Trigger.weekly() # Every week (Sundays at midnight) monthly_trigger = flyte.Trigger.monthly() # Every month (1st day at midnight) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* For reference, here's what each predefined trigger is equivalent to: ```python # These are functionally identical: flyte.Trigger.minutely() == flyte.Trigger("minutely", flyte.Cron("* * * * *")) flyte.Trigger.hourly() == flyte.Trigger("hourly", flyte.Cron("0 * * * *")) flyte.Trigger.daily() == flyte.Trigger("daily", flyte.Cron("0 0 * * *")) flyte.Trigger.weekly() == flyte.Trigger("weekly", flyte.Cron("0 0 * * 0")) flyte.Trigger.monthly() == flyte.Trigger("monthly", flyte.Cron("0 0 1 * *")) ``` Each predefined trigger method takes `trigger_time_input_key` as its first argument, and the other parameters of `flyte.Trigger` as keyword arguments, except `automation`, `notifications`, and `task_version`. `name` and `description` have defaults; `name` defaults to the method's name, such as `hourly`. For the full parameter list, see the **Flyte SDK > flyte > Trigger**. ### Trigger time in predefined triggers A predefined trigger passes its fire time to a task input only when you name that input with `trigger_time_input_key`. With no key, the trigger passes the fire time to no input. Set `trigger_time_input_key` to the name of a `datetime` input. If the task has no input with that name, deployment fails with an error: ``` @env.task(triggers=flyte.Trigger.daily(trigger_time_input_key="scheduled_at")) def task_with_custom_trigger_time_input(scheduled_at: datetime) -> str: return f"Executed at {scheduled_at}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ## Schedule time zones ### Setting time zone for a cron schedule Cron expressions are by default in UTC, but it's possible to specify custom time zones like so: ``` sf_trigger = flyte.Trigger( "sf_tz", flyte.Cron( "0 9 * * *", timezone="America/Los_Angeles" ), # Every day at 9 AM PT inputs={"start_time": flyte.TriggerTime, "x": 1}, ) nyc_trigger = flyte.Trigger( "nyc_tz", flyte.Cron( "1 12 * * *", timezone="America/New_York" ), # Every day at 12:01 PM ET inputs={"start_time": flyte.TriggerTime, "x": 1}, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* The above two schedules will fire 1 minute apart, at 9 AM PT and 12:01 PM ET respectively. ### `flyte.TriggerTime` is always in UTC The `flyte.TriggerTime` value is always in UTC. For timezone-aware logic, convert as needed: ``` @env.task(triggers=flyte.Trigger.minutely(trigger_time_input_key="utc_trigger_time", name="timezone_trigger")) def timezone_task(utc_trigger_time: datetime) -> str: local_time = utc_trigger_time.replace(tzinfo=timezone.utc).astimezone() return f"Task fired at {utc_trigger_time} UTC ({local_time} local)" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ### Daylight savings time behavior When Daylight Savings Time (DST) begins and ends, it can impact when the scheduled execution begins. On the day DST begins, time jumps from 2:00AM to 3:00AM, which means the time of 2:30AM won't exist. In this case, the trigger will not fire until the next 2:30AM, which is the next day. On the day DST ends, the hour from 1:00AM to 2:00AM repeats, which means the time of 1:30AM will exist twice. If the schedule above was instead set for 1:30AM, it would only run once, on the first occurrence of 1:30AM. === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers/schedule-timing === When the first run of a cron or fixed-rate trigger happens, depending on activation and `start_time`. # When scheduled runs start You deploy a trigger with `flyte.Cron("0 0 * * *")` at 17:00, and nothing runs for seven hours. That is expected: a schedule never fires on deploy. It waits for its next scheduled time. The timing of the first run created by a trigger depends on the type of trigger used (Cron-based or Fixed-rate) and whether the trigger is active upon deployment. A trigger with no automation never creates runs on its own; it only runs when **Triggers > Manual triggers and firing on demand > Firing a trigger on demand**. ## Cron-based triggers For Cron-based triggers, the first run will be created at the next scheduled time according to the cron expression after trigger activation and similarly thereafter. * `0 0 * * *` If deployed at 17:00 today, the trigger will first fire 7 hours later (0:00 of the following day) and then every day at 0:00 thereafter. * `*/15 14 * * 1-5` if today is Tuesday at 17:00, the trigger will fire the next day (Wednesday) at 14:00, 14:15, 14:30, and 14:45 and then the same for every subsequent weekday thereafter. ## Fixed-rate triggers without `start_time` If no `start_time` is specified, then the first run will be created after the specified interval from the time of activation. No run will be created immediately upon activation, but the activation time will be used as the reference point for future runs. ### No `start_time`, auto_activate: True Let's say you define a fixed rate trigger with automatic activation like this: ``` my_trigger = flyte.Trigger("my_trigger", flyte.FixedRate(60)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* In this case, the first run will occur 60 minutes after the successful deployment of the trigger. So, if you deployed this trigger at 13:15, the first run will occur at 14:15 and so on thereafter. ### No `start_time`, auto_activate: False On the other hand, let's say you define a fixed rate trigger without automatic activation like this: ``` my_trigger = flyte.Trigger("my_trigger", flyte.FixedRate(60), auto_activate=False) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* Then you activate it after about 3 hours. In this case the first run will kick off 60 minutes after trigger activation. If you deployed the trigger at 13:15 and activated it at 16:07, the first run will occur at 17:07. ## Fixed-rate triggers with `start_time` If a `start_time` is specified, the timing of the first run depends on whether the trigger is active at `start_time` or not. ### Fixed-rate with `start_time` while active If a `start_time` is specified, and the trigger is active at `start_time` then the first run will occur at `start_time` and then at the specified interval thereafter. For example: ``` my_trigger = flyte.Trigger( "my_trigger", # Runs every 60 minutes starting from October 26th, 2025, 10:00am flyte.FixedRate(60, start_time=datetime(2025, 10, 26, 10, 0, 0)), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* If you deploy this trigger on October 24th, 2025, the trigger will wait until October 26th 10:00am and will create the first run at exactly 10:00am. ### Fixed-rate with `start_time` while inactive If a start time is specified, but the trigger is activated after `start_time`, then the first run will be created when the next time point occurs that aligns with the recurring trigger interval using `start_time` as the initial reference point. For example: ``` custom_rate_trigger = flyte.Trigger( "custom_rate", # Runs every 60 minutes starting from October 26th, 2025, 10:00am flyte.FixedRate(60, start_time=datetime(2025, 10, 26, 10, 0, 0)), auto_activate=False ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* If activated later than the `start_time`, say on October 28th 12:35pm for example, the first run will be created at October 28th at 1:00pm. === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers/manual-triggers === Save named launch configurations for a task with triggers that have no automation, and fire any trigger from the UI or Python. # Manual triggers and firing on demand Not every repeated run is on a schedule. An analyst re-runs a report with the same few input combinations whenever someone asks, and retypes them each time. A trigger with no automation saves each combination under a name, and anyone can fire it from the UI or from Python. ## Triggers without automation > [!NOTE] > Triggers without automation, and firing a trigger on demand from Python, require flyte 2.7.1 or later. Leave `automation` unset and the trigger has nothing that fires it. It becomes a saved launch configuration for the task: a name, a set of inputs, and optionally env vars, a queue, notifications and the other `flyte.Trigger` settings. Nothing runs until someone fires it, from the UI or from Python (see **Triggers > Manual triggers and firing on demand > Firing a trigger on demand**). This is a convenient way to publish a handful of "blessed" ways to run a task without re-typing inputs each time. Here, one task gets a quick sanity-check configuration and a full monthly one, each with its own inputs and notifications: ``` from datetime import datetime import flyte import flyte.notify from flyte.models import ActionPhase env = flyte.TaskEnvironment(name="manual_trigger_example") # No `automation=`: nothing schedules these. Each is a named set of inputs # plus what to do when the run ends. # # Trigger inputs override the task's own defaults (`region="all"`, `days=7` # below) for every run fired through the trigger. Inputs the trigger does not # mention keep the task default, so `quick-report` still gets `as_of=None`. quick_report = flyte.Trigger( name="quick-report", inputs={"region": "us-east", "days": 1}, description="Yesterday only, for a fast sanity check", notifications=flyte.notify.Slack( on_phase=(ActionPhase.FAILED, ActionPhase.TIMED_OUT), webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL", message=":x: quick-report {{.Run.Name}} ended in {{.Phase}}: {{.Error}}", ), ) full_report = flyte.Trigger( name="full-report", inputs={"region": "all", "days": 30}, description="The full monthly report", env_vars={"REPORT_VERBOSE": "1"}, notifications=( flyte.notify.Email( on_phase=ActionPhase.SUCCEEDED, recipients=["reports@example.com"], subject="Monthly report {{.Run.Name}} is ready", body="Run: {{.Run.Name}}\nProject/Domain: {{.Run.Project}}/{{.Run.Domain}}", ), flyte.notify.Slack( on_phase=ActionPhase.FAILED, webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL", message=":rotating_light: full-report {{.Run.Name}} failed: {{.Error}}", ), ), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/manual.py* Trigger inputs override the task's own defaults for every run fired through the trigger. Inputs the trigger does not mention keep the task default, so `quick-report` above still runs with `as_of=None`. A manual trigger can sit next to scheduled ones on the same task. Only a schedule can bind `flyte.TriggerTime`, since a manual trigger has no fire time: ``` # A scheduled trigger can sit next to the manual ones on the same task. Only a # schedule can bind `flyte.TriggerTime`, since a manual trigger has no fire time. nightly = flyte.Trigger( name="nightly", automation=flyte.Cron("0 2 * * *"), inputs={"as_of": flyte.TriggerTime, "region": "all", "days": 1}, ) @env.task(triggers=(quick_report, full_report, nightly)) async def report_on_demand(region: str = "all", days: int = 7, as_of: datetime | None = None) -> str: as_of = as_of or datetime.now() msg = f"report for region={region!r} over the last {days} day(s), as of {as_of.isoformat()}" print(msg) return msg CODE0python flyte.deploy(env) for trigger in flyte.remote.Trigger.listall(): print(trigger.name, trigger.task_name) CODE1bash flyte deploy manual.py env flyte get trigger ``` You can also create a manual trigger for an already-deployed task. In the CLI, leave out `--schedule`: ### Programmatic CODE2 ### CLI CODE3 ## Firing a trigger on demand > [!NOTE] > Passing a trigger to `flyte.run()` requires flyte 2.7.1 or later. Every deployed trigger can be fired on demand, whether or not it has an automation. The run starts with the inputs, env vars, queue and notification rules the trigger was deployed with, and the platform records the trigger as the run's origin, exactly as it does for a scheduled fire. ### From the UI Open the task in the UI, go to its **Triggers** tab, open the trigger you want, and select **Run**. ### From Python Fetch the trigger with `flyte.remote.Trigger.get()` and pass it to `flyte.run()`, exactly like a task. This needs a remote client, so call `flyte.init_from_config()` or `flyte.init()` first. ``` import flyte import flyte.remote TASK_NAME = "manual_trigger_example.report_on_demand" def fire_as_deployed() -> flyte.remote.Run: """Fire `full-report` with exactly what it was deployed with (region="all", days=30).""" trigger = flyte.remote.Trigger.get(name="full-report", task_name=TASK_NAME) return flyte.run(trigger) CODE4 def fire_with_overrides() -> flyte.remote.Run: """Override one input; `region` keeps the trigger's value, `days` becomes 3.""" trigger = flyte.remote.Trigger.get(name="full-report", task_name=TASK_NAME) return flyte.run(trigger, days=3) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/programmatic.py* Overrides are keyword-only. Positional arguments raise an error, because a trigger already binds a subset of the inputs and positional values would be ambiguous. Passing an input name the task does not have also raises an error, listing the known inputs. `flyte.with_runcontext()` layers run-level settings on top of the trigger's own. The trigger's env vars, queue and notifications are the floor; anything the run context sets wins over the trigger's value for that setting: ``` def fire_with_runcontext() -> flyte.remote.Run: """Layer run-level overrides on top of the trigger's run spec. The trigger's own env vars and notification rules are kept; `EXTRA_FLAG` is added and the run gets a fixed name. Anything `with_runcontext` sets wins over the trigger's value. """ trigger = flyte.remote.Trigger.get(name="quick-report", task_name=TASK_NAME) return flyte.with_runcontext(env_vars={"EXTRA_FLAG": "1"}, name="quick-report-from-python").run(trigger) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/programmatic.py* Triggers returned by `flyte.remote.Trigger.listall()` can be fired the same way. Their full definition is fetched when you run them: ``` def fire_every_trigger_on_task() -> list[flyte.remote.Run]: """Triggers from `listall()` can be fired too; their details are fetched on demand. Scheduled triggers (`nightly` here) fire just fine off-schedule: the platform stamps the run start time, and any `flyte.TriggerTime` input is filled from it. """ runs = [] for trigger in flyte.remote.Trigger.listall(task_name=TASK_NAME): runs.append(flyte.run(trigger)) return runs ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/programmatic.py* A scheduled trigger fired this way runs immediately, off its schedule. The platform stamps the run start time, and any input bound to `flyte.TriggerTime` is filled from it. If you pass that input explicitly as a keyword override, your value is used instead. The returned `flyte.remote.Run` is an ordinary run handle, so you can `wait()` on it and read its inputs and outputs: CODE5 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/programmatic.py* Running a trigger is remote-only. It is not supported in local mode or with `dry_run`. === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers/artifact-triggers === Run a task automatically whenever a new version of an artifact lands, using `flyte.OnArtifact`. It fires no matter who published the version. # Trigger on new artifact versions An artifact trigger runs a task automatically whenever a new version of a named artifact lands. Use it to validate every new model, retrain when a dataset is refreshed, or kick off batch inference when fresh data arrives. A trigger is a `flyte.Trigger` whose `automation` is `flyte.OnArtifact`. The `flyte.TriggeredArtifact` sentinel marks which task input receives the new version: ```python import flyte from flyte.io import File env = flyte.TaskEnvironment(name="validation") retrain = flyte.Trigger( name="retrain-on-new-model", automation=flyte.OnArtifact(name="customer_model"), inputs={"model": flyte.TriggeredArtifact, "threshold": 0.5}, description="Validate every new customer_model version", ) @env.task(triggers=(retrain,)) async def validate(model: File, threshold: float = 0.5) -> str: ... ``` Deploy the environment to register the trigger: ### Programmatic ```python flyte.deploy(env) ``` ### CLI ```bash flyte deploy validation.py env ``` From then on, every new version of `customer_model` in the task's project and domain starts a run of `validate`, with the new version bound to the `model` input. The task body sees an ordinary `File` or `Dir` and needs no artifact-specific code. ## What counts as a new version The trigger fires no matter how the version was published: a task output wrapped with `flyte.artifacts.new()`, an upload through `flyte.remote.Artifact.create()` or `flyte create artifact`, or a Hugging Face prefetch. This makes triggers a clean handoff point between external processes and your pipelines: a partner drops a dataset, publishes it as an artifact, and your processing task starts on its own. By default any new version fires the trigger. Pass `version=` to `flyte.OnArtifact` to fire only when that exact version is published. For partitioned artifacts, you can also fire only for matching partitions and receive the partition values as inputs. See **Triggers > Trigger on partitions**. ## Rules * At most one input can be `flyte.TriggeredArtifact`. * `flyte.TriggeredArtifact` requires the automation to be `flyte.OnArtifact`. * `flyte.TriggerTime` cannot be combined with `flyte.OnArtifact`; it is for schedule triggers. * `flyte.TriggeredPartition` also requires `flyte.OnArtifact`. All other inputs must have values in the trigger definition or defaults on the task, the same as **Triggers > Configure a trigger > The `inputs` parameter**. ## Firing an artifact trigger by hand > [!NOTE] > Firing a trigger from Python requires flyte 2.7.1 or later. Passing an `Artifact` object as an input override requires flyte 2.7.2 or later; on 2.7.1 the trigger path does not bind artifacts and raises a `TypeError`. An artifact trigger can also be fired on demand, from the UI or by passing it to `flyte.run()` in Python. See **Triggers > Manual triggers and firing on demand > Firing a trigger on demand**. No new version is being published in that case, so nothing fills the `flyte.TriggeredArtifact` input. Pass it yourself as a keyword override. This needs a remote client, so initialize one first: ```python import flyte flyte.init_from_config() trigger = flyte.remote.Trigger.get(name="retrain-on-new-model", task_name="validation.validate") model = flyte.remote.Artifact.get(name="customer_model") run = flyte.run(trigger, model=model) ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers/partition-triggers === Fire an artifact trigger only for matching partitions with `flyte.OnArtifact`, and pass the partition values into the task with `flyte.TriggeredPartition`. # Trigger on partitions > [!NOTE] > Requires flyte 2.10.0 or later. An ingest job publishes `raw_events` once per day for each region, as a **Artifacts > Partitioned artifacts**. The US team owns a cleaning pipeline that should run when a US partition lands, and not when an EU one does. It also needs to know which day just arrived without opening the file to find out. A plain **Triggers > Trigger on new artifact versions** fires on every new version. Scope it to a partition and bind the partition values to inputs: ```python from datetime import datetime import flyte from flyte.io import File env = flyte.TaskEnvironment(name="us_cleaning") process_us = flyte.Trigger( name="process-new-us-partition", automation=flyte.OnArtifact(name="raw_events", region="us"), inputs={ "events": flyte.TriggeredArtifact, "day": flyte.TriggeredPartition("date"), "region": flyte.TriggeredPartition("region"), }, description="Process every new US partition of raw_events", ) @env.task(triggers=(process_us,)) async def process_partition(events: File, day: datetime, region: str) -> str: async with events.open("rb") as fh: content = bytes(await fh.read()).decode() return f"processed {region} for {day:%Y-%m-%d}: {content}" ``` Deploy the environment to register the trigger: ### Programmatic ```python flyte.deploy(env) ``` ### CLI ```bash flyte deploy us_cleaning.py env ``` From then on, a new `raw_events` version with `region="us"` starts a run of `process_partition`, with `events`, `day`, and `region` filled in. A version published for `region="eu"` is still registered, but it fires nothing. ## Narrowing which versions fire Pass partition values to `flyte.OnArtifact`, either as keyword arguments or as a `partitions` mapping: ```python flyte.OnArtifact("raw_events", region="us") flyte.OnArtifact("raw_events", partitions={"region": "us", "source": "web"}) ``` A version fires the trigger only if its partitions carry every key and value you list. Only string partitions can narrow a trigger, and the values must be strings. To act on a particular day, bind the time partition to an input and check it in the task. ## Binding partition values to inputs `flyte.TriggeredPartition("key")` fills a task input with that partition's value from the version that fired the trigger. It works like `flyte.TriggeredArtifact`, which fills in the version itself, and `flyte.TriggerTime`, which fills in a schedule's fire time. The input type depends on the partition: | Partition | Input type | |---|---| | Time partition (for example `date` or `hour`) | `datetime`, the start of the partition in UTC. A daily partition arrives as midnight UTC | | String partition (for example `region`) | `str` | You can bind any number of partition keys, with or without `flyte.TriggeredArtifact`. `flyte.TriggeredPartition` requires the automation to be `flyte.OnArtifact`. ## Firing it by hand When you **Triggers > Trigger on new artifact versions > Firing an artifact trigger by hand**, no version is being published. Pass the artifact and the partition-bound inputs as keyword overrides: ```python from datetime import date, datetime, timezone import flyte from flyte.remote import Artifact, Trigger flyte.init_from_config() trigger = Trigger.get(name="process-new-us-partition", task_name="us_cleaning.process_partition") events = Artifact.get("raw_events", date=date(2026, 8, 2), region="us") run = flyte.run(trigger, events=events, day=datetime(2026, 8, 2, tzinfo=timezone.utc), region="us") ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers/trigger-notifications === Send Slack, email, Teams, or webhook notifications when a run started by a trigger ends. # Notifications A nightly job that fails at 2 AM should reach someone on Slack, instead of waiting for a person to notice in the UI. Attach notifications to the trigger and every run it starts reports its outcome. You can attach notifications to a trigger using the `notifications` parameter of `flyte.Trigger`. Notifications fire when a triggered run reaches a terminal execution phase. > [!NOTE] > Delivery details such as `webhook_url` and `recipients` are stored with the trigger when you deploy it, and a notification can't reference a secret. To choose the destination at runtime, **Tasks > Run and deploy tasks > Send notifications from your code**. ``` import flyte from flyte import notify from flyte.models import ActionPhase env = flyte.TaskEnvironment(name="my_task_env") trigger_with_notifications = flyte.Trigger( name="daily_report", automation=flyte.Cron("0 9 * * 1-5"), notifications=( notify.Slack( on_phase=ActionPhase.FAILED, webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL", message="Run {{.Run.Name}} failed with: {{.Error}}", ), notify.Email( on_phase=ActionPhase.SUCCEEDED, recipients=["oncall@example.com"], subject="Run {{.Run.Name}} succeeded", body="Run: {{.Run.Name}}", ), ), ) @env.task(triggers=trigger_with_notifications) def process_data(date: str) -> str: return f"Processed {date}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* ## Execution phases The `on_phase` parameter accepts a single phase or a tuple of terminal phases from `flyte.models.ActionPhase`: | Phase | Description | |-------|----------------------------| | `ActionPhase.SUCCEEDED` | Run completed successfully | | `ActionPhase.FAILED` | Run failed with an error | | `ActionPhase.TIMED_OUT` | Run exceeded its timeout | | `ActionPhase.ABORTED` | Run was manually aborted | To notify on multiple phases with the same notification: ``` notify.Email( on_phase=(ActionPhase.FAILED, ActionPhase.ABORTED), recipients=["oncall@example.com"], subject="Alert: Run completed with phase {{.Phase}}", body="Run: {{.Run.Name}}\nError: {{.Error}}", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* ## Template variables All message fields support template variables that are substituted at delivery time: | Variable | Description | |--------------------|--------------------------------------------------------| | `{{.Run.Project}}` | Project name | | `{{.Run.Domain}}` | Domain name | | `{{.Run.Name}}` | Run ID | | `{{.Phase}}` | Execution phase | | `{{.Error}}` | Error message when failed or abort reason when aborted | ## Slack notifications `notify.Slack` sends a message to a Slack channel via an [incoming webhook](https://api.slack.com/messaging/webhooks). **Simple message:** ``` notify.Slack( on_phase=ActionPhase.FAILED, webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL", message="Run {{.Run.Name}} failed in {{.Run.Project}}/{{.Run.Domain}}: {{.Error}}", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* **Rich formatting with [Block Kit](https://api.slack.com/block-kit):** Use `blocks` instead of `message` for structured layouts. When `blocks` is provided, `message` is ignored. ``` notify.Slack( on_phase=ActionPhase.SUCCEEDED, webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL", blocks=[ { "type": "header", "text": {"type": "plain_text", "text": "Task Succeeded"}, }, { "type": "section", "fields": [ {"type": "mrkdwn", "text": "*Run:*\n{{.Run.Name}}"}, {"type": "mrkdwn", "text": "*Phase:*\n{{.Phase}}"}, ], }, {"type": "divider"}, { "type": "context", "elements": [ {"type": "mrkdwn", "text": "{{.Run.Project}}/{{.Run.Domain}}"}, ], }, ], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* ## Email notifications `notify.Email` sends an email notification. You can provide a plain-text `body`, an `html_body`, or both (the email is sent as multipart when both are present). ``` notify.Email( on_phase=ActionPhase.FAILED, recipients=["oncall@example.com"], cc=["team-lead@example.com"], subject="ALERT: Run {{.Run.Name}} failed", body="Run: {{.Run.Name}}\nError: {{.Error}}", html_body="Error: {{.Error}}
", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* ## Microsoft Teams notifications `notify.Teams` sends a message to a Teams channel via an incoming webhook. Use `card` for [Adaptive Card](https://adaptivecards.io/designer/) formatting; when `card` is set, `title` and `message` are ignored. ``` notify.Teams( on_phase=ActionPhase.FAILED, webhook_url="https://outlook.office.com/webhook/YOUR_WEBHOOK_URL", title="Task Failed", message="Run {{.Run.Name}} failed: {{.Error}}\n", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* ## Custom webhook notifications `notify.Webhook` sends an HTTP request to any endpoint. All string values in `headers` and `body` support template variables. ``` notify.Webhook( on_phase=ActionPhase.SUCCEEDED, url="https://api.example.com/events", method="POST", headers={"Authorization": "Bearer my-token"}, body={ "event": "task_succeeded", "run": "{{.Run.Name}}", }, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/notifications/notifications.py* To attach notifications to a single run instead of a trigger, see **Tasks > Run and deploy tasks > Run with notifications**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/triggers/manage-triggers === Deploy triggers with their task, activate or deactivate them, and delete them. # Deploy and manage triggers Triggers are deployed with their task, and you can switch them off without deleting them. To pause a nightly job during a data migration, deactivate its trigger and reactivate it afterwards. ## Deploying a task with triggers We recommend that you define your triggers in code together with your tasks and deploy them together. The Union UI displays: * `Owner` - who last deployed the trigger. * `Last updated` - who last activated or deactivated the trigger and when. Note: If you deploy a trigger with `auto_activate=True`(default), this will match the `Owner`. * `Last Run` - when was the last run created by this trigger. For development and debugging purposes, you can adjust and deploy individual triggers from the UI. To deploy a task with its triggers: ### Programmatic ```python flyte.deploy(env) ``` ### CLI ```bash flyte deploy -p -d env ``` Upon deploy, all triggers that are associated with a given task `T` will be automatically switched to apply to the version of `T` being deployed, except triggers **Triggers > Deploy and manage triggers > Pinning a trigger to a task version**, which stay on their pinned version. Triggers on task `T` that are defined elsewhere, such as in the UI, are deleted unless the task definition of `T` references them. ## Pinning a trigger to a task version Set `task_version` on a trigger to keep it on one version of its task while you deploy other versions. A pinned trigger can serve as a stable production entrypoint while CI keeps deploying pre-releases. Requires `flyte` 2.12.5 or later. ```python import flyte env = flyte.TaskEnvironment(name="ingest") prod = flyte.Trigger(name="prod", automation=flyte.Cron("0 6 * * *"), task_version="v1.4.0") @env.task(triggers=[prod]) async def entrypoint() -> None: ... ``` When you deploy another version of the task, the pinned trigger keeps launching the pinned version. The rest of the trigger's definition (automation, inputs, activation, and run settings) is still updated from your code on each deploy. Triggers without `task_version` keep following each deploy. To promote or roll back, change `task_version` and deploy again. The pinned version must already be deployed for the task, or be the version you are deploying. Otherwise the deploy fails. ## Activating and deactivating triggers By default, triggers are automatically activated upon deployment (`auto_activate=True`). Alternatively, you can set `auto_activate=False` to deploy inactive triggers. An inactive trigger will not create runs until activated. ``` env = flyte.TaskEnvironment(name="my_task_env") custom_cron_trigger = flyte.Trigger( "custom_cron", flyte.Cron("0 0 * * *"), auto_activate=False # Dont create runs yet ) @env.task(triggers=custom_cron_trigger) def custom_task() -> str: return "Hello, world!" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/triggers/triggers.py* This trigger won't create runs until it is explicitly activated. Activate it, or deactivate a trigger to stop it from creating new runs: ### Programmatic ```python # Activate flyte.remote.Trigger.update("custom_cron", "my_task_env.custom_task", active=True) # Deactivate flyte.remote.Trigger.update("custom_cron", "my_task_env.custom_task", active=False) ``` ### CLI ```bash # Activate flyte update trigger custom_cron my_task_env.custom_task --activate --project --domain # Deactivate flyte update trigger custom_cron my_task_env.custom_task --deactivate --project --domain ``` You can also view and manage your deployed triggers in the Union UI. ## Deleting triggers If you decide that you don't need a trigger anymore, you can remove the trigger from the task definition and deploy the task again. Alternatively, delete it directly: ### Programmatic ```python flyte.remote.Trigger.delete("custom_cron", "my_task_env.custom_task") ``` ### CLI ```bash flyte delete trigger custom_cron my_task_env.custom_task --project --domain ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/model-training === Train models with Flyte, from multi-node pretraining and LLM fine-tuning to classical machine learning, with every stage cached, recoverable, and sized to its own hardware. # Model training A training job is more than a training loop. Data has to be prepared, the loop needs GPUs, the model has to be evaluated, and the result has to reach the people or apps that use it. Flyte runs each of these stages as a task, so each one gets its own hardware, its own retries, and its own cache. ## The shape of a training pipeline Most pipelines in this section follow the same structure. Separate task environments hold each kind of work, and a lightweight driver task calls them in plain Python: ```mermaid flowchart LR D["driver
CPU"] --> P["prepare data
CPU, cached"] P --> T["train
GPU or multi-node"] T --> E["evaluate
small GPU or CPU"] E --> S["serve or publish"] ``` ```python data_env = flyte.TaskEnvironment(name="data", resources=flyte.Resources(cpu=8, memory="32Gi"), cache="auto") train_env = flyte.TaskEnvironment(name="train", resources=flyte.Resources(gpu="A100:8", shm="16Gi")) driver_env = flyte.TaskEnvironment(name="driver", depends_on=[data_env, train_env]) ``` The driver is an ordinary `async` function. It can loop, branch on a metric, or fan out a sweep with `asyncio.gather`, and every task it calls shows up as a separate action in the run. ## What Flyte adds to a training job | Need | Construct | |---|---| | Put each stage on the right hardware | One `flyte.TaskEnvironment` per stage, with `flyte.Resources` for CPU, memory, GPU type and count, and shared memory. See **Tasks > Configure tasks > Resources**. | | Train across several nodes | `flyte.clustered.ClusteredTaskEnvironment` runs torchrun across a group of pods. See **Model training > Pre-training**. | | Skip work that already ran | `cache="auto"` on data prep and training. A rerun with the same inputs and code returns the stored outputs. See **Tasks > Configure tasks > Caching**. | | Resume after a crash or preemption | `retries` plus `flyte.Checkpoint` restarts the loop from its last checkpoint. See **Model training > Durable training**. | | Pass datasets, checkpoints, and weights between stages | `flyte.io.Dir`, `flyte.io.File`, and DataFrames store data in your object store and pass a reference. See **Tasks > Build tasks > Files and directories**. | | Watch a run while it trains | `report=True` and `flyte.report` publish live charts to the run's UI. See **Tasks > Build tasks > Reports**. | | Run many trials at once | `asyncio.gather` or `flyte.map` fans out one task per trial. See **Model training > Hyperparameter optimization**. | On Union.ai, trained models can also be published as [artifacts](../artifacts/_index) with lineage back to the run that produced them, and **Tasks > Configure tasks > Queues** control which cluster and how much capacity each training job uses. ## Choose a page | You want to | Read | |---|---| | Train a model from scratch, or on more GPUs than one node has | **Model training > Pre-training** | | Adapt a pretrained model with SFT, LoRA, or preference tuning | **Model training > Post-training** | | Train scikit-learn or XGBoost models | **Model training > Classical machine learning** | | Sweep hyperparameters and stop weak trials early | **Model training > Hyperparameter optimization** | | Measure a model on held-out data and compare it with a baseline | **Model training > Evaluation** | | Keep a long job from losing progress | **Model training > Durable training** | To optimize a model with rewards instead of labels, see [Reinforcement learning](../reinforcement-learning/_index). To serve the model you train, see **Inference > Deploy trained models**. {{< subpage-cards >}} ## Related - [Model training tutorials](../../tutorials/model-training/_index): complete pipelines for fine-tuning and hyperparameter optimization. - [Distributed LLM pretraining](../../tutorials/frontier-ai/distributed-pretraining/_index): a GPT model pretrained on multiple H200 nodes, end to end. - [Computer vision tutorials](../../tutorials/computer-vision/_index): fine-tuning detectors and vision-language models. ## Subpages - **Model training > Pre-training** - Train a model from scratch across many GPUs and nodes, with data prep cached and sized separately from the training job. - **Model training > Post-training** - Adapt a pretrained model with supervised fine-tuning, LoRA, or preference tuning, then evaluate it and hand it to serving. - **Model training > Classical machine learning** - Train scikit-learn, XGBoost, and other CPU models with cached data prep and hyperparameter sweeps that run every trial in parallel. - **Model training > Hyperparameter optimization** - Run hyperparameter sweeps with every trial as its own task, stop weak trials early, search adaptively with Optuna, and drive sweeps from Weights & Biases or Hydra. - **Model training > Evaluation** - Run an inference pass over a held-out set, compute metrics from the stored predictions, compare against a baseline, and choose an evaluation framework for classifiers, detectors, and LLMs. - **Model training > Durable training** - Keep long training jobs from losing progress to preemption, node failures, out-of-memory errors, and scarce GPU capacity. === PAGE: https://www.union.ai/docs/v2/union/user-guide/model-training/pretraining === Train a model from scratch across many GPUs and nodes, with data prep cached and sized separately from the training job. # Pre-training Pretraining runs one training loop across more GPUs than a single machine holds. Flyte launches the nodes as one group, wires up `torch.distributed`, and runs the data pipeline and the driver on cheaper hardware next to it. ## Split the job by hardware A pretraining run has three kinds of work with very different needs. Give each its own environment: ```python import flyte from flyte.clustered import ClusteredTaskEnvironment, TorchRun image = flyte.Image.from_debian_base().with_pip_packages("torch", "datasets") data_env = flyte.TaskEnvironment( name="data", image=image, resources=flyte.Resources(cpu=16, memory="64Gi", disk="200Gi"), cache="auto", ) train_env = ClusteredTaskEnvironment( name="pretrain", image=image, resources=flyte.Resources(cpu=64, memory="512Gi", gpu="H200:8", shm="16Gi"), replicas=4, nproc_per_node=8, runtime=TorchRun(), ) driver_env = flyte.TaskEnvironment( name="driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[data_env, train_env], ) ``` - **Data loading** gets CPUs, memory, and disk for tokenization, and no GPU. `cache="auto"` means a second training run on the same dataset reuses the tokenized shards instead of rebuilding them. - **Training** gets the GPUs: 4 nodes with 8 GPUs each. Set `shm` explicitly, because NCCL and PyTorch data loaders use shared memory, and the container default is small. - **The driver** gets two CPUs. `depends_on` deploys the other two environments with it, so a single `flyte run` deploys all three. ## Run torchrun across nodes `flyte.clustered.ClusteredTaskEnvironment` runs a task on `replicas` identical pods, each starting `nproc_per_node` processes with torchrun: ``` # The torch wheel from PyPI bundles CUDA + NCCL, so the same image runs on CPU # and GPU nodes. `flyte` itself provides the `clustered` runtime entrypoint that # bootstraps torchrun inside each pod โ€” no extra runtime library is needed. image = flyte.Image.from_debian_base().with_pip_packages("torch", "numpy") resources = ( flyte.Resources(cpu=(2, 4), memory=("4Gi", "8Gi"), gpu="L4:1") if USE_GPU else flyte.Resources(cpu=(1, 2), memory=("1Gi", "2Gi")) ) env = ClusteredTaskEnvironment( name="ddp_env", image=image, resources=resources, replicas=REPLICAS, # number of pods (nodes) in the JobSet nproc_per_node=NPROC_PER_NODE, # processes (one per GPU) per pod runtime=TorchRun(rdzv_backend="static", max_restarts=0), failure_policy=ClusterFailurePolicy(max_restarts=1), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/ddp_train.py* `resources` applies to each pod, so 2 replicas with `gpu="H100:8"` and `nproc_per_node=8` is a 16-GPU job. Inside the task, torchrun has already set `RANK`, `WORLD_SIZE`, and `MASTER_ADDR`, and `flyte.ctx()` exposes the same topology to your code: CODE1 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/ddp_train.py* Every rank runs the same function. Return a value of the declared type from every rank; Flyte keeps rank 0's output. Frameworks that read the torchrun environment, such as Lightning, Hugging Face Accelerate, and DeepSpeed, work unchanged. For FSDP and Lightning versions of this task, and the prerequisites on the cluster, see [Clustered task environment](../tasks/task-configuration/clustered-task-environment.md). For JAX, set `runtime=JaxRun()` and `nproc_per_node=1`: JAX runs one process per node that owns every local GPU. ## Save checkpoints to your object store A pretraining run can take days, so save progress as it trains. Write to `flyte.ctx().checkpoint` from rank 0 only, so the ranks don't write the same file: CODE2 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-configuration/clustered-task-environment/fsdp_train.py* The checkpoint lives in your object store, not on the pod, so it survives a restart of the whole group and a retry of the task. Load it at the start of the task to continue from the last save. See [Durable training](durable-training.md). ## Schedule all nodes together A multi-node job can't start until every node is available. If pods start one at a time, the first nodes sit idle while the rest wait for capacity. Admit the job as one gang through a Kueue queue on the cluster: CODE3 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/gang_scheduling/main.py* If a higher-priority job can preempt yours after it starts, set `failure_policy=ClusterFailurePolicy(resume_after_preemption=True)`, so the job waits to be readmitted and resumes from its checkpoint without using a retry. This needs `flyte` 2.12.5 or later and, on the open-source Flyte backend, v2.0.54 or later. See [Durable training](durable-training.md#restart-a-multi-node-job). On Union.ai, a [queue](../tasks/task-configuration/queues.md) also caps the GPUs a team's training jobs can use and sets their priority. See [Resource caps and scheduling](../clusters-and-queues/resource-caps-and-scheduling.md). ## Profile a training step To find out whether a step is bound by compute, communication, or data loading, capture an NVIDIA Nsight Systems profile from the task. See the [Nsight integration](../../integrations/nsight/_index). ## Related - [Distributed LLM pretraining](../../tutorials/frontier-ai/distributed-pretraining/_index): a GPT model pretrained on multiple H200 nodes, end to end. - [Fine-tuning a VLM](../../tutorials/computer-vision/qwen-vl-finetuning/_index): multi-node DeepSpeed training with checkpoints you can resume from. - [PyTorch](../../integrations/pytorch/_index): the `Elastic` plugin config, an alternative to the clustered environment. - [Ray](../../integrations/ray/_index): run a Ray cluster from a task. - **Weights & Biases > Distributed training**: log from every rank. === PAGE: https://www.union.ai/docs/v2/union/user-guide/model-training/post-training === Adapt a pretrained model with supervised fine-tuning, LoRA, or preference tuning, then evaluate it and hand it to serving. # Post-training Post-training starts from a pretrained model and adapts it with your data: supervised fine-tuning (SFT), parameter-efficient methods such as LoRA and QLoRA, or preference tuning such as DPO. The training code is usually a library call, such as TRL's `SFTTrainer` or the Hugging Face `Trainer`. Flyte runs the stages around it: getting the base model and data onto the GPU, keeping the run recoverable, comparing the result with the base model, and handing the weights to serving. ## Define the environments Fine-tuning needs one GPU environment for training and evaluation, and a CPU environment for data prep and the driver: ``` import os main_img = flyte.Image.from_uv_script(__file__, name="llm-fine-tuning-lora-qlora", pre=True) gpu_env = flyte.TaskEnvironment( name="llm-fine-tuning-lora-qlora-gpu", image=main_img, resources=flyte.Resources(cpu=4, memory="24Gi", gpu=1), secrets=[flyte.Secret(key="huggingface-token", as_env_var="HF_TOKEN")], ) cpu_env = flyte.TaskEnvironment( name="llm-fine-tuning-lora-qlora-cpu", image=main_img, resources=flyte.Resources(cpu=2, memory="8Gi"), depends_on=[gpu_env], ) HF_TOKEN = os.environ.get("HF_TOKEN") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/llm_fine_tuning_lora_qlora/llm_fine_tuning_lora_qlora.py* - `flyte.Image.from_uv_script` builds the image from the script's own PEP 723 dependency header, so the image and your local environment install the same dependency list. - The Hugging Face token comes from a **Tasks > Configure tasks > Secrets** and is set as `HF_TOKEN`, which `transformers` and `datasets` read automatically. - `depends_on=[gpu_env]` lets a driver in the CPU environment call the GPU tasks. A single GPU is enough for LoRA on models of a few billion parameters. For full fine-tuning of a larger model, or fine-tuning with DeepSpeed, use a **Model training > Pre-training > Run torchrun across nodes**. ## Structure the pipeline A fine-tuning pipeline has the same stages whatever the method: 1. **Prepare the data** in a CPU task with `cache="auto"`, and return it as a `flyte.io.Dir`. Later runs with a different learning rate or LoRA rank skip this step. 2. **Train** in a GPU task with `report=True`, and return the adapter or model as a `flyte.io.Dir`. The directory goes to your object store, and the next task gets a reference to it. 3. **Evaluate** the base model and the fine-tuned model on the same held-out set, and report both scores. A fine-tuning run that doesn't beat the base model is a result too. 4. **Serve or publish** the model directory. Because each step is a task, switching methods is a change to one task's arguments, not to the pipeline. Comparing LoRA with full fine-tuning is two calls to the same pipeline, run side by side with `asyncio.gather`. ## Avoid downloading the base model every run A large base model takes minutes to download from Hugging Face, on every GPU task that loads it. Copy it into your object store once and pass the stored copy to each task. See **Inference > Prefetching models**. ## Resume from the last checkpoint GPU nodes get preempted, and a fine-tuning run that restarts from step 0 wastes the hours before the failure. Connect the trainer's checkpoints to `flyte.Checkpoint` with a callback: ``` class FlyteTrainerCheckpointCallback(TrainerCallback): """Mirror the Trainer's `output_dir` to the Flyte checkpoint after each epoch.""" def __init__(self, checkpoint: flyte.Checkpoint, output_dir: pathlib.Path) -> None: self._checkpoint = checkpoint self._output_dir = output_dir def on_epoch_end(self, args, state, control, **kwargs) -> None: # Trainer callbacks are synchronous, so use save_sync self._checkpoint.save_sync(self._output_dir) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/huggingface_trainer_checkpoint.py* Then load the previous attempt's checkpoint at the start of the task and pass it to `trainer.train`: CODE1 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/huggingface_trainer_checkpoint.py* With `retries` set on the task, a failed attempt restarts from the last saved epoch. The same pattern works for PyTorch Lightning, plain PyTorch loops, and Unsloth. The [Brain tumor MRI classification](../../tutorials/biotech-healthcare/tumor-detection/_index) tutorial does it for Lightning. See [Intra-task checkpoints](../tasks/task-programming/intra-task-checkpoints.md). ## Watch training while it runs `report=True` gives the task a report tab in the UI. Publish loss curves, learning-rate schedules, and sample generations with `flyte.report.replace.aio(..., do_flush=True)`, and the tab updates while the task runs. See [Reports](../tasks/task-programming/reports.md). To log to an experiment tracker instead, see the [Weights & Biases](../../integrations/wandb/_index) and [MLflow](../../integrations/mlflow/_index) integrations. ## Hand the model to serving Publish the trained model as an [artifact](../artifacts/_index): set `produces_artifacts=True` on the task and wrap its return value with `flyte.artifacts.new()`. A vLLM or FastAPI app can then serve the latest version by name, and each version records the run that produced it. See [Deploy trained models](../inference/deploy-trained-models.md). ## Related - [LLM fine-tuning with LoRA and QLoRA](../../tutorials/model-training/llm-fine-tuning-lora-qlora/_index): the full pipeline on this page, with live reports. - [Fine-tuning a VLM](../../tutorials/computer-vision/qwen-vl-finetuning/_index): multi-node fine-tuning with DeepSpeed and Lightning. - [BERT emotion classification](../../tutorials/model-training/bert-fine-tuning-emotion/_index): fine-tuning an encoder with the Hugging Face `Trainer`. - [RT-DETR object detection](../../tutorials/computer-vision/detr-object-detection/_index): fine-tuning a detector with cached data prep, live training charts, and mAP evaluation. - [Brain tumor MRI classification](../../tutorials/biotech-healthcare/tumor-detection/_index): two-phase transfer learning with checkpoints that survive preemption. - [Reinforcement learning](../reinforcement-learning/_index): post-training with rewards instead of labels. === PAGE: https://www.union.ai/docs/v2/union/user-guide/model-training/classical-ml === Train scikit-learn, XGBoost, and other CPU models with cached data prep and hyperparameter sweeps that run every trial in parallel. # Classical machine learning Classical models such as gradient-boosted trees, linear models, and random forests train on CPUs in seconds to minutes. The cost is in how many times you train them: one fit per hyperparameter setting, per fold, per feature set. Flyte turns each fit into a task, runs them all at once, and caches every result, so a sweep that took an afternoon on a laptop finishes, given enough cluster capacity, in the time of its slowest trial. ## Define the environments Trials are small and CPU-only, so each gets two CPUs. The driver gets less, because it only launches trials and compares scores: ``` import asyncio import tempfile from dataclasses import dataclass from pathlib import Path import flyte import joblib import pandas as pd from flyte.io import File # The image installs the dependencies listed in this file's script header. image = flyte.Image.from_uv_script(__file__, name="classical-ml") env = flyte.TaskEnvironment( name="classical-ml", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), ) driver_env = flyte.TaskEnvironment( name="classical-ml-driver", image=image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[env], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/classical_ml.py* `Image.from_uv_script` builds the image from the dependencies in the script's header. `depends_on=[env]` deploys the trial environment with the driver. ## Cache the data Load and clean the data in its own task, with `cache="auto"`: ``` @env.task(cache="auto") async def load_data() -> pd.DataFrame: """Load and clean the training data once. Later runs reuse the cached output.""" from sklearn.datasets import load_breast_cancer data = load_breast_cancer(as_frame=True) return data.frame.dropna() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/classical_ml.py* The task returns a `pandas.DataFrame`, which Flyte stores as Parquet in your object store. Every trial receives a reference to the same stored data, and later runs skip the load entirely. See **Tasks > Build tasks > DataFrames**. ## Score one setting per task Each hyperparameter setting is one call to an evaluation task: ``` @dataclass class Params: n_estimators: int max_depth: int @dataclass class TrialResult: params: Params score: float @env.task(cache="auto", retries=2) async def evaluate(df: pd.DataFrame, params: Params) -> TrialResult: """Score one hyperparameter setting with cross-validation.""" from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import cross_val_score X, y = df.drop(columns="target"), df["target"] model = GradientBoostingClassifier( n_estimators=params.n_estimators, max_depth=params.max_depth, random_state=0 ) score = cross_val_score(model, X, y, cv=5).mean() return TrialResult(params=params, score=float(score)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/classical_ml.py* - **Typed inputs and outputs.** `Params` and `TrialResult` are dataclasses, so the UI shows each trial's settings and score, and the driver gets real objects back. See **Tasks > Build tasks > Data classes and structures**. - **Caching per trial.** With `cache="auto"`, rerunning a sweep with one new value only runs the new trials. - **Retries per trial.** One trial that fails on a bad node retries on its own instead of failing the sweep. ## Run the sweep in parallel The final fit is one more task, which trains on all of the data and saves the model as a file: ``` @env.task async def fit(df: pd.DataFrame, params: Params) -> File: """Fit the final model on all of the data and save it as a file.""" from sklearn.ensemble import GradientBoostingClassifier X, y = df.drop(columns="target"), df["target"] model = GradientBoostingClassifier( n_estimators=params.n_estimators, max_depth=params.max_depth, random_state=0 ).fit(X, y) path = Path(tempfile.mkdtemp()) / "model.joblib" joblib.dump(model, path) return await File.from_local(str(path)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/classical_ml.py* The driver builds the grid in plain Python and launches every trial at once with `asyncio.gather`: ``` @driver_env.task(report=True) async def training_pipeline( n_estimators: list[int] = [50, 100, 200], max_depth: list[int] = [2, 3, 4], ) -> File: df = await load_data() # One task per setting, all running at once. grid = [Params(n, d) for n in n_estimators for d in max_depth] with flyte.group("sweep"): results = await asyncio.gather(*(evaluate(df, p) for p in grid)) best = max(results, key=lambda r: r.score) rows = "".join( f"{r.params.n_estimators}{r.params.max_depth}{r.score:.4f}" for r in sorted(results, key=lambda r: -r.score) ) await flyte.report.replace.aio( f"

Sweep results

" f"{rows}
n_estimatorsmax_depthCV accuracy
", do_flush=True, ) return await fit(df, best.params) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/classical_ml.py* `flyte.group("sweep")` collects the trials under one node in the UI. The driver picks the winner with ordinary Python, publishes a results table to the run's report, and calls `fit` with the best settings. The model comes back as a `flyte.io.File`, ready to pass to an evaluation task or a serving app. To limit how many trials run at once, see **Tasks > Build tasks > Controlling parallel execution**. ## Search more efficiently A grid tries every combination. To sample settings at random, stop weak trials early, or let an Optuna study choose the next setting from earlier results, see **Model training > Hyperparameter optimization**. ## Keep containers warm for short trials When each trial takes seconds, starting a container for each one costs more than the trial. **Tasks > Configure tasks > Reusable containers** keep a pool of replicas running and send each trial to a warm one. ## Related - [Fraud detection with Feast](../../tutorials/financial-services/fraud-detection-feast/_index): train an XGBoost classifier on features from a feature store. - [MLE bot](../../tutorials/agents/mle-bot/_index): an agent that designs and runs XGBoost experiments in parallel. - **Tasks > Build tasks > Mapping over inputs**: `flyte.map` for sweeps over a list. - [MLflow](../../integrations/mlflow/_index) and [Weights & Biases](../../integrations/wandb/_index): log each trial to an experiment tracker. - **Inference > Deploy trained models**: serve the fitted model behind a FastAPI app. === PAGE: https://www.union.ai/docs/v2/union/user-guide/model-training/hyperparameter-optimization === Run hyperparameter sweeps with every trial as its own task, stop weak trials early, search adaptively with Optuna, and drive sweeps from Weights & Biases or Hydra. # Hyperparameter optimization A sweep trains the same model many times with different settings and keeps the best one. Most of its cost goes to trials that turn out to be bad. Flyte makes each trial a task, so trials run in parallel on their own hardware, retry on their own, and are cached. The driver that chooses which trials to run is ordinary Python, so you can stop weak trials early and give their budget to strong ones. ## Run every trial as a task Put trials and the driver in separate environments. Each trial gets the hardware one training run needs, and the driver only chooses settings and compares scores: ``` import asyncio import math import random import tempfile from dataclasses import dataclass from pathlib import Path import flyte import joblib import pandas as pd from flyte.io import File image = flyte.Image.from_uv_script(__file__, name="hpo") trial_env = flyte.TaskEnvironment( name="hpo-trial", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), ) driver_env = flyte.TaskEnvironment( name="hpo-driver", image=image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[trial_env], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/hpo.py* The trial task trains one setting for a number of epochs and returns its validation score with a checkpoint. It can also continue from a checkpoint, which the next section uses: ``` @dataclass class Params: alpha: float eta0: float @dataclass class Trial: params: Params epochs: int score: float checkpoint: File @trial_env.task(cache="auto", retries=2) async def train_trial( df: pd.DataFrame, params: Params, epochs: int, start_epoch: int = 0, checkpoint: File | None = None ) -> Trial: """Train one setting up to `epochs`, continuing from `checkpoint` if one is given.""" from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split X, y = df.drop(columns="target").to_numpy() / 16.0, df["target"].to_numpy() X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.25, random_state=0) if checkpoint is not None: model = joblib.load(await checkpoint.download()) else: model = SGDClassifier(alpha=params.alpha, eta0=params.eta0, learning_rate="constant", random_state=0) for _ in range(start_epoch, epochs): model.partial_fit(X_train, y_train, classes=sorted(set(y))) path = Path(tempfile.mkdtemp()) / "model.joblib" joblib.dump(model, path) return Trial( params=params, epochs=epochs, score=float(model.score(X_val, y_val)), checkpoint=await File.from_local(str(path)), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/hpo.py* - **`cache="auto"`** stores every finished trial. Rerunning the sweep with more trials runs only the new ones, and a sweep that failed halfway resumes without retraining what finished. - **`retries=2`** reruns a trial that hit a bad node, without failing the sweep. - **Typed results.** `Params` and `Trial` are dataclasses, so the UI shows each trial's settings, score, and checkpoint. ## Sweep in parallel A random search samples settings and launches every trial at once. A semaphore caps how many run at the same time, so a large sweep doesn't take the whole cluster: CODE1 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/hpo.py* Sample from a seeded `random.Random`, so a rerun proposes the same settings and gets every finished trial from the cache. Random search usually finds a good setting with fewer trials than a grid, because it doesn't spend trials on dimensions that don't matter. For a grid over a few values, see [Classical machine learning](classical-ml.md#run-the-sweep-in-parallel). ## Stop weak trials early Most trials are bad after a few epochs as well as at the end. Successive halving trains every trial on a small budget, keeps the best fraction, and continues only those from their checkpoints with a larger budget: CODE2 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/hpo.py* With 16 trials and `eta=2`, the sweep trains 16 trials for 2 epochs, 8 for 4, 4 for 8, 2 for 16, and 1 for 32. Because survivors continue from their checkpoints, that is 96 epochs of training in total, against 512 to train all 16 for 32 epochs. Each rung is a group in the UI. A surviving trial passes its checkpoint to its next rung, so it continues training instead of starting over. Hyperband runs several of these brackets with different starting budgets, and the same driver loop covers it. ## Search adaptively with Optuna To let earlier trials decide which settings to try next, drive an Optuna study from the driver task. The study asks for a setting, and `self.objective` is a Flyte task that scores it, so each trial runs as its own action: CODE3 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/ml/optimizer.py* A semaphore bounds the trials in flight, and a trial that raises `flyte.errors.RuntimeUserError` is recorded as failed instead of stopping the study. Optuna's samplers, such as TPE, propose each new setting from the results so far, so the number of trials in flight trades speed against how much each proposal can learn. See the [Hyperparameter optimization](../../tutorials/model-training/hpo/_index) tutorial for the full optimizer. ## Use a sweep tool you already have These integrations run their own search and use Flyte to execute the trials: | Integration | How it sweeps | Each trial runs as | |---|---|---| | [Weights & Biases sweeps](../../integrations/wandb/sweeps.md) | `@wandb_sweep` creates a W&B sweep, and parallel agent tasks pull settings from it. W&B chooses the settings with grid, random, or Bayesian search, and plots every trial. | One call in a sweep agent task | | [Hydra](../../integrations/hydra/_index) | `--multirun` expands config overrides into a grid, and `hydra/sweeper=optuna` runs an Optuna sweeper over your Hydra config. | A separate Flyte run | | [Ray](../../integrations/ray/_index) | Ray Tune runs its schedulers, such as ASHA and PBT, on a Ray cluster that a task starts. | A Ray trial inside one task | To record every trial's settings and metrics in an experiment tracker, log from the trial task with [Weights & Biases](../../integrations/wandb/experiments.md) or [MLflow](../../integrations/mlflow/_index). ## Size trials for the hardware - **GPU trials.** Give each trial one GPU, and cap concurrency at the number of GPUs you want the sweep to use. A trial that runs out of memory raises `flyte.errors.OOMError` to the driver, which can record it as failed. See [Durable training](durable-training.md#recover-from-out-of-memory-errors). - **Multi-node trials.** Make the trial task a `flyte.clustered.ClusteredTaskEnvironment`. The driver doesn't change. See [Pre-training](pretraining.md). - **Preemptible capacity.** Trials are short and retry on their own, so they suit `interruptible=True`. Keep the driver on on-demand capacity. See **Model training > Durable training > Use spot capacity**. - **Seconds-long trials.** When a trial takes less time than a container takes to start, use **Tasks > Configure tasks > Reusable containers** to send trials to a warm pool of replicas. ## Related - [Hyperparameter optimization](../../tutorials/model-training/hpo/_index): a parallel Optuna study, end to end. - **Tasks > Build tasks > Controlling parallel execution**: limit concurrency for a whole run. - **Model training > Evaluation**: score the winning setting on a held-out set before you promote it. === PAGE: https://www.union.ai/docs/v2/union/user-guide/model-training/evaluation === Run an inference pass over a held-out set, compute metrics from the stored predictions, compare against a baseline, and choose an evaluation framework for classifiers, detectors, and LLMs. # Evaluation Evaluation answers whether a trained model is good enough to use, and whether it is better than the one you have. It has two parts with different costs: an inference pass that runs the model over a held-out set, which needs the model's hardware, and the metrics computed from its predictions, which run on a CPU in seconds. Flyte runs them as separate tasks, so you can change a metric without running the model again. ## Separate inference from metrics Give each part its own environment. The prediction tasks get the hardware the model needs, and the metrics task gets a CPU: ``` import asyncio import tempfile from dataclasses import dataclass from pathlib import Path import flyte import joblib import pandas as pd from flyte.io import File image = flyte.Image.from_uv_script(__file__, name="evaluation") # In a real pipeline, give this environment the GPU the model needs. predict_env = flyte.TaskEnvironment( name="eval-predict", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), ) metrics_env = flyte.TaskEnvironment( name="eval-metrics", image=image, resources=flyte.Resources(cpu=1, memory="2Gi"), ) driver_env = flyte.TaskEnvironment( name="eval-driver", image=image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[predict_env, metrics_env], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/evaluation.py* ## Run the inference pass The prediction task runs the model over one shard of the held-out set and returns every prediction, not only a score: ``` @predict_env.task(cache="auto", retries=2) async def predict(model: File, shard: pd.DataFrame) -> pd.DataFrame: """Run the model over one shard of the held-out set and keep every prediction.""" clf = joblib.load(await model.download()) features = shard.drop(columns="target") return pd.DataFrame( { "label": shard["target"], "prediction": clf.predict(features), "score": clf.predict_proba(features)[:, 1], } ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/evaluation.py* - **Keep the predictions.** The task returns the labels, the predicted classes, and the scores as a DataFrame. You can compute new metrics from it, slice it by subgroup, or inspect the examples the model got wrong, without running the model again. - **`cache="auto"`** stores the predictions under the model and the shard. Evaluating the same checkpoint again, for example from a later pipeline, reuses them. - **Shards in parallel.** Each shard is its own task, so a large test set finishes in the time of one shard. For an LLM or other large model, the inference pass is a batch inference job: load the model once per task, and send it as many examples at a time as the engine can batch. See **Inference > Maximize GPU utilization for batch inference** and **Inference > Stream model weights**. ## Compute metrics from the predictions The metrics task reads the stored predictions and returns typed metrics: ``` @dataclass class Metrics: accuracy: float f1: float roc_auc: float @metrics_env.task async def compute_metrics(predictions: pd.DataFrame) -> Metrics: """Compute metrics from stored predictions. Changing a metric reruns only this task.""" from sklearn.metrics import accuracy_score, f1_score, roc_auc_score y, y_hat = predictions["label"], predictions["prediction"] return Metrics( accuracy=float(accuracy_score(y, y_hat)), f1=float(f1_score(y, y_hat)), roc_auc=float(roc_auc_score(y, predictions["score"])), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/evaluation.py* It has no cache, because it is cheap. To add a metric, edit this task and rerun: the predictions come from the cache, and only the metrics run again. ## Compare against a baseline A metric means little on its own. Evaluate the candidate and the model it would replace on the same held-out set, and decide from the difference: ``` async def run_eval(model: File, test: pd.DataFrame, n_shards: int) -> Metrics: shards = [test.iloc[i::n_shards].reset_index(drop=True) for i in range(n_shards)] predictions = await asyncio.gather(*(predict(model, s) for s in shards)) return await compute_metrics(pd.concat(predictions, ignore_index=True)) @driver_env.task(report=True) async def evaluate_model(max_depth: int = 8, baseline_depth: int = 2, n_shards: int = 4) -> bool: train, test = await make_split() candidate, baseline = await asyncio.gather(train_model(train, max_depth), train_model(train, baseline_depth)) with flyte.group("candidate"): new = await run_eval(candidate, test, n_shards) with flyte.group("baseline"): old = await run_eval(baseline, test, n_shards) rows = "".join( f"{name}{getattr(old, name):.4f}{getattr(new, name):.4f}" for name in ("accuracy", "f1", "roc_auc") ) await flyte.report.replace.aio( f"

Evaluation

{rows}
MetricBaselineCandidate
", do_flush=True, ) # Promote the candidate only if it matches or beats the baseline on the metric that matters. return new.roc_auc >= old.roc_auc ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/model-training/evaluation.py* The driver evaluates both models with the same code, publishes a side-by-side table to the run's report, and returns whether the candidate should be promoted. With a small test set or a noisy metric, a difference can be chance. To compare with repeated samples and a margin, see **Project patterns > Software development lifecycle > Evaluation gates**. ## Choose an evaluation framework The framework runs inside the metrics task, or, for LLM harnesses that call the model themselves, inside the prediction task: | Model | Framework | What it computes | |---|---|---| | Classical ML | [scikit-learn metrics](https://scikit-learn.org/stable/modules/model_evaluation.html) | Accuracy, F1, ROC AUC, calibration, regression errors | | Deep learning | [TorchMetrics](https://lightning.ai/docs/torchmetrics/) | Metrics that accumulate over batches, including across ranks | | Hugging Face models | [Hugging Face Evaluate](https://huggingface.co/docs/evaluate/) | Task metrics such as BLEU, ROUGE, and seqeval | | Object detection | [pycocotools](https://github.com/cocodataset/cocoapi) or TorchMetrics `MeanAveragePrecision` | COCO mAP | | LLMs on standard benchmarks | [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) or [lighteval](https://github.com/huggingface/lighteval) | Benchmark accuracy, with a vLLM backend for throughput | | LLM agents and open-ended output | [Inspect](https://inspect.aisi.org.uk/) or an LLM judge | Multi-turn and tool-use tasks, and rubric scores | Run each benchmark as its own task, so benchmarks run in parallel and are cached separately. When the judge is a paid model API, wrap the call in `@flyte.trace`, so a retried task replays the recorded result instead of paying again. See **Reinforcement learning > Reward setup > Call a judge without paying for it twice**. ## Evaluate checkpoints while training runs To see how quality changes during a long run, evaluate checkpoints as they are saved. Have the training task return checkpoints at intervals, or split training into stages, and launch an evaluation for each checkpoint with `asyncio.create_task` while the next stage trains. The evaluations run on their own hardware and never hold up the trainer. The last checkpoint isn't always the best, so keep each checkpoint's metrics in the run's **Tasks > Build tasks > Reports** and promote the one that scores highest. ## Show results in the UI `report=True` on the driver lets it publish tables and charts, such as a confusion matrix or a precision-recall curve, to the run's report. To keep results across runs, log them from the metrics task to [Weights & Biases](../../integrations/wandb/_index) or [MLflow](../../integrations/mlflow/_index). On Union.ai, publish the metrics alongside the model as an [artifact](../artifacts/_index), so the model registry shows the evaluation that each version passed. ## Related - [BERT emotion classification](../../tutorials/model-training/bert-fine-tuning-emotion/_index): a confusion matrix and attention visualizations in the report. - [RT-DETR object detection](../../tutorials/computer-vision/detr-object-detection/_index): COCO mAP evaluation and side-by-side bounding boxes. - [Multimodal retrieval evaluation](../../tutorials/computer-vision/multimodal-retrieval-evaluation/_index): benchmarking three retrieval models on GPUs. - **Reinforcement learning > Evaluation**: how evaluating an RL policy differs. - **Inference > Deploy trained models**: serve the model that passed. === PAGE: https://www.union.ai/docs/v2/union/user-guide/model-training/durable-training === Keep long training jobs from losing progress to preemption, node failures, out-of-memory errors, and scarce GPU capacity. # Durable training The longer a training job runs, the more likely something under it fails: a spot node is reclaimed, a node fails, a batch runs out of memory, or the cluster has no free H100s. Flyte turns each of these into something your code handles, instead of a run you start over. | Failure | What to use | What happens | |---|---|---| | The task's pod dies or is preempted | `retries` with `flyte.Checkpoint` | The next attempt loads the last checkpoint and continues from there | | A node in a multi-node job fails, or the job is preempted after it starts | `ClusterFailurePolicy` | The whole group restarts in place and resumes from the checkpoint | | The container runs out of memory | `flyte.errors.OOMError` with `override` | The driver retries the task with more memory | | The GPU type you asked for isn't available | `max_queued_time` with `override` | The driver moves on to the next GPU type | | A later stage fails | Recovery or caching | A new run reuses the stages that already succeeded | ## Resume from a checkpoint after a retry `flyte.ctx().checkpoint` is a per-task store in your object store. It survives across a task's retries. Save to it as training progresses, and load from it at the start of the task: ``` @env.task(retries=RETRIES) async def train_linear(epochs: int = 10) -> float: checkpoint = flyte.ctx().checkpoint model = nn.Linear(4, 1) opt = torch.optim.SGD(model.parameters(), lr=0.01) # Resume model, optimizer, and epoch from the previous attempt, if any. prev = await checkpoint.load() if prev: blob = torch.load(prev, map_location="cpu", weights_only=False) model.load_state_dict(blob["model"]) opt.load_state_dict(blob["opt"]) start = int(blob["epoch"]) + 1 else: start = 0 wpath = pathlib.Path("pytorch_linear") / "training.pt" wpath.parent.mkdir(parents=True, exist_ok=True) failure_interval = epochs // RETRIES for epoch in range(start, epochs): x = torch.randn(8, 4) y = torch.randn(8, 1) loss = torch.nn.functional.mse_loss(model(x), y) opt.zero_grad() loss.backward() opt.step() if epoch > start and epoch % failure_interval == 0: # Simulate a failure so the next attempt resumes from the checkpoint raise RuntimeError(f"Simulated failure at epoch {epoch}") # Save model, optimizer, and epoch state to object storage. torch.save( {"model": model.state_dict(), "opt": opt.state_dict(), "epoch": epoch}, wpath, ) await checkpoint.save(wpath) with torch.no_grad(): return float(model(torch.ones(1, 4)).squeeze().item()) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/task-programming/intra-task-checkpoints/pytorch_checkpoint.py* Save the optimizer state and the step or epoch along with the weights, so the resumed attempt continues the same schedule. To connect a framework's own checkpointing, such as the Hugging Face `Trainer` or Lightning's `ModelCheckpoint`, use a callback. See **Tasks > Build tasks > Intra-task checkpoints**, and the [Brain tumor MRI classification](../../tutorials/biotech-healthcare/tumor-detection/_index) tutorial for a Lightning training task that resumes this way. ## Use spot capacity Spot and preemptible GPUs cost a fraction of on-demand ones. With checkpoints in place, a preemption costs only the work since the last save. Set `interruptible=True` and give the task retries: ```python import flyte train_env = flyte.TaskEnvironment( name="train", resources=flyte.Resources(gpu="A100:8"), interruptible=True, ) @train_env.task(retries=5) async def train(epochs: int) -> flyte.io.Dir: ... ``` Keep the driver and evaluation tasks on on-demand capacity with `interruptible=False`. See **Tasks > Configure tasks > Interruptible tasks**. ## Restart a multi-node job When one pod of a clustered job fails, the other ranks can't continue. `ClusterFailurePolicy` restarts the whole group in place: ```python import flyte from flyte.clustered import ClusterFailurePolicy, ClusteredTaskEnvironment, TorchRun env = ClusteredTaskEnvironment( name="pretrain", resources=flyte.Resources(gpu="H100:8", shm="16Gi"), replicas=4, nproc_per_node=8, runtime=TorchRun(), failure_policy=ClusterFailurePolicy(max_restarts=2, restart_on_host_maintenance=True), ) ``` - `max_restarts` is the number of in-place restarts before the attempt fails. They don't count against the task's `retries`. - `restart_on_host_maintenance=True` makes a restart caused by a node eviction free, so planned maintenance doesn't use up `max_restarts`. - `resume_after_preemption=True` keeps the attempt when Kueue preempts the job after it started. The job waits to be readmitted and then resumes, without using a retry. It needs Flyte backend v2.0.54 or later. Without it, a preemption ends the attempt, so set `retries` on the task. Pod-local disk is wiped on a restart, so write checkpoints from rank 0 to `flyte.ctx().checkpoint`. `flyte.ctx().restart_attempt` counts the in-place restarts, which is useful for logging. See **Tasks > Configure tasks > Clustered task environment > Checkpointing**. ## Recover from out-of-memory errors When a container runs out of host memory, the parent task receives `flyte.errors.OOMError` and can call the task again with more memory: ```python import flyte.errors @driver_env.task async def main(epochs: int) -> flyte.io.Dir: for memory in ["256Gi", "512Gi", "1Ti"]: try: resources = flyte.Resources(gpu="A100:8", memory=memory) return await train.override(resources=resources, retries=0)(epochs=epochs) except flyte.errors.OOMError: continue raise RuntimeError("Out of memory at every size") ``` `override` keeps the task's own `retries` unless you set them. `retries=0` sends an out-of-memory error straight back to the driver, instead of trying the same size again first. Running out of GPU memory is different: the framework raises its own exception, such as `torch.cuda.OutOfMemoryError`. See **Tasks > Build tasks > Error handling > Out-of-memory on the GPU** to catch it and retry with a smaller batch. ## Fall back to another GPU type A job that asks for scarce GPUs can wait in the queue for a long time. Set `timeout=flyte.Timeout(max_queued_time=...)` on the training task to bound the wait. When it expires, the driver catches `flyte.errors.MaxQueuedTimeExceededError` and calls the task again with `override(resources=...)` for the next GPU type on its list. See **Tasks > Build tasks > Error handling > Falling back when GPU capacity isn't available** for the full example. ## Reuse finished stages A pipeline that fails at evaluation shouldn't retrain the model. Two features keep finished stages from running again: - **Recovery** starts a new run from a failed one and reuses every action that succeeded. See **Tasks > Run and deploy tasks > Recover a failed run**. - **Caching** reuses a task's output in any later run with the same inputs and code. Set `cache="auto"` on data prep and training. See **Tasks > Configure tasks > Caching**. ## Related - **Tasks > Configure tasks > Retries and timeouts** - [Distributed LLM pretraining](../../tutorials/frontier-ai/distributed-pretraining/_index): checkpointing and fault tolerance for a multi-node pretraining run. - [Fine-tuning a VLM](../../tutorials/computer-vision/qwen-vl-finetuning/_index): multi-node fine-tuning with recovery checkpoints. - **Model training > Pre-training** - **Model training > Post-training** === PAGE: https://www.union.ai/docs/v2/union/user-guide/reinforcement-learning === Run reinforcement learning loops with Flyte, with environments, rewards, rollouts, and the trainer each on their own hardware, and a loop that survives failures. # Reinforcement learning Reinforcement learning (RL) trains a policy from rewards instead of labels. The policy acts in an environment, a reward function scores what it did, and a trainer updates the policy toward higher-scoring behavior. For LLMs, the policy is the model, an action is a completion or an agent's trajectory, and the update is a method such as GRPO or PPO. RL has more moving parts than supervised training, and they need different hardware at different times: ```mermaid flowchart LR L(["training loop
CPU driver"]) --> R["inference rollouts
GPU workers"] R --> E["environment
sandboxes, simulators"] E --> W["reward
CPU, verifiers, judges"] W --> T["trainer
GPU or multi-node"] T -- "new weights" --> R classDef gpu fill:#3b82f633,stroke:#3b82f6,stroke-width:1.5px classDef cpu fill:#94a3b826,stroke:#94a3b8,stroke-width:1px class R,T gpu class L,E,W cpu ``` In Flyte, each part is a task environment, and the loop is a Python `for` loop in a driver task. Nothing runs that a stage doesn't need: the reward tier is CPU only, the trainer only holds GPUs during an update, and the number of rollout workers follows the number of prompts in flight. ## What Flyte adds to an RL loop | Need | Construct | |---|---| | Size each part of the loop separately | One `flyte.TaskEnvironment` per role, each with its own `flyte.Resources`, retries, and timeouts | | Write the loop as ordinary code | An `async` driver task that calls rollout, reward, and train tasks, and overlaps them with `asyncio` | | Pass weights from the trainer to the rollout workers | The trainer returns a `flyte.io.Dir`, and rollout tasks read it from your object store. No direct connection between trainer and generators is needed. | | Train on more GPUs than one node has | A `flyte.clustered.ClusteredTaskEnvironment` for the trainer | | Survive a crashed driver or a failed step | `flyte.Checkpoint` for loop state, `retries` per task, and `@flyte.trace` so a retried step doesn't call a paid judge again | | Try a new reward on old rollouts | Run recovery or caching reuses rollouts whose inputs didn't change | | Inspect any iteration | `flyte.group` per iteration in the UI, and a live `flyte.report` of reward, accuracy, and loss | On Union.ai, **Tasks > Configure tasks > Reusable containers** keep the inference engine loaded between rollout calls, and [volumes](../tasks/task-programming/volumes/_index) give every episode its own copy-on-write fork of an environment's filesystem. Overlapping generation with a multi-node trainer step can hide the trainer's time almost entirely. See **Reinforcement learning > Training loop > Overlap generation with training**. ## The parts of the loop | Page | Covers | |---|---| | **Reinforcement learning > Training environment** | What the policy acts in: datasets of verifiable problems, simulators, and sandboxed agent environments | | **Reinforcement learning > Reward setup** | Verifiers, reward functions, and LLM judges, and how to change the reward without regenerating rollouts | | **Reinforcement learning > Inference rollouts** | Generating completions or trajectories from the current policy, and getting new weights to the generators | | **Reinforcement learning > Training loop** | The driver task that ties the parts together, the policy update, multi-node trainers, and overlapping generation with training | | **Reinforcement learning > Evaluation** | Sampling the policy on held-out problems, training-health metrics, and catching reward hacking | The examples on these pages come from a GRPO loop with LoRA adapters and an agentic RL loop with sandboxed environments. To fine-tune on labeled data instead, see **Model training > Post-training**. {{< subpage-cards >}} ## Related - [RL for LLMs with GRPO and LoRA](../../tutorials/reinforcement-learning/grpo-lora/_index): the GRPO loop on these pages, end to end, and its multi-node version. - [Teach a humanoid to run](../../tutorials/reinforcement-learning/humanoid-locomotion/_index): a simulator compiled onto the GPU, with a live video report of the policy as it learns. - [Reward design with Claude and sandboxes](../../tutorials/reinforcement-learning/eureka-reward-design/_index): model-written reward functions, each trained in a sandbox. - [Self-play league for Connect Four](../../tutorials/reinforcement-learning/self-play-league/_index): a learner, a league of its past snapshots, and Elo ratings. - [Durable agentic RL with SkyRL and Harbor](../../tutorials/reinforcement-learning/agentic-rl-skyrl/_index): an agentic RL loop with sandboxes, verifiers, and judges. It has an open-source version, which the open-source code on these pages comes from. - **Agents > Sandboxing > Code sandboxing**: run model-written code safely inside an environment or a reward. ## Subpages - **Reinforcement learning > Training environment** - Set up what the policy acts in, from datasets of verifiable problems to simulators and sandboxed agent environments, with each episode isolated and reproducible. - **Reinforcement learning > Reward setup** - Score rollouts with verifiers, reward functions, and LLM judges in their own CPU tier, without paying for a judge twice or regenerating rollouts to try a new reward. - **Reinforcement learning > Inference rollouts** - Generate completions and trajectories from the current policy on a pool of GPU workers, and move each new set of weights from the trainer to the generators. - **Reinforcement learning > Training loop** - Tie rollouts, rewards, and policy updates together in a durable driver task, scale the trainer across nodes, and overlap generation with training. - **Reinforcement learning > Evaluation** - Evaluate an RL policy by sampling it many times on held-out problems, report avg@k and pass@k, watch training health, catch reward hacking, and see how this differs from evaluating a supervised model. === PAGE: https://www.union.ai/docs/v2/union/user-guide/reinforcement-learning/training-environment === Set up what the policy acts in, from datasets of verifiable problems to simulators and sandboxed agent environments, with each episode isolated and reproducible. # Training environment The environment is what the policy acts in and what produces the observations a reward scores. Its shape depends on the task: | Environment | Example | Each episode is | |---|---|---| | A dataset of verifiable problems | Math word problems with known answers | One prompt, and the completions the policy samples for it | | A simulator | A MuJoCo or Brax physics model | A trajectory of observations, actions, and rewards | | A sandboxed world | A filesystem and tools an agent explores | A multi-turn trajectory of tool calls and their results | Whatever the shape, the environment has to be cheap to reset, isolated between episodes, and reproducible, so that a retried episode produces the same result. ## Use a dataset as the environment For RL on reasoning tasks, the environment is a set of prompts with checkable answers. The driver samples a batch each iteration, and the reward compares each completion with the answer. Load the dataset in a task with `cache="auto"`, or bundle a small one with the code. The loop on these pages rotates through a fixed list of prompts: ```python def _sample_prompts(iteration: int) -> list[tuple[str, str]]: start = (iteration * PROMPTS_PER_ITER) % len(DATASET) return [DATASET[(start + i) % len(DATASET)] for i in range(PROMPTS_PER_ITER)] ``` Sampling deterministically from the iteration number means a resumed loop picks up the same prompts it would have used. ## Build a world once and share it An agentic environment is a world the policy explores, such as a directory of documents, a repository, or a database. Building it can take longer than an episode, so build each world once in a cached task and pass it to every episode: ``` @sandbox_env.task(cache="auto") async def build_world(world_id: str) -> ROVolume: """Populate the world's filesystem once; sealed as a read-only volume every trial forks.""" secret_doc, secret = _world_secret(world_id) vol = Volume.new(name=f"world-{world_id}-{flyte.ctx().action.run_name}") await vol.mount() root = Path(vol.mount_path) / "docs" root.mkdir(parents=True) for i in range(N_DOCS): lines = [f"title: report {i} for {world_id}", f"owner: team-{i % 3}", f"pages: {10 + i}"] if i == secret_doc: lines.append(f"secret_sha256: {hashlib.sha256(secret.encode()).hexdigest()}") (root / f"doc_{i}.txt").write_text("\n".join(lines) + "\n") return await vol.finalize(message=f"world {world_id}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/skyrl/agentic_rl_durable.py* The world is a read-only [volume](../tasks/task-programming/volumes/_index). Each episode forks it into an instant private copy and mounts the fork: ``` @sandbox_env.task(retries=1, timeout=flyte.Timeout(max_runtime=300)) async def generate(spec: TrialSpec, weights: Weights, world: ROVolume, flaky_rate: float = 0.0) -> Trajectory: """One trial: fork the world, run the agent loop against it, return what happened. Idempotent by construction โ€” re-running produces the same trajectory (seeded by trial_id), so a retry is a clean regeneration, not a replay of stale sandbox state. """ t0 = time.monotonic() attempt = int(os.environ.get("FLYTE_ATTEMPT_NUMBER", "0")) rng = random.Random(_seed("trial", spec.trial_id)) if attempt == 0 and rng.random() < flaky_rate: raise RuntimeError(f"simulated sandbox failure for {spec.trial_id} (attempt 0)") # -> retried # [S2] instant private copy of the world for this trial fork_name = f"{world.name}-{spec.trial_id}" ws = await world.fork(name=fork_name) await ws.mount() docs = Path(ws.mount_path) / "docs" # the "agent": pick documents to read in an order driven by the policy's prior for this world prior = list(weights.doc_prior.get(spec.world_id) or [1.0] * N_DOCS) order: list[int] = [] remaining = list(range(N_DOCS)) while remaining: w = [prior[i] for i in remaining] pick = rng.choices(remaining, weights=w, k=1)[0] order.append(pick) remaining.remove(pick) turns, answer = [], None for doc in order[: spec.max_turns]: text = (docs / f"doc_{doc}.txt").read_text() found = "secret_sha256:" in text turns.append({"doc": doc, "found": found}) await asyncio.sleep(0.2) # a tool call if found: answer = text.split("secret_sha256:")[1].strip() break written = [] (docs.parent / "answer.txt").write_text(answer or "") written.append("answer.txt") if rng.random() < 0.3: # untidy agents leave scratch files behind (the judge cares) (docs.parent / "scratch.tmp").write_text("notes") written.append("scratch.tmp") return Trajectory( trial_id=spec.trial_id, world_id=spec.world_id, weights_version=weights.version, turns=turns, answer=answer, files_written=written, elapsed_s=round(time.monotonic() - t0, 2), fork_name=fork_name, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/skyrl/agentic_rl_durable.py* `cache="auto"` on the build task means every run, including one that re-scores old episodes with a new reward, gets the same world. That keeps the cache keys of the downstream tasks stable. ## Run each episode in its own task Running an episode as its own task gives it the properties an environment needs: - **Isolation.** Each episode gets a fresh container, so a policy that deletes files or fills the disk only affects its own episode. - **Limits.** `timeout=flyte.Timeout(max_runtime=300)` stops an episode that loops forever, and `retries=1` reruns one that hits a transient failure. - **Reproducibility.** Seed the episode's randomness from its ID, so a retry produces the same trajectory instead of a different one. - **Separate sizing.** The environment tier gets CPU and memory for the simulator or tools, with no GPU. Episodes are independent, so the driver launches all of them at once with `asyncio.create_task` and collects them with `asyncio.as_completed`. It awaits each episode in a `try` block, so an episode that still fails after its retries is skipped instead of failing the iteration. See **Reinforcement learning > Training loop**. ## Run model-written code safely When the policy writes code that runs during an episode or during scoring, such as a generated function and the test suite that checks it, run that code in a sandbox rather than in the task's own process. See **Agents > Sandboxing > Code sandboxing**, and the [MLE bot](../../tutorials/agents/mle-bot/_index) tutorial for an agent whose generated code runs in a sandbox. ## Serve the environment as an app Some environments are long-running servers that clients step through over HTTP, such as an environment that keeps game state between calls. Deploy the server as an [app](../apps/_index) and connect to it from the rollout tasks by its URL. The app scales and restarts independently of the training loop, and any number of rollout tasks can share it. ## Related - **Reinforcement learning > Reward setup**: score what happened in each episode. - **Reinforcement learning > Inference rollouts**: generate the policy's actions. - [Durable agentic RL with SkyRL and Harbor](../../tutorials/reinforcement-learning/agentic-rl-skyrl/_index): the world-building and episode code on this page, in a complete loop. === PAGE: https://www.union.ai/docs/v2/union/user-guide/reinforcement-learning/reward-setup === Score rollouts with verifiers, reward functions, and LLM judges in their own CPU tier, without paying for a judge twice or regenerating rollouts to try a new reward. # Reward setup The reward turns what the policy did into the number the trainer optimizes. Most rewards combine some of these: - **A verifier** checks a result against ground truth: an exact answer, a passing test suite, or a state the environment can confirm. It is deterministic and cheap. - **A rule-based score** rewards properties of the output, such as the requested format or a length limit. - **A judge** is a model that grades what a verifier can't check, such as helpfulness or efficiency. It is slower, costs money per call, and can fail. In Flyte, scoring runs in its own CPU environment. It never holds a GPU, and its retries and timeouts are separate from generation and training. ## Write a verifiable reward A verifiable reward is a plain Python function. This one gives 1.0 for the correct answer and 0.2 for using the required answer format: ``` def _extract_answer(text: str) -> str | None: """Pull the integer following the last '####' marker; fall back to the last integer in the text.""" import re if "####" in text: tail = text.rsplit("####", 1)[1] m = re.search(r"-?\d+", tail) if m: return m.group(0) nums = re.findall(r"-?\d+", text) return nums[-1] if nums else None def _reward(rollout: Rollout) -> float: """Verifiable reward: 1.0 for the correct answer, +0.2 format bonus for emitting the '####' marker.""" reward = 0.0 if "####" in rollout.completion: reward += 0.2 predicted = _extract_answer(rollout.completion) if predicted is not None and predicted == rollout.answer: reward += 1.0 return reward ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* Keep the reward function outside of any task, so you can unit-test it against hand-labeled completions without running the loop. ## Score a group per task A rule-based reward takes microseconds, so a task per completion would spend nearly all of its time starting containers. Score a whole group of completions in one task: ``` reward_env = flyte.TaskEnvironment( name="rl-grpo-reward", image=image, resources=flyte.Resources(cpu=1, memory="2Gi"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* ``` @reward_env.task async def score_group(rollouts: list[Rollout]) -> list[float]: """Score a whole prompt group in one task โ€” one reward task per group, not per rollout. The rule-based reward is microseconds of pure-Python work, so a task *per rollout* would pay pod startup over and over for trivial compute. Scoring at the group granularity (the unit `generate` already returns) keeps reward an observable, pipelined task while cutting the pod count ~GROUP_SIZEร—. """ return [_reward(r) for r in rollouts] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* The group is the unit the rollout task already returns, and the unit GRPO normalizes rewards over. Scoring at that granularity keeps reward observable as its own step in the UI, at a fraction of the task count. The driver scores each group as soon as its rollouts arrive. See [Training loop](training-loop.md). ## Call a judge without paying for it twice A judge call is an API request that costs money and can fail after it returns, for example while uploading the result. Wrap the call in `@flyte.trace`, so a retried task replays the recorded result instead of calling the judge again: CODE2 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/skyrl/agentic_rl_durable_oss.py* `verify_and_judge` combines both kinds of signal: the deterministic verifier decides whether the answer is correct, and the judge grades how the policy got there. The task returns a typed `Reward`, so each component is visible in the UI and the trainer can weight them. See [Traces](../tasks/task-programming/traces.md). ## Change the reward without regenerating rollouts Reward design is iterative. When you change the rubric, the rollouts from earlier steps are still valid inputs, and regenerating them costs GPU time. Pass the rubric to the loop as an input, and choose how to reuse the rollouts: **Recover the finished run with a new rubric.** Every action whose inputs didn't change is reused, and judging and training run again: ``` def fork_with_new_rubric(run_name: str) -> None: """Fork a finished run with a new rubric. Step 0's `generate` actions are reused, because their inputs are unchanged. `verify_and_judge` (new rubric input) and `train_step` re-run, and so do later steps' rollouts, which now see different weights. """ new = Rubric(correctness_weight=1.0, efficiency_weight=1.0, tidiness_weight=0.5, name="v2-efficiency") r = flyte.rerun(run_name, recover=True, rubric=new) print("forked run:", r.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/skyrl/agentic_rl_durable.py* See [Recover a failed run](../tasks/task-deployment/recover-runs.md#changing-inputs). **Start a new run and let the cache find the reuse.** Set `cache="auto"` on the world-building and rollout tasks. A new run with a new rubric gets every rollout whose inputs are unchanged from the cache: ``` @driver_env.task(report=True) async def rescore( n_steps: int = 3, n_worlds: int = 3, prompts_per_step: int = 3, n_samples: int = 2, ) -> list[StepResult]: """Re-run training with a new rubric. Cached `build_world` and `generate` actions are reused wherever their inputs are unchanged; judging and training re-run everywhere. Step 0 reuses every rollout (same worlds, same v0 weights). The new rewards change the weights after step 0, so later steps' `generate` inputs differ and regenerate โ€” cache-key identity finds that invalidation frontier by itself; nothing here knows about "forks". """ new = Rubric(correctness_weight=1.0, efficiency_weight=1.0, tidiness_weight=0.5, name="v2-efficiency") return await train( n_steps=n_steps, n_worlds=n_worlds, prompts_per_step=prompts_per_step, n_samples=n_samples, rubric=new ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/skyrl/agentic_rl_durable_oss.py* Either way, the first step's rollouts are reused, because the worlds and starting weights are the same. After the new reward changes the weights, later rollouts have different inputs and run again. Flyte finds that boundary from the inputs, without any extra code. ## Related - [RL for LLMs with GRPO and LoRA](../../tutorials/reinforcement-learning/grpo-lora/_index): the verifiable reward and group scoring on this page. - [Durable agentic RL with SkyRL and Harbor](../../tutorials/reinforcement-learning/agentic-rl-skyrl/_index): the judge on this page, and re-scoring old rollouts with a new rubric. - **Reinforcement learning > Training environment**: what produces the trajectories you score. - **Reinforcement learning > Training loop**: how rewards become advantages for the policy update. - **Reinforcement learning > Training environment > Run model-written code safely**: sandbox the code a reward executes. - **Project patterns > Software development lifecycle > Evaluation gates**: score a model before it is promoted. === PAGE: https://www.union.ai/docs/v2/union/user-guide/reinforcement-learning/inference-rollouts === Generate completions and trajectories from the current policy on a pool of GPU workers, and move each new set of weights from the trainer to the generators. # Inference rollouts A rollout is the policy acting: sampling completions for a prompt, or taking an agent's turns in an environment. In LLM RL, generating rollouts usually takes more time than the policy update, so the rollout tier decides how fast the loop runs. Rollouts need three things from the platform: - **An inference engine on a GPU**, such as vLLM, that batches many sequences per call. - **The current policy weights**, which change every iteration. - **Parallelism**, so many prompts generate at once. ## Generate a group per call GRPO compares several completions of the same prompt, so ask the engine for the whole group in one call. vLLM's `SamplingParams(n=GROUP_SIZE)` samples them as one batch, and the task returns them together for scoring. ## Keep the engine loaded between calls Loading a base model into vLLM takes much longer than generating a group, so don't do it on every call. A **Tasks > Configure tasks > Reusable containers** keeps a pool of rollout workers running between calls: ``` rollout_env = flyte.TaskEnvironment( name="rl-grpo-rollout", image=image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu=flyte.GPU("L4", 1), shm="auto"), reusable=flyte.ReusePolicy(replicas=(1, 4), concurrency=1, idle_ttl=300, scaledown_ttl=120), secrets=[HF_SECRET], env_vars={"VLLM_USE_V1": "1"}, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* - `replicas=(1, 4)` scales the pool from one to four GPU workers with the number of groups in flight. - `concurrency=1` sends one call at a time to each worker. A single vLLM engine batches internally and isn't safe to drive from several calls at once. - `idle_ttl=300` shuts the whole pool down after 300 seconds with no calls, and `scaledown_ttl=120` removes each idle worker after 120 seconds. Set `idle_ttl` longer than one training step, so the pool survives while the trainer runs. To keep every worker warm across the step, not just one, set `scaledown_ttl` longer than the step too. Load the engine once per worker and cache it at module level: ``` @alru_cache(maxsize=1) async def _load_engine(base_uri: str) -> Any: """Build the vLLM engine once per warm replica (cached); the frozen base stays resident in GPU.""" from vllm import LLM local_base: str = await flyte.io.Dir.from_existing_remote(base_uri).download() # plain-HF base logger.info("Building warm vLLM engine from %s", local_base) return LLM( model=local_base, enable_lora=True, max_lora_rank=LORA_RANK, max_loras=1, trust_remote_code=True, gpu_memory_utilization=0.85, max_model_len=2048, enforce_eager=True, # skip CUDA-graph capture โ†’ faster cold start for an MVP ) @alru_cache(maxsize=None) async def _adapter_local_path(adapter_uri: str) -> str: """Download a LoRA adapter once per warm replica (cached by its remote URI โ†’ one download/version).""" return await flyte.io.Dir.from_existing_remote(adapter_uri).download() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* The first call on a worker builds the engine; every later call reuses it. The image needs the `unionai-reuse` package for reusable environments. ## Generate with the current adapter Each call attaches the current LoRA adapter to the resident base model, by version: ``` @rollout_env.task async def generate( base: flyte.io.Dir, question: str, answer: str, adapter: flyte.io.Dir, version: int, group_id: int, ) -> list[Rollout]: """Generate a GROUP_SIZE group of completions for one prompt, using the current LoRA adapter. The frozen base loads exactly once per replica (cached ``_load_engine``); each adapter version is downloaded once (cached ``_adapter_local_path``) and attached per request via ``LoRARequest`` โ€” the base weights in GPU memory are never touched. """ from vllm import SamplingParams from vllm.lora.request import LoRARequest engine: Any = await _load_engine(base.path) adapter_path: str = await _adapter_local_path(adapter.path) # lora_int_id must be >= 1 and unique per adapter; version starts at 0 so shift by 1. lora: LoRARequest = LoRARequest(f"policy-v{version}", version + 1, adapter_path) sampling: SamplingParams = SamplingParams( n=GROUP_SIZE, temperature=SAMPLING_TEMPERATURE, top_p=1.0, max_tokens=MAX_NEW_TOKENS, ) prompt: str = build_prompt(question) # vLLM's generate() is a blocking call, so we run it via asyncio.to_thread to keep it off the event # loop โ€” that lets the reusable replica's background actor heartbeat stay responsive while the GPU # is busy. (We deliberately do not use flyte.extras.DynamicBatcher here: it batches many concurrent # producers, whereas this env runs concurrency=1 and each call already submits a full group of # GROUP_SIZE sequences as one vLLM batch.) outputs: Any = await asyncio.to_thread(engine.generate, [prompt], sampling, lora_request=lora) completions: list[str] = [o.text for o in outputs[0].outputs] logger.info("group %s: generated %d completions (adapter v%d)", group_id, len(completions), version) return [ Rollout(group_id=group_id, question=question, completion=c, answer=answer) for c in completions ] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* Each adapter version is downloaded once per worker. The base weights in GPU memory never reload, so moving to a new policy costs one small download. ## Move weights from the trainer to the generators ### Pass the weights as a directory The trainer returns the new policy as a `flyte.io.Dir`, and the next round of rollout tasks receives it as an input: 1. The train task saves the weights, or only the LoRA adapter, and returns `await flyte.io.Dir.from_local(path)`. 2. The driver passes that `Dir` to the next round of rollout calls. 3. Each rollout task downloads it, or reads it by its path, before generating. The weights travel through your object store, so the trainer and the generators never have to run at the same time or share a network connection. A LoRA adapter is a few megabytes, so the transfer is fast even when the base model is large. With full-weight updates, write the checkpoint once from rank 0 and pass the same `Dir` to every worker. To load full weights onto the GPU without writing them to local disk first, pass the `Dir`'s path to the model streamer. See [Stream model weights](../inference/stream-model-weights.md). ### When a volume helps A [volume](../tasks/task-programming/volumes/_index) is a versioned file system that tasks mount. For moving weights, it doesn't beat a `Dir`: - **Speed.** A rollout task reads the whole adapter or checkpoint, which a `Dir` download or the model streamer already does at object-store speed. Reads through a volume pass through a file-system layer, and loading weights into memory that way is slower than streaming them. See [Performance and trade-offs](../tasks/task-programming/volumes/performance.md#performance-and-trade-offs). - **Durability.** Both are stored in your object store, and both are immutable once a task returns them. A volume does help in these cases: - **Many rollout pods on one node.** With `allow_volumes(shared_node_cache=True)`, read-only mounts on a node share one cache, so each node fetches the weights once instead of once per pod. This matters when you pack several single-GPU rollout pods onto each multi-GPU node. - **Reading part of a large tree.** A task that needs only some files, such as one shard of a sharded checkpoint, mounts the volume and reads those files, instead of downloading the whole `Dir`. - **Data that grows across iterations.** A rollout buffer that every iteration adds to can live on a volume, with each version storing only what changed. See [Keep rollouts on a volume](training-loop.md#keep-rollouts-on-a-volume). - **A browsable history of policies.** A volume declared as an artifact publishes each committed version with a parent edge to the one before it. See [Versions, artifacts and lineage](../tasks/task-programming/volumes/versions.md). A volume has one writer while it is mounted, so in a multi-node trainer only one rank can write to it. ## Keep rollouts on-policy Training on rollouts from an older policy biases the update. Record which policy version produced each rollout, so the trainer can detect stale samples or correct for them. Pass the version number into the rollout task and return it with each rollout. To compute importance ratios, also store the token IDs and sampling log-probabilities the engine returns: set `SamplingParams(logprobs=0)`, which returns only the sampled token's log-probability, and keep it with the completion. Sample at `temperature=1.0` with `top_p=1.0`: vLLM reports log-probabilities after its sampling adjustments, so they equal the policy's own only at those settings. See **Reinforcement learning > Training loop > Overlap generation with training** for the loss that uses them. ## Related - [RL for LLMs with GRPO and LoRA](../../tutorials/reinforcement-learning/grpo-lora/_index): the rollout pool on this page, with the full loop around it. - [Durable agentic RL with SkyRL and Harbor](../../tutorials/reinforcement-learning/agentic-rl-skyrl/_index): rollouts that are multi-turn agent trajectories. - **Reinforcement learning > Training environment**: where the policy's actions run. - **Reinforcement learning > Training loop**: how the driver fans out rollouts and overlaps them with training. - **Inference > Maximize GPU utilization for batch inference**: the same engine patterns for scoring a dataset. === PAGE: https://www.union.ai/docs/v2/union/user-guide/reinforcement-learning/training-loop === Tie rollouts, rewards, and policy updates together in a durable driver task, scale the trainer across nodes, and overlap generation with training. # Training loop The training loop runs every iteration of RL: sample prompts, generate rollouts, score them, update the policy, and repeat with the new weights. In Flyte, the loop is a Python `for` loop in a driver task. The driver holds no GPU and does no heavy work; it calls tasks in the rollout, reward, and train environments, and keeps track of where the run is. ## Define the environments Each part of the loop gets its own environment. The trainer needs a GPU only while it updates the policy, and the driver is a small CPU task: ``` train_env = flyte.TaskEnvironment( name="rl-grpo-train", image=image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu=flyte.GPU("L4", 1), shm="auto"), secrets=[HF_SECRET], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* ``` driver_env = flyte.TaskEnvironment( name="rl-grpo-driver", image=image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[rollout_env, reward_env, train_env], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* `depends_on` lists every environment the driver calls, so deploying the driver deploys the whole loop. For the rollout and reward environments, see **Reinforcement learning > Inference rollouts** and **Reinforcement learning > Reward setup**. ## Write the loop The driver runs one iteration per loop pass: ``` @driver_env.task(report=True) async def train_rl(base: flyte.io.Dir, num_iterations: int = NUM_ITERATIONS) -> flyte.io.Dir: """Own the GRPO loop: fan out rollouts, score as they finish, take one GRPO step, repeat. Loop state (iteration, current adapter, and the report history) is checkpointed each iteration so a preempted driver resumes mid-run โ€” including the accumulated report rows โ€” instead of restarting. Progress is published to a live HTML report (``report=True``) after every iteration. """ ctx = flyte.ctx() cp = ctx.checkpoint if ctx is not None else None start_iter = 0 adapter: flyte.io.Dir | None = None adapter_version = 0 history: list[IterationMetrics] = [] # Resume from a prior driver attempt, if any. if cp is not None: prev = await cp.load() if prev is not None: state = json.loads(prev.read_text()) start_iter = state["iteration"] + 1 adapter_version = state["adapter_version"] adapter = flyte.io.Dir.from_existing_remote(state["adapter_path"]) history = [IterationMetrics(**row) for row in state.get("history", [])] logger.info("Resumed from checkpoint at iteration %d (adapter v%d)", start_iter, adapter_version) # Cold start: mint a fresh LoRA adapter (version 0). if adapter is None: adapter = await init_adapter(base) adapter_version = 0 await _publish_report(history, status="running") for it in range(start_iter, num_iterations): with flyte.group(f"iter-{it}"): prompts = _sample_prompts(it) # Launch every rollout group at once on the warm replicas. rollout_futs = [ asyncio.create_task(generate(base, q, a, adapter, adapter_version, group_id=gid)) for gid, (q, a) in enumerate(prompts) ] # Score each group the instant its rollout finishes โ€” reward overlaps in-flight rollouts. # One reward task per group (not per rollout): see score_group. flat_rollouts: list[Rollout] = [] reward_futs: list[asyncio.Task[list[float]]] = [] for fut in asyncio.as_completed(rollout_futs): group = await fut flat_rollouts.extend(group) reward_futs.append(asyncio.create_task(score_group(group))) group_rewards = await asyncio.gather(*reward_futs) # aligned with append order rewards = [r for gr in group_rewards for r in gr] # flatten โ†’ aligned with flat_rollouts mean_reward = sum(rewards) / len(rewards) if rewards else 0.0 logger.info("iter %d: %d rollouts, mean reward %.3f", it, len(rewards), mean_reward) # One GRPO step โ†’ next adapter version. new_version = adapter_version + 1 adapter, mean_loss, contributing = await train_step( base, flat_rollouts, rewards, adapter, new_version ) adapter_version = new_version # Record metrics for the report (accuracy/format derived directly from the rollouts). n = len(flat_rollouts) correct = sum(1 for r in flat_rollouts if _extract_answer(r.completion) == r.answer) formatted = sum(1 for r in flat_rollouts if "####" in r.completion) best_idx = max(range(n), key=lambda i: rewards[i]) if n else None history.append( IterationMetrics( iteration=it, adapter_version=adapter_version, num_rollouts=n, mean_reward=mean_reward, max_reward=max(rewards) if rewards else 0.0, accuracy=correct / n if n else 0.0, format_rate=formatted / n if n else 0.0, mean_loss=mean_loss, contributing=contributing, sample_question=flat_rollouts[best_idx].question if best_idx is not None else "", sample_completion=flat_rollouts[best_idx].completion if best_idx is not None else "", sample_reward=rewards[best_idx] if best_idx is not None else 0.0, ) ) await _publish_report(history, status="running") # Persist loop state so a preempted driver resumes here (with its report history). if cp is not None: state = { "iteration": it, "adapter_version": adapter_version, "adapter_path": adapter.path, "history": [vars(m) for m in history], } await cp.save(json.dumps(state).encode()) await _publish_report(history, status="complete") assert adapter is not None return adapter ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* Each part of the loop uses one construct: - **Fan-out.** `asyncio.create_task` launches every rollout group at once. - **Overlapping reward with generation.** `asyncio.as_completed` hands each group to `score_group` the moment it finishes, so scoring runs while slower groups are still generating. - **The update.** `train_step` takes the rollouts and rewards and returns the next adapter as a `flyte.io.Dir`, which the next iteration's rollouts receive. - **One node per iteration in the UI.** `flyte.group(f"iter-{it}")` collects an iteration's rollout, reward, and train actions, so you can open iteration 12 and see exactly which completions it trained on. - **A live report.** `report=True` and `flyte.report.replace.aio` publish reward, accuracy, and loss after every iteration. - **Resuming.** The driver saves the iteration number, the adapter's path, and the report history to `flyte.ctx().checkpoint` after every iteration. If a later attempt of the driver starts, it loads that state and continues from the next iteration instead of from the start. Set `retries` on the driver task so that a failed or preempted driver gets another attempt. The checkpoint belongs to the task's attempts within one run, so a new run starts from iteration 0. ## Compute the update The trainer turns rewards into a learning signal. GRPO normalizes each completion's reward against the other completions of the same prompt: ``` def _group_normalized_advantages(rollouts: list[Rollout], rewards: list[float]) -> list[float]: """GRPO advantage: within each prompt group, ``(r - mean) / (std + eps)``.""" import statistics from collections import defaultdict by_group: dict[int, list[int]] = defaultdict(list) for i, r in enumerate(rollouts): by_group[r.group_id].append(i) advantages = [0.0] * len(rollouts) for idxs in by_group.values(): group_rewards = [rewards[i] for i in idxs] mean = statistics.fmean(group_rewards) std = statistics.pstdev(group_rewards) if len(group_rewards) > 1 else 0.0 for i in idxs: advantages[i] = (rewards[i] - mean) / (std + 1e-4) return advantages ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/rl_grpo_lora/rl_grpo_lora.py* A completion that scored above its group's mean gets a positive advantage, and the update makes it more likely. A group where every completion scored the same gives no signal and is skipped. The policy update itself is ordinary PyTorch inside `train_step`. Libraries such as TRL work there too. ## Scale the trainer across nodes When the policy is too large to update on one node, make the trainer a `flyte.clustered.ClusteredTaskEnvironment`: CODE2 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multinode_rl_grpo_lora/rl_grpo_lora_clustered.py* `resources` applies to each pod, and the train task runs on every rank, as in [Pre-training](../model-training/pretraining.md#run-torchrun-across-nodes). Rank 0 saves the new adapter and broadcasts its path, so every rank returns the same values of the declared types. Rank 0's return value becomes the task's output, so the driver's loop doesn't change. A multi-node trainer has a cold start of its own, because every pod has to be scheduled before the step begins. The next section hides it. ## Overlap generation with training In a sequential loop, the GPUs for generation wait while the trainer runs, and the trainer waits while generation runs. Start generating the next batch before training on the current one. The body of the pipelined loop, simplified from the multi-node example: CODE3 Before the loop, the driver starts `pending` for the first batch. Each trained adapter gets a new `version`, which the rollout tasks use to tell adapters apart. The trainer's time, including its cold start, now runs under generation, and each iteration takes about as long as generation alone. The cost is that batch N+1 is generated by a policy one step behind the one it trains. Correct for this in the loss with a clipped importance ratio, using the sampling log-probabilities recorded during generation: ``` def grpo_sample_loss( new_logp: Any, old_logp: Any, ref_logp: Any, advantage: float, clip_eps: float = CLIP_EPS, kl_beta: float = KL_BETA, ) -> tuple[Any, dict[str, float]]: """Token-level clipped-ratio GRPO loss for ONE completion. All inputs are fp32 tensors of shape (T,) over the completion tokens; only ``new_logp`` requires grad. ``old_logp`` is the *behavior* policy โ€” vLLM's sampling-time logprobs, i.e. the adapter version that actually generated the rollout (one step stale when pipelining). ``ref_logp`` is the frozen base with the adapter disabled, for the KL anchor. loss = โˆ’( mean_t min(r_tยทร‚, clip(r_t, 1ยฑฮต)ยทร‚) โˆ’ ฮฒยทmean_t KL_k3 ), r_t = exp(newโˆ’old). The k3 estimator ``exp(ฮด) โˆ’ ฮด โˆ’ 1`` (ฮด = ref โˆ’ new) is non-negative and low-variance (Schulman). At r = 1 the surrogate's *gradient* equals REINFORCE's (its value does not). """ import torch ratio = torch.exp(new_logp - old_logp) clipped = torch.clamp(ratio, 1.0 - clip_eps, 1.0 + clip_eps) surrogate = torch.minimum(ratio * advantage, clipped * advantage).mean() delta = ref_logp - new_logp kl = (torch.exp(delta) - delta - 1.0).mean() loss = -(surrogate - kl_beta * kl) stats = { "loss": float(loss.detach()), "ratio": float(ratio.mean().detach()), "kl": float(kl.detach()), "clip_frac": float(((ratio - 1.0).abs() > clip_eps).float().mean().detach()), } return loss, stats def ddp_shard_step(ddp_model: Any, sample_loss_fns: list, sync_forward: Any) -> None: """Accumulate per-sample gradients, then synchronize with EXACTLY ONE collective backward. DDP fires its gradient all-reduce inside ``backward()``, so all ranks must execute the same number of collective-bearing backwards โ€” but shards are data-dependent and may be empty on some ranks. The documented escape hatch: backwards inside ``no_sync()`` accumulate grads locally with NO collectives (and free each sample's graph immediately), and the first forward-backward AFTER the context syncs everything. Every rank therefore runs one dummy 1-token forward + zero-scaled backward, unconditionally โ€” the collective count is identical on every rank *by construction*, empty shards included. (A bare ``(0.0 * sum(p.sum())).backward()`` would NOT work: it never passes through ``DDP.forward``, so the reducer is not prepared for the iteration.) """ with ddp_model.no_sync(): for fn in sample_loss_fns: fn().backward() # local grad accumulation; per-sample graph freed here (sync_forward().float().sum() * 0.0).backward() # the ONE synchronizing backward ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multinode_rl_grpo_lora/rl_grpo_lora_clustered.py* `old_logp` comes from the rollout, `new_logp` from the policy being trained, and `ref_logp` from the base model with the adapter turned off. The ratio of new to old is clipped, so a stale sample can't move the policy far, and the KL term keeps the policy close to the base model. See [Keep rollouts on-policy](inference-rollouts.md#keep-rollouts-on-policy). Run held-out evaluation off the critical path too. Launch the evaluation of step N with `asyncio.create_task` and await it after step N+1 trains, so it never sits between iterations. See [Evaluation](evaluation.md). For a GRPO loop on Qwen3-8B with a two-node, eight-GPU trainer, overlapping cut each iteration from 434 seconds to 298 in steady state. See [We ran multi-node GRPO on 8 GPUs and the trainer cost us nothing](https://www.union.ai/blog-post/we-ran-multi-node-grpo-on-8-gpus-and-the-trainer-cost-us-nothing). ## Make each step durable Checkpointing the driver protects the loop's position. To also protect the work inside an iteration, make each step a pure function of its inputs: - Set `retries` on rollout, reward, and train tasks, so a transient failure reruns one task, not the iteration. - Seed each rollout from its prompt and iteration, for example with vLLM's `SamplingParams(seed=...)`, so a retried rollout produces the same result. Without a seed, sampling at a nonzero temperature gives a different result on every attempt, and caching the rollout isn't sound. - Pass weights and optimizer state in and out of the train task as `flyte.io.Dir`, instead of keeping them in a long-lived process. A replayed step then recomputes the same outputs. - Set `cache="auto"` on steps that are pure, so a rerun of the loop returns finished steps from the cache. ## Keep rollouts on a volume Weights and optimizer state move best as a `flyte.io.Dir`, because every task that receives them reads all of them. See [Move weights from the trainer to the generators](inference-rollouts.md#move-weights-from-the-trainer-to-the-generators). Rollouts are different: they accumulate across iterations, and later work often reads only part of them. An off-policy trainer samples from a replay buffer, an analysis reads the completions from a few iterations, and an evaluation rescores them with a new verifier. Store them on a [volume](../tasks/task-programming/volumes/_index) that each iteration forks and adds to: CODE4 - **Each version is cheap.** A fork is copy-on-write, so each iteration's version stores only its own new file and shares the rest with the version before it. - **Readers mount only what they need.** A trainer task that receives the `ROVolume` mounts it and reads the iterations it samples from, without downloading the whole buffer. - **Every version stays addressable.** The driver keeps the `ROVolume` for each iteration, and any later task or run can mount the buffer as it was after any iteration. Create the first, empty version with `Volume.new()` in a task before the loop, and pass the version each call returns to the next one, so the buffer is a chain of versions. Each fork has one writer, so writes never collide. ## Related - [RL for LLMs with GRPO and LoRA](../../tutorials/reinforcement-learning/grpo-lora/_index): the loop on this page, including the multi-node, pipelined version. - [Durable agentic RL with SkyRL and Harbor](../../tutorials/reinforcement-learning/agentic-rl-skyrl/_index): an agentic loop with sandboxed episodes and a judge. - [Intra-task checkpoints](../tasks/task-programming/intra-task-checkpoints.md): the checkpoint store the driver uses. - [Grouping actions](../tasks/task-programming/grouping-actions.md): how `flyte.group` organizes the run's UI. === PAGE: https://www.union.ai/docs/v2/union/user-guide/reinforcement-learning/evaluation === Evaluate an RL policy by sampling it many times on held-out problems, report avg@k and pass@k, watch training health, catch reward hacking, and see how this differs from evaluating a supervised model. # Evaluation Evaluating an RL policy takes more than evaluating a supervised model. The training reward is a proxy that the policy is optimized to exploit, and the data the policy trains on is data it generated itself. A rising reward can mean the policy got better, or that it found a flaw in the reward. Evaluation has to tell the two apart. ## How it differs from supervised evaluation | | Supervised model | RL policy | |---|---|---| | **What you score** | One prediction per example, often with greedy decoding | Many samples per problem, at the temperature the policy will run at | | **The metric** | Accuracy or loss on a held-out split | avg@k and pass@k on held-out problems, scored by a verifier the policy didn't train against | | **Training signal** | The loss on labeled data, which tracks quality | The reward, which can rise while quality falls | | **What can go wrong** | Overfitting to the training split | Reward hacking, entropy collapse, and loss of general capabilities | | **Which checkpoint** | Usually the last, or the lowest validation loss | Often an earlier one, chosen by held-out evaluation | | **Variance** | One run is usually representative | Results vary between seeds, so compare several runs | For supervised evaluation, see **Model training > Evaluation** in Model training. ## Sample each problem many times A policy samples, so one completion per problem gives a noisy score. Generate `k` completions per problem and report statistics over them: - **avg@k** is the mean accuracy over all `k` samples. It estimates pass@1, the chance that one sample is right, with much less noise than a single sample. - **pass@k** is the chance that at least one of `k` samples is right. It measures coverage: which problems the policy can solve at all. - **maj@k** scores the most common answer among `k` samples. Report it when the policy will be used with majority voting. Report both avg@k and pass@k. RL with verifiable rewards often raises avg@k much more than pass@k at large `k`: it makes the policy sample the answers it could already reach more reliably, and a base model sampled many times can solve as many problems. Comparing the policy with its base model on both metrics shows which one improved. Evaluate at the sampling settings the policy will be used with, and state them with the results. Long chain-of-thought models are commonly evaluated at a temperature of about 0.6 with `top_p=0.95`, because greedy decoding makes them repeat themselves. ## Run evaluation as a task The evaluation task loads the base model and the policy's adapter into vLLM, samples `n` completions for every problem, and scores them with the verifier: ```python import math import flyte eval_env = flyte.TaskEnvironment( name="rl-eval", image=image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1"), ) def pass_at_k(n: int, c: int, k: int) -> float: """The unbiased estimate of pass@k from n samples, c of them correct.""" if n - c < k: return 1.0 return 1.0 - math.comb(n - c, k) / math.comb(n, k) @eval_env.task(cache="auto", retries=2) async def evaluate_policy( base: flyte.io.Dir, adapter: flyte.io.Dir | None, benchmark: str, n: int = 16, k: int = 8 ) -> dict[str, float]: from vllm import LLM, SamplingParams from vllm.lora.request import LoRARequest problems = load_problems(benchmark) # held-out prompts with known answers engine = LLM(model=await base.download(), enable_lora=adapter is not None) lora = LoRARequest("eval", 1, await adapter.download()) if adapter else None sampling = SamplingParams(n=n, temperature=0.6, top_p=0.95, max_tokens=4096, seed=0) outputs = engine.generate([p.prompt for p in problems], sampling, lora_request=lora) correct = [sum(verify(o.text, p.answer) for o in out.outputs) for p, out in zip(problems, outputs)] lengths = [len(o.token_ids) for out in outputs for o in out.outputs] return { f"avg@{n}": sum(correct) / (n * len(problems)), f"pass@{k}": sum(pass_at_k(n, c, k) for c in correct) / len(problems), "mean_length": sum(lengths) / len(lengths), } ``` `load_problems` and `verify` are your own functions. Use the same answer extraction for every model you compare, and score an answer that can't be parsed as wrong. - **`adapter=None` evaluates the base model** with the same code, which gives you the baseline to compare against. - **`cache="auto"`** keys the result on the checkpoint, the benchmark, and the settings. Re-evaluating a checkpoint you already scored costs nothing. - **`seed=0`** makes a retried evaluation produce the same samples. Run one task per checkpoint and benchmark, all at once: ```python import asyncio @driver_env.task(report=True) async def evaluate_checkpoints( base: flyte.io.Dir, adapters: list[flyte.io.Dir], benchmarks: list[str] ) -> list[dict[str, float]]: candidates = [None, *adapters] # the base model first return await asyncio.gather( *(evaluate_policy(base, a, b) for a in candidates for b in benchmarks) ) ``` Train on one set of problems and evaluate on problems the policy never saw, such as a held-out split of the same dataset or a public benchmark: AIME and MATH-500 for math, LiveCodeBench for code, or SWE-bench Verified and Terminal-Bench for agents. Check that no evaluation problem appears in the training prompts. ## Evaluate during training Evaluate the policy every few iterations, so you see held-out accuracy next to the training reward. In the driver loop, launch the evaluation of iteration N with `asyncio.create_task` and collect it later, so it never sits between iterations. See **Reinforcement learning > Training loop > Overlap generation with training**. Evaluate the base model before the first iteration too, so every later score has a baseline. Afterwards, evaluate every saved checkpoint on the full benchmarks. The best checkpoint is often not the last one. ## Watch training health Some failures show up in the loop's own numbers before they show up in an evaluation. Log these from the train task every iteration, and plot them in the driver's report: | Metric | What to watch for | |---|---| | Mean reward, and each reward component | A reward that rises while held-out accuracy stays flat | | Reward standard deviation within groups | Falling toward zero, which means the policy gives every completion the same score | | Fraction of groups with zero advantage | A high fraction means most prompts give no learning signal, because they are too easy or too hard | | Policy entropy | A fast collapse toward zero, which means the policy has stopped exploring | | KL divergence to the reference model | Steady growth, which means the policy is drifting far from the base model | | Clip fraction | A high fraction means the policy changes too much per step | | Mean response length, and the fraction cut off at the length limit | Growth without a gain in accuracy, or completions that hit the limit | ## Catch reward hacking The policy optimizes the reward you wrote, including its mistakes. Look for these signs: - **The training reward and held-out accuracy diverge.** The reward keeps rising, and accuracy on the held-out verifier doesn't. - **A judge and a verifier disagree.** If the reward uses an LLM judge, score a sample of completions with a deterministic verifier or a second judge, and track how often they disagree. - **The output gets longer without getting better.** A judge that prefers longer answers rewards length itself. - **The verifier accepts wrong answers.** Before training, test the reward against outputs that should fail, such as answers in the wrong format or empty code. Keep the evaluation verifier separate from the reward function, so a flaw in the reward doesn't also hide in the evaluation. Because every completion a rollout task returns is stored, you can read the completions the reward scored highest at any iteration and check them yourself. ## Check what the policy may have lost RL on a narrow task can lower performance on others. Rerun a broad suite, such as instruction-following and general-knowledge benchmarks, on the final policy and on the base model. [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) and [lighteval](https://github.com/huggingface/lighteval) run standard benchmarks with a vLLM backend. [Inspect](https://inspect.aisi.org.uk/) runs agentic and multi-turn evaluations. Run each suite in its own task, so suites run in parallel and are cached separately. ## Compare runs across seeds Two RL runs with different seeds can end far apart. Before you conclude that one setting beats another, train each with several seeds and compare the distributions, not single runs. For classic RL, report the episode return over 10 or more seeds with confidence intervals, and use the interquartile mean, which is less sensitive to outlier runs. [rliable](https://github.com/google-research/rliable) computes both. Each seed is its own run of the training loop, so launch them in parallel from one driver. ## Related - **Reinforcement learning > Reward setup**: the reward the policy trains on. - **Reinforcement learning > Training loop**: where evaluation runs during training. - **Project patterns > Software development lifecycle > Evaluation gates**: promote a policy only when it beats what is live. - **Model training > Evaluation**: evaluating supervised models. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference === Run models from Flyte by calling a hosted provider, serving open-weight models on your own GPUs, deploying the models your tasks train, or making typed model calls. # Inference Choose how to run a model based on where it lives and how you call it: | You want to | Use | |---|---| | Call a hosted model such as Fireworks, OpenAI, or Anthropic from a task or app | [Providers](./providers/_index) | | Serve an open-weight LLM on your own GPUs at high throughput | **Inference > Self-hosted endpoints > vLLM** or **Inference > Self-hosted endpoints > SGLang** | | Serve a small LLM with minimal setup | **Inference > Self-hosted endpoints > Ollama** | | Serve quantized GGUF weights, a model larger than VRAM, or a model on CPU only | **Inference > Self-hosted endpoints > llama.cpp** | | Serve any model behind your own API | **Inference > Self-hosted endpoints > FastAPI** or **Inference > Self-hosted endpoints > Other frameworks** such as Ray Serve, LitServe, and BentoML | | Copy Hugging Face weights into your storage before serving them | **Inference > Prefetching models** | | Serve a model you trained in a task | **Inference > Deploy trained models** | | Score a dataset on GPUs as a job, with no endpoint | **Inference > Maximize GPU utilization for batch inference** | | Load weights inside a task from object storage | **Inference > Stream model weights** | | Ask a model many typed questions in one call and branch on calibrated answers | [Decision models](./decision-models/_index) | Most hosted providers, and vLLM, SGLang, Ollama, and llama.cpp endpoints, expose the OpenAI API or an API compatible with it. Code written against the OpenAI SDK moves between them by changing the base URL, the API key, and the model name. Some providers, such as Anthropic, need their own SDK. See [Providers](./providers/_index#providers-with-their-own-sdk). ## Route calls through the Inference Gateway The [Inference Gateway](./inference-gateway/_index) puts one endpoint in front of hosted providers, including Fireworks, and the models you serve with vLLM or SGLang. It adds budgets, fallbacks between providers, and guardrails. See [Choose direct calls or the gateway](./providers/_index#choose-direct-calls-or-the-gateway). {{< subpage-cards >}} ## Subpages - **Inference > Providers** - Call hosted LLM and model APIs such as Fireworks AI, OpenAI, and Anthropic from Flyte tasks and apps, with API keys stored as secrets. - **Inference > Self-hosted endpoints** - Serve models on your own GPUs or CPUs, with vLLM, SGLang, Ollama, llama.cpp, FastAPI, Ray Serve, LitServe, BentoML, or another framework. - **Inference > Prefetching models** - Download and shard a HuggingFace model before an inference app starts. - **Inference > Deploy trained models** - Serve a model trained in a Flyte task behind an endpoint, with vLLM, SGLang, or your own FastAPI app. - **Inference > Maximize GPU utilization for batch inference** - Keep expensive GPUs busy during batch inference instead of idle and waiting. - **Inference > Stream model weights** - Load a model's safetensors weights from object storage onto the GPU inside a task, without writing them to local disk. - **Inference > Inference Gateway** - One endpoint in your own cloud for every model call, with virtual keys and budgets, fallbacks when a provider fails, and guardrails on every prompt and answer. - **Inference > Decision models** - Answer many typed questions in one call, with calibrated confidence, and decide what happens next in code. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/providers === Call hosted LLM and model APIs such as Fireworks AI, OpenAI, and Anthropic from Flyte tasks and apps, with API keys stored as secrets. # Providers Tasks and apps can call a hosted model API using a key from your own provider account. Billing, rate limits, and data handling stay under your agreement with the provider. You store the key as a secret, and your code reads it from an environment variable at runtime. This works on both BYOC and Self-managed deployments. To add budgets, fallbacks, and guardrails, route the same calls through the **Inference > Providers > Choose direct calls or the gateway**. ## Supported providers These guides cover setup and a complete task for the most common providers: {{< subpage-cards >}} ### Other OpenAI-compatible providers These providers work with the OpenAI SDK by changing the base URL. Start from the **Inference > Providers > Fireworks > Call Fireworks from a task**, and change the base URL, the secret, the environment variable, and the model. | Provider | Get an API key | Base URL | Conventional variable | |---|---|---|---| | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/foundry/openai/api-version-lifecycle) | Your Azure resource | `https://.openai.azure.com/openai/v1/` | `AZURE_OPENAI_API_KEY` | | [Gemini API](https://ai.google.dev/gemini-api/docs/openai) | [Google AI Studio](https://aistudio.google.com/apikey) | `https://generativelanguage.googleapis.com/v1beta/openai/` | `GEMINI_API_KEY` | | [Mistral AI](https://docs.mistral.ai/resources/sdks) | Mistral console, **API Keys** | `https://api.mistral.ai/v1` | `MISTRAL_API_KEY` | | [Cohere](https://docs.cohere.com/docs/compatibility-api) | [API keys](https://dashboard.cohere.com/api-keys) | `https://api.cohere.ai/compatibility/v1` | `CO_API_KEY` | | [Groq](https://console.groq.com/docs/quickstart) | [API keys](https://console.groq.com/keys) | `https://api.groq.com/openai/v1` | `GROQ_API_KEY` | | [DeepSeek](https://api-docs.deepseek.com/) | DeepSeek platform, **API keys** | `https://api.deepseek.com` | `DEEPSEEK_API_KEY` | | [Grok API](https://docs.x.ai/docs/tutorial) | xAI console, **API Keys** | `https://api.x.ai/v1` | `XAI_API_KEY` | | [Perplexity](https://docs.perplexity.ai/docs/agent-api/openai-compatibility) | [API keys](https://console.perplexity.ai/project/keys) | `https://api.perplexity.ai/v1` | `PERPLEXITY_API_KEY` | | [Cerebras](https://inference-docs.cerebras.ai/resources/openai) | Cerebras Cloud console, **API Keys** | `https://api.cerebras.ai/v1` | `CEREBRAS_API_KEY` | | [OpenRouter](https://openrouter.ai/docs/quickstart) | [API keys](https://openrouter.ai/keys) | `https://openrouter.ai/api/v1` | `OPENROUTER_API_KEY` | | [Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers/index) | [Access tokens](https://huggingface.co/settings/tokens) | `https://router.huggingface.co/v1` | `HF_TOKEN` | | [Nebius Token Factory](https://docs.tokenfactory.nebius.com/quickstart) | Token Factory console | `https://api.tokenfactory.nebius.com/v1/` | `NEBIUS_API_KEY` | | [Sarvam AI](https://docs.sarvam.ai/api/getting-started/models/openweight) | [Key management](https://indus.sarvam.ai/key-management) | `https://api.sarvam.ai/v2` | `SARVAM_API_KEY` | | [Wafer](https://docs.wafer.ai/serverless) | Wafer dashboard | `https://pass.wafer.ai/v1` | Your choice | Two of these differ from the task: - **Azure OpenAI:** Set `model` to the name of your deployment, not the name of the underlying model. - **Perplexity:** Its Agent API uses OpenAI's Responses format, so call `client.responses.create()` instead of `client.chat.completions.create()`. Support for its earlier Sonar Chat Completions API has ended. ### Providers with their own SDK These providers don't document an OpenAI-compatible endpoint for production use. Add the SDK to the image and pass it the key from the environment. See the **Inference > Providers > Anthropic** for the pattern. | Provider | Get an API key | Python package | Conventional variable | Models | |---|---|---|---|---| | **Inference > Providers > Anthropic** | [API keys](https://platform.claude.com/settings/keys) | `anthropic` | `ANTHROPIC_API_KEY` | Chat | | [ElevenLabs](https://elevenlabs.io/docs/quickstart) | [API keys](https://elevenlabs.io/app/api/api-keys) | `elevenlabs` | `ELEVENLABS_API_KEY` | Speech | | [Runway](https://docs.dev.runwayml.com/guides/using-the-api/) | [Developer portal](https://dev.runway.com/) | `runwayml` | `RUNWAYML_API_SECRET` | Video and image | | [TypeSafe](https://docs.typesafe.ai/introduction/quickstart.md) | TypeSafe console | `typesafe-sdk` | `TYPESAFE_API_KEY` | Typed answers | ## Store the API key as a secret Run this command without `--value` and paste the key at the prompt, which keeps it out of your shell history: ```bash flyte create secret fireworks-api-key --project --domain development ``` Leave out `--project` and `--domain` to make the secret available across your organization. Prefer a project and domain, so that one team's tasks can't use another team's key. Check that the secret exists: ```bash flyte get secret --project --domain development ``` The output lists metadata such as the name and scope. It never includes the value. Each cluster pool has its own secret store. If your organization has more than one pool, an organization-wide secret needs `--cluster-pool`. See **Tasks > Configure tasks > Secrets > Org-wide secrets in a multi-cluster deployment**. Secret values stay in your own infrastructure and no API returns them. See **Data protection > Secrets management**. ## Call the provider from a task Declare the secret on the environment and read it from the environment variable. This task calls Fireworks AI through the OpenAI SDK: ``` import asyncio import os import flyte env = flyte.TaskEnvironment( name="fireworks-inference", image=flyte.Image.from_debian_base().with_pip_packages("openai"), secrets=flyte.Secret(key="fireworks-api-key", as_env_var="FIREWORKS_API_KEY"), ) @env.task async def summarize(text: str) -> str: from openai import AsyncOpenAI client = AsyncOpenAI( base_url="https://api.fireworks.ai/inference/v1", api_key=os.environ["FIREWORKS_API_KEY"], ) response = await client.chat.completions.create( model="accounts/fireworks/models/glm-5p3-flash", messages=[{"role": "user", "content": f"Summarize in two sentences:\n\n{text}"}], ) return response.choices[0].message.content @env.task async def main(texts: list[str]) -> list[str]: return await asyncio.gather(*(summarize(text) for text in texts)) if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, texts=["First document...", "Second document..."]) print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/call_fireworks.py* A task can only read a secret whose scope covers the project and domain it runs in. Provider model IDs change often, so check the provider's model catalog for current names. ## Call the provider from an app `AppEnvironment` takes the same `secrets` argument, and the app reads the same environment variable: ``` app_env = FastAPIAppEnvironment( name="summarizer-api", app=app, image=flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "openai"), secrets=flyte.Secret(key="fireworks-api-key", as_env_var="FIREWORKS_API_KEY"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/call_from_app.py* ## Use a different key for one call Override the secret for a single invocation when the same task needs different credentials, for example per team: ``` team_b = summarize.override( secrets=flyte.Secret(key="fireworks-api-key-team-b", as_env_var="FIREWORKS_API_KEY") ) result = await team_b(text=text) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/override_key.py* The override replaces the environment's secrets for that call. On a **Tasks > Configure tasks > Reusable containers** it raises an error unless you also pass `reusable="off"`. See **Tasks > Configure tasks > Overrides > Overriding secrets**. ## Choose direct calls or the gateway Calling a provider directly needs the fewest moving parts. The [Inference Gateway](../inference-gateway/_index) supports all of the providers above, including Fireworks, behind one endpoint. | | Direct call | Inference Gateway | |---|---|---| | **Key your code holds** | The provider's API key | A virtual key with its own budget and rate limit | | **Change provider** | Change the base URL, key, and model | Change the model name | | **Provider outage** | Handle it in your code | Fall back to another model | | **Prompt and answer checks** | Write them into each task or app | Global guardrails on every call | | **Spend across teams** | One view per provider account | One view per virtual key | To move to the gateway, **Inference > Inference Gateway > Providers > Add a hosted provider**, which stores the key as an organization-wide secret, then **Inference > Inference Gateway > Use from tasks and apps**. ## Keep keys safe - **Never return a key from a task.** Task outputs are written in plaintext to your object store and appear in the UI and in downstream tasks. - **Keep keys out of code, task inputs, and `flyte.run()` arguments.** Inputs are stored and displayed the same way as outputs. - **Rotate without downtime.** Create a key at the provider, delete and re-create the secret with the new value, redeploy apps that use it, and then revoke the old key. ## Troubleshooting **The provider returns 401:** The key is invalid, revoked, or was stored with a typo. Test it outside Flyte with the provider's REST API, then re-create the secret. **The task fails before it runs, with a secret not found error:** The secret's scope doesn't cover the task's project and domain. List secrets with the same `--project` and `--domain` the task uses. **The provider returns 429:** You've reached a rate limit on your provider account. Check its limits and your usage in the provider's console. ## Subpages - **Inference > Providers > Fireworks** - Call the Fireworks AI API from Flyte tasks and apps with the OpenAI SDK: store your API key as a secret, set the base URL, and use serverless or on-demand model - **Inference > Providers > OpenAI** - Call the OpenAI API from Flyte tasks and apps: store your OpenAI API key as a secret and read it from the environment in your code. - **Inference > Providers > Anthropic** - Call the Anthropic API and Claude models from Flyte tasks and apps: store your API key as a secret and use the anthropic Python SDK. - **Inference > Providers > AWS Bedrock** - Call the Amazon Bedrock API from Flyte tasks and apps with the OpenAI SDK: store your API key as a secret and set the base URL. - **Inference > Providers > Google Vertex AI** - Call Google Vertex AI from Flyte tasks and apps with the OpenAI SDK: store a service account key as a secret and request an access token in the task. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/providers/fireworks === Call the Fireworks AI API from Flyte tasks and apps with the OpenAI SDK: store your API key as a secret, set the base URL, and use serverless or on-demand model # Fireworks [Fireworks AI](https://docs.fireworks.ai/getting-started/quickstart) has an OpenAI-compatible API, so a Flyte task or app can call it with the OpenAI SDK by changing the base URL. | Setting | Value | |---|---| | Base URL | `https://api.fireworks.ai/inference/v1` | | API key | [API keys](https://app.fireworks.ai/settings/users/api-keys) | | Environment variable | `FIREWORKS_API_KEY` | ## Store your Fireworks API key Run this command and paste the key at the prompt: ```bash flyte create secret fireworks-api-key --project --domain development ``` ## Call Fireworks from a task ``` import asyncio import os import flyte env = flyte.TaskEnvironment( name="fireworks-inference", image=flyte.Image.from_debian_base().with_pip_packages("openai"), secrets=flyte.Secret(key="fireworks-api-key", as_env_var="FIREWORKS_API_KEY"), ) @env.task async def summarize(text: str) -> str: from openai import AsyncOpenAI client = AsyncOpenAI( base_url="https://api.fireworks.ai/inference/v1", api_key=os.environ["FIREWORKS_API_KEY"], ) response = await client.chat.completions.create( model="accounts/fireworks/models/glm-5p3-flash", messages=[{"role": "user", "content": f"Summarize in two sentences:\n\n{text}"}], ) return response.choices[0].message.content @env.task async def main(texts: list[str]) -> list[str]: return await asyncio.gather(*(summarize(text) for text in texts)) if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, texts=["First document...", "Second document..."]) print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/call_fireworks.py* Models on Fireworks' serverless tier use the name `accounts/fireworks/models/`. Some catalog models aren't available on that tier and need a dedicated deployment. ## Call Fireworks from an app An `AppEnvironment` takes the same `secrets` argument, and the app reads the same environment variable. See [Call the provider from an app](./_index#call-the-provider-from-an-app). ## Use an on-demand deployment An on-demand deployment runs a model on dedicated GPUs. To use one, change only the model name. The base URL, the key, and the secret stay the same: ``` # An on-demand deployment, in place of the model name above. on_demand_model = "accounts//deployments/" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/call_fireworks.py* A deployment that has scaled to zero returns a 503 while it scales up, so give the task **Tasks > Configure tasks > Retries and timeouts**. ## Handle rate limits A 429 means you've reached a rate limit on your Fireworks account. You can move to an on-demand deployment, but its requests still count toward account-wide limits, and a 429 there usually means the GPUs are saturated. ## Route calls through the Inference Gateway To add budgets, fallbacks, and guardrails, **Inference > Inference Gateway > Providers > Add a hosted provider** using the same secret, then **Inference > Inference Gateway > Use from tasks and apps**. See [Choose direct calls or the gateway](./_index#choose-direct-calls-or-the-gateway). === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/providers/openai === Call the OpenAI API from Flyte tasks and apps: store your OpenAI API key as a secret and read it from the environment in your code. # OpenAI A Flyte task or app can call the [OpenAI API](https://developers.openai.com/api/docs/quickstart) with the OpenAI SDK and a key from your own account. | Setting | Value | |---|---| | Base URL | SDK default | | API key | [API keys](https://platform.openai.com/settings/organization/api-keys) | | Environment variable | `OPENAI_API_KEY` | ## Store your OpenAI API key Run this command and paste the key at the prompt: ```bash flyte create secret openai-api-key --project --domain development ``` ## Call OpenAI from a task ``` import os import flyte env = flyte.TaskEnvironment( name="openai-inference", image=flyte.Image.from_debian_base().with_pip_packages("openai"), secrets=flyte.Secret(key="openai-api-key", as_env_var="OPENAI_API_KEY"), ) @env.task async def summarize(text: str) -> str: from openai import AsyncOpenAI client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"]) response = await client.chat.completions.create( model="gpt-6-astra", messages=[{"role": "user", "content": f"Summarize in two sentences:\n\n{text}"}], ) return response.choices[0].message.content if __name__ == "__main__": flyte.init_from_config() run = flyte.run(summarize, text="First document...") print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/call_openai.py* ## Call OpenAI from an app An `AppEnvironment` takes the same `secrets` argument, and the app reads the same environment variable. See [Call the provider from an app](./_index#call-the-provider-from-an-app). ## Route calls through the Inference Gateway To add budgets, fallbacks, and guardrails, **Inference > Inference Gateway > Providers > Add a hosted provider** using the same secret, then **Inference > Inference Gateway > Use from tasks and apps**. See [Choose direct calls or the gateway](./_index#choose-direct-calls-or-the-gateway). === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/providers/anthropic === Call the Anthropic API and Claude models from Flyte tasks and apps: store your API key as a secret and use the anthropic Python SDK. # Anthropic A Flyte task or app can call the [Anthropic API](https://platform.claude.com/docs/en/get-started) with the `anthropic` Python SDK and a key from your own account. | Setting | Value | |---|---| | Python package | `anthropic` | | API key | [API keys](https://platform.claude.com/settings/keys) | | Environment variable | `ANTHROPIC_API_KEY` | ## Store your Anthropic API key Run this command and paste the key at the prompt: ```bash flyte create secret anthropic-api-key --project --domain development ``` ## Call Anthropic from a task ``` import os import flyte env = flyte.TaskEnvironment( name="anthropic-inference", image=flyte.Image.from_debian_base().with_pip_packages("anthropic"), secrets=flyte.Secret(key="anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ) @env.task async def summarize(text: str) -> str: from anthropic import AsyncAnthropic client = AsyncAnthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) response = await client.messages.create( model="claude-opus-5-5", max_tokens=1000, messages=[{"role": "user", "content": f"Summarize in two sentences:\n\n{text}"}], ) return response.content[0].text if __name__ == "__main__": flyte.init_from_config() run = flyte.run(summarize, text="First document...") print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/call_anthropic.py* ## Call Anthropic from an app An `AppEnvironment` takes the same `secrets` argument, and the app reads the same environment variable. See [Call the provider from an app](./_index#call-the-provider-from-an-app). Anthropic also has an OpenAI-compatible endpoint, which its docs describe as being for testing and comparing models, not production. ## Route calls through the Inference Gateway To add budgets, fallbacks, and guardrails, **Inference > Inference Gateway > Providers > Add a hosted provider** using the same secret, then **Inference > Inference Gateway > Use from tasks and apps**. See [Choose direct calls or the gateway](./_index#choose-direct-calls-or-the-gateway). === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/providers/amazon-bedrock === Call the Amazon Bedrock API from Flyte tasks and apps with the OpenAI SDK: store your API key as a secret and set the base URL. # AWS Bedrock [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-chat-completions.html) has an OpenAI-compatible API, so a Flyte task or app can call it with the OpenAI SDK by changing the base URL. | Setting | Value | |---|---| | Base URL | `https://bedrock-runtime..amazonaws.com/openai/v1` | | API key | Bedrock console, **API keys** | | Environment variable | `AWS_BEARER_TOKEN_BEDROCK` | ## Store your Bedrock API key Run this command and paste the key at the prompt: ```bash flyte create secret amazon-bedrock-api-key --project --domain development ``` ## Call Bedrock from a task ``` import os import flyte env = flyte.TaskEnvironment( name="amazon-bedrock-inference", image=flyte.Image.from_debian_base().with_pip_packages("openai"), secrets=flyte.Secret(key="amazon-bedrock-api-key", as_env_var="AWS_BEARER_TOKEN_BEDROCK"), ) @env.task async def summarize(text: str) -> str: from openai import AsyncOpenAI client = AsyncOpenAI( base_url="https://bedrock-runtime..amazonaws.com/openai/v1", api_key=os.environ["AWS_BEARER_TOKEN_BEDROCK"], ) response = await client.chat.completions.create( model="", messages=[{"role": "user", "content": f"Summarize in two sentences:\n\n{text}"}], ) return response.choices[0].message.content if __name__ == "__main__": flyte.init_from_config() run = flyte.run(summarize, text="First document...") print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/call_amazon_bedrock.py* Replace `` with a model from the [Bedrock docs](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-chat-completions.html). ## Call Bedrock from an app An `AppEnvironment` takes the same `secrets` argument, and the app reads the same environment variable. See [Call the provider from an app](./_index#call-the-provider-from-an-app). ## Use a Bedrock API key Pass a Bedrock API key to the OpenAI SDK as `api_key`. AWS recommends short-term keys for production, which you'd need to refresh in the secret before they expire. ## Route calls through the Inference Gateway To add budgets, fallbacks, and guardrails, **Inference > Inference Gateway > Providers > Add a hosted provider** using the same secret, then **Inference > Inference Gateway > Use from tasks and apps**. See [Choose direct calls or the gateway](./_index#choose-direct-calls-or-the-gateway). === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/providers/vertex-ai === Call Google Vertex AI from Flyte tasks and apps with the OpenAI SDK: store a service account key as a secret and request an access token in the task. # Google Vertex AI [Google Vertex AI](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/start/openai) has an OpenAI-compatible endpoint, but it takes a short-lived OAuth access token rather than a static API key. The token expires after 1 hour by default, so it doesn't fit a static secret. Instead, store a service account key as a secret, and have the task request a token when it starts. | Setting | Value | |---|---| | Base URL | `https://aiplatform.googleapis.com/v1/projects//locations//endpoints/openapi` | | Credentials | Google Cloud service account key | | Environment variable | None | ## Store your service account key Create a **Tasks > Configure tasks > Secrets > Using a file secret** from the key file: ```bash flyte create secret vertex-service-account --from-file --project --domain development ``` ## Call Vertex AI from a task ``` import flyte BASE_URL = "https://aiplatform.googleapis.com/v1/projects//locations//endpoints/openapi" env = flyte.TaskEnvironment( name="vertex-ai-inference", image=flyte.Image.from_debian_base().with_pip_packages("google-auth[requests]", "openai"), secrets=flyte.Secret(key="vertex-service-account", mount="/etc/flyte/secrets"), ) @env.task async def summarize(text: str) -> str: from google.auth.transport.requests import Request from google.oauth2 import service_account from openai import AsyncOpenAI credentials = service_account.Credentials.from_service_account_file( "/etc/flyte/secrets/vertex-service-account", scopes=["https://www.googleapis.com/auth/cloud-platform"], ) credentials.refresh(Request()) client = AsyncOpenAI(base_url=BASE_URL, api_key=credentials.token) response = await client.chat.completions.create( model="", messages=[{"role": "user", "content": f"Summarize in two sentences:\n\n{text}"}], ) return response.choices[0].message.content if __name__ == "__main__": flyte.init_from_config() run = flyte.run(summarize, text="First document...") print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/providers/call_vertex_ai.py* Replace ``, ``, and `` with your own values. ## Call Vertex AI from an app An `AppEnvironment` takes the same `secrets` argument, and the app reads the same environment variable. See [Call the provider from an app](./_index#call-the-provider-from-an-app). ## Route calls through the Inference Gateway To add budgets, fallbacks, and guardrails, **Inference > Inference Gateway > Providers > Add a hosted provider** using the same secret, then **Inference > Inference Gateway > Use from tasks and apps**. See [Choose direct calls or the gateway](./_index#choose-direct-calls-or-the-gateway). === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/self-hosted-endpoints === Serve models on your own GPUs or CPUs, with vLLM, SGLang, Ollama, llama.cpp, FastAPI, Ray Serve, LitServe, BentoML, or another framework. # Self-hosted endpoints Serve a model as an app on your own compute. The vLLM, SGLang, Ollama, and llama.cpp endpoints expose the OpenAI API, so code written against the OpenAI SDK reaches any of them by changing the base URL, the API key, and the model name. FastAPI and other frameworks serve any model behind the API you define. | You want to | Use | |---|---| | Serve an LLM at high throughput | **Inference > Self-hosted endpoints > vLLM** | | Serve an LLM with structured generation | **Inference > Self-hosted endpoints > SGLang** | | Serve a small LLM with minimal setup | **Inference > Self-hosted endpoints > Ollama** | | Serve quantized GGUF weights, a model larger than VRAM, or a model on CPU only | **Inference > Self-hosted endpoints > llama.cpp** | | Serve any model behind your own REST API | **Inference > Self-hosted endpoints > FastAPI** | | Serve a model with Ray Serve, LitServe, BentoML, or another framework | **Inference > Self-hosted endpoints > Other frameworks** | {{< subpage-cards >}} ## Subpages - **Inference > Self-hosted endpoints > vLLM** - Deploy a high-throughput vLLM model server. - **Inference > Self-hosted endpoints > SGLang** - Deploy an SGLang model server for fast structured generation. - **Inference > Self-hosted endpoints > Ollama** - Serve open models locally with Ollama's OpenAI-compatible API. - **Inference > Self-hosted endpoints > llama.cpp** - Serve quantized GGUF models with llama-server as a Flyte app, on GPU or CPU, behind an OpenAI-compatible API. - **Inference > Self-hosted endpoints > FastAPI** - Serve any Python model behind a custom REST API on your own compute with FastAPI, for models and request shapes an LLM server doesn't cover. - **Inference > Self-hosted endpoints > Other frameworks** - Serve models with Ray Serve, LitServe, BentoML, or any other ML serving framework by running its server in a generic AppEnvironment. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/self-hosted-endpoints/vllm === Deploy a high-throughput vLLM model server. # vLLM vLLM is a high-performance library for serving large language models (LLMs). Flyte provides `VLLMAppEnvironment` for deploying vLLM model servers. ## Installation First, install the vLLM plugin: ```bash pip install flyteplugins-vllm ``` ## Basic vLLM endpoint Here's a simple example serving a HuggingFace model: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b45", # ] # /// """A simple vLLM app example.""" from flyteplugins.vllm import VLLMAppEnvironment import flyte # {{docs-fragment basic-vllm-app}} vllm_app = VLLMAppEnvironment( name="my-llm-app", model_hf_path="Qwen/Qwen3-0.6B", # HuggingFace model path model_id="qwen3-0.6b", # Model ID exposed by vLLM resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU required for LLM serving disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), requires_auth=False, ) # {{/docs-fragment basic-vllm-app}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(vllm_app) print(f"Deployed vLLM app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/vllm/basic_vllm.py* ## Using prefetched models You can use models prefetched with `flyte.prefetch`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b45", # ] # override-dependencies = [ # "cel-python; sys_platform == 'never'", # ] # /// """vLLM app using prefetched models.""" from flyteplugins.vllm import VLLMAppEnvironment import flyte # {{docs-fragment prefetch}} # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_hf_path="Qwen/Qwen3-0.6B", # this is a placeholder model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi"), stream_model=True, # Stream model directly from blob store to GPU requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config() # Prefetch the model first run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model app = flyte.serve( vllm_app.clone_with( vllm_app.name, model_hf_path=None, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), ) ) print(f"Deployed vLLM app: {app.url}") # {{/docs-fragment prefetch}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/vllm/vllm_with_prefetch.py* ## Model streaming `VLLMAppEnvironment` supports streaming models directly from blob storage to GPU memory, reducing startup time. When `stream_model=True` and the `model_path` argument is provided with either a `flyte.io.Dir` or `RunOutput` pointing to a path in object store: - Model weights stream directly from storage to GPU - Faster startup time (no full download required) - Lower disk space requirements > [!NOTE] > The contents of the model directory must be compatible with the vLLM-supported formats, e.g. the HuggingFace model > serialization format. ## Custom vLLM arguments Use `extra_args` to pass additional arguments to vLLM: ```python vllm_app = VLLMAppEnvironment( name="custom-vllm-app", model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", extra_args=[ "--max-model-len", "8192", # Maximum context length "--gpu-memory-utilization", "0.8", # GPU memory utilization "--trust-remote-code", # Trust remote code in models ], resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), # ... ) ``` See the [vLLM documentation](https://docs.vllm.ai/en/stable/configuration/engine_args.html) for all available arguments. ## Using the OpenAI-compatible API Once deployed, your vLLM endpoint exposes an OpenAI-compatible API: ```python from openai import OpenAI client = OpenAI( base_url="https://your-app-url/v1", # vLLM endpoint api_key="your-api-key", # If you passed an --api-key argument ) response = client.chat.completions.create( model="qwen3-0.6b", # Your model_id messages=[ {"role": "user", "content": "Hello, how are you?"} ], ) print(response.choices[0].message.content) ``` > [!TIP] > If you passed an `--api-key` argument, you can use the `api_key` parameter to authenticate your requests. > See **Apps > Build apps > Secret-based authentication > Authentication for vLLM and SGLang apps > Deploy vLLM app with authentication** for more details on how to pass auth secrets to your app. ## Multi-GPU inference (Tensor parallelism) For larger models, use multiple GPUs with tensor parallelism: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b45", # ] # /// """vLLM app with multi-GPU tensor parallelism.""" from flyteplugins.vllm import VLLMAppEnvironment import flyte # {{docs-fragment multi-gpu}} vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", model_hf_path="meta-llama/Llama-2-70b-hf", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # 4 GPUs for tensor parallelism disk="100Gi", ), extra_args=[ "--tensor-parallel-size", "4", # Use 4 GPUs "--max-model-len", "4096", "--gpu-memory-utilization", "0.9", ], requires_auth=False, ) # {{/docs-fragment multi-gpu}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(vllm_app) print(f"Deployed vLLM app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/vllm/vllm_multi_gpu.py* The `tensor-parallel-size` should match the number of GPUs specified in resources. ## Model sharding with prefetch You can prefetch and shard models for multi-GPU inference: ```python # Prefetch with sharding configuration run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(gpu="L40s:4"), shard_config=flyte.prefetch.ShardConfig( engine="vllm", args=flyte.prefetch.VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), ) run.wait() # Use the sharded model vllm_app = VLLMAppEnvironment( name="sharded-llm-app", model_path=flyte.app.RunOutput(type="directory", run_name=run.name), model_id="llama-2-70b", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4", disk="100Gi"), extra_args=["--tensor-parallel-size", "4"], stream_model=True, ) ``` See **Inference > Prefetching models** for more details on sharding. ## Autoscaling vLLM endpoints work well with autoscaling: ```python vllm_app = VLLMAppEnvironment( name="autoscaling-llm-app", model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), scaling=flyte.app.Scaling( replicas=(0, 1), # Scale to zero when idle scaledown_after=600, # 10 minutes idle before scaling down ), # ... ) ``` ## Best practices 1. **Use prefetching**: Prefetch models for faster deployment and better reproducibility 2. **Enable streaming**: Use `stream_model=True` to reduce startup time and disk usage 3. **Right-size GPUs**: Match GPU memory to model size 4. **Configure memory utilization**: Use `--gpu-memory-utilization` to control memory usage 5. **Use tensor parallelism**: For large models, use multiple GPUs with `tensor-parallel-size` 6. **Set autoscaling**: Use appropriate idle TTL to balance cost and performance 7. **Limit context length**: Use `--max-model-len` for smaller models to reduce memory usage ## Troubleshooting **Model loading fails:** - Verify GPU memory is sufficient for the model - Check that the model path or HuggingFace path is correct - Review container logs for detailed error messages **Out of memory errors:** - Reduce `--max-model-len` - Lower `--gpu-memory-utilization` - Use a smaller model or more GPUs **Slow startup:** - Enable `stream_model=True` for faster loading - Prefetch models before deployment - Use faster storage backends ## API reference See the [vLLM API reference](../../../api-reference/integrations/vllm/_index) for full details. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/self-hosted-endpoints/sglang === Deploy an SGLang model server for fast structured generation. # SGLang SGLang is a fast structured generation library for large language models (LLMs). Flyte provides `SGLangAppEnvironment` for deploying SGLang model servers. ## Installation First, install the SGLang plugin: ```bash pip install flyteplugins-sglang ``` ## Basic SGLang endpoint Here's a simple example serving a HuggingFace model: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-sglang>=2.0.0b45", # ] # /// """A simple SGLang app example.""" from flyteplugins.sglang import SGLangAppEnvironment import flyte # {{docs-fragment basic-sglang-app}} sglang_app = SGLangAppEnvironment( name="my-sglang-app", model_hf_path="Qwen/Qwen3-0.6B", # HuggingFace model path model_id="qwen3-0.6b", # Model ID exposed by SGLang resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU required for LLM serving disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), requires_auth=False, ) # {{/docs-fragment basic-sglang-app}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(sglang_app) print(f"Deployed SGLang app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/sglang/basic_sglang.py* ## Using prefetched models You can use models prefetched with `flyte.prefetch`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-sglang>=2.0.0b45", # ] # /// """SGLang app using prefetched models.""" from flyteplugins.sglang import SGLangAppEnvironment import flyte # {{docs-fragment prefetch}} # Use the prefetched model sglang_app = SGLangAppEnvironment( name="my-sglang-app", model_hf_path="Qwen/Qwen3-0.6B", # this is a placeholder model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi"), stream_model=True, # Stream model directly from blob store to GPU requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config() # Prefetch the model first run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() app = flyte.serve( sglang_app.clone_with( sglang_app.name, model_hf_path=None, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), ) ) print(f"Deployed SGLang app: {app.url}") # {{/docs-fragment prefetch}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/sglang/sglang_with_prefetch.py* ## Model streaming `SGLangAppEnvironment` supports streaming models directly from blob storage to GPU memory, reducing startup time. When `stream_model=True` and the `model_path` argument is provided with either a `flyte.io.Dir` or `RunOutput` pointing to a path in object store: - Model weights stream directly from storage to GPU - Faster startup time (no full download required) - Lower disk space requirements > [!NOTE] > The contents of the model directory must be compatible with the SGLang-supported formats, e.g. the HuggingFace model > serialization format. ## Custom SGLang arguments Use `extra_args` to pass additional arguments to SGLang: ```python sglang_app = SGLangAppEnvironment( name="custom-sglang-app", model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", extra_args=[ "--max-model-len", "8192", # Maximum context length "--mem-fraction-static", "0.8", # Memory fraction for static allocation "--trust-remote-code", # Trust remote code in models ], resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), # ... ) ``` See the [SGLang server arguments documentation](https://docs.sglang.io/advanced_features/server_arguments.html) for all available options. ## Using the OpenAI-compatible API Once deployed, your SGLang endpoint exposes an OpenAI-compatible API: ```python from openai import OpenAI client = OpenAI( base_url="https://your-app-url/v1", # SGLang endpoint api_key="your-api-key", # If you passed an --api-key argument ) response = client.chat.completions.create( model="qwen3-0.6b", # Your model_id messages=[ {"role": "user", "content": "Hello, how are you?"} ], ) print(response.choices[0].message.content) ``` > [!TIP] > If you passed an `--api-key` argument, you can use the `api_key` parameter to authenticate your requests. > See **Apps > Build apps > Secret-based authentication > Deploy SGLang app with authentication** for more details on how to pass auth secrets to your app. ## Multi-GPU inference (Tensor parallelism) For larger models, use multiple GPUs with tensor parallelism: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-sglang>=2.0.0b45", # ] # /// """SGLang app with multi-GPU tensor parallelism.""" from flyteplugins.sglang import SGLangAppEnvironment import flyte # {{docs-fragment multi-gpu}} sglang_app = SGLangAppEnvironment( name="multi-gpu-sglang-app", model_hf_path="meta-llama/Llama-2-70b-hf", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # 4 GPUs for tensor parallelism disk="100Gi", ), extra_args=[ "--tp", "4", # Tensor parallelism size (4 GPUs) "--max-model-len", "4096", "--mem-fraction-static", "0.9", ], requires_auth=False, ) # {{/docs-fragment multi-gpu}} # {{docs-fragment deploy}} if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(sglang_app) print(f"Deployed SGLang app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/sglang/sglang_multi_gpu.py* The tensor parallelism size (`--tp`) should match the number of GPUs specified in resources. ## Model sharding with prefetch You can prefetch and shard models for multi-GPU inference using SGLang's sharding: ```python # Prefetch with sharding configuration run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(gpu="L40s:4"), shard_config=flyte.prefetch.ShardConfig( engine="vllm", args=flyte.prefetch.VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), ) run.wait() # Use the sharded model sglang_app = SGLangAppEnvironment( name="sharded-sglang-app", model_path=flyte.app.RunOutput(type="directory", run_name=run.name), model_id="llama-2-70b", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4", disk="100Gi"), extra_args=["--tp", "4"], stream_model=True, ) ``` See **Inference > Prefetching models** for more details on sharding. ## Autoscaling SGLang endpoints work well with autoscaling: ```python sglang_app = SGLangAppEnvironment( name="autoscaling-sglang-app", model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), scaling=flyte.app.Scaling( replicas=(0, 1), # Scale to zero when idle scaledown_after=600, # 10 minutes idle before scaling down ), # ... ) ``` ## Structured generation SGLang is particularly well-suited for structured generation tasks. The deployed app supports standard OpenAI API calls, and you can use SGLang's advanced features through the API. ## Best practices 1. **Use prefetching**: Prefetch models for faster deployment and better reproducibility 2. **Enable streaming**: Use `stream_model=True` to reduce startup time and disk usage 3. **Right-size GPUs**: Match GPU memory to model size 4. **Use tensor parallelism**: For large models, use multiple GPUs with `--tp` 5. **Set autoscaling**: Use appropriate idle TTL to balance cost and performance 6. **Configure memory**: Use `--mem-fraction-static` to control memory allocation 7. **Limit context length**: Use `--max-model-len` for smaller models to reduce memory usage ## Troubleshooting **Model loading fails:** - Verify GPU memory is sufficient for the model - Check that the model path or HuggingFace path is correct - Review container logs for detailed error messages **Out of memory errors:** - Reduce `--max-model-len` - Lower `--mem-fraction-static` - Use a smaller model or more GPUs **Slow startup:** - Enable `stream_model=True` for faster loading - Prefetch models before deployment - Use faster storage backends ## API reference See the [SGLang API reference](../../../api-reference/integrations/sglang/_index) for full details. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/self-hosted-endpoints/ollama === Serve open models locally with Ollama's OpenAI-compatible API. # Ollama [Ollama](https://ollama.com/) is a lightweight runtime for serving open large language models (LLMs) locally, with a built-in OpenAI-compatible API. It is a good fit for smaller models and quick local-style serving, and complements the higher-throughput **Inference > Self-hosted endpoints > vLLM** and **Inference > Self-hosted endpoints > SGLang** integrations. Unlike vLLM and SGLang, Ollama has no dedicated `*AppEnvironment` plugin. Instead, you serve it with the generic **Apps > Build apps > Single-script apps**: an image that installs Ollama plus a small entrypoint that launches `ollama serve` and pulls the model on startup. ## Installation Ollama needs no Flyte plugin โ€” it is installed into the app image. Start from the default Flyte base image and add the Ollama binary with a build command: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A simple Ollama serving app example. Unlike vLLM and SGLang, Ollama has no dedicated ``*AppEnvironment`` plugin, so it is served with the generic ``flyte.app.AppEnvironment``: an image that installs Ollama plus a small ``--server`` entrypoint that launches ``ollama serve`` and pulls the model on startup. Ollama exposes an OpenAI-compatible API, so clients call it exactly like the vLLM / SGLang apps. """ import os import subprocess import sys import time import urllib.request from pathlib import Path import flyte import flyte.app # Any tag from https://ollama.com/library. Small models run fine on CPU; larger # ones benefit from the GPU requested below. MODEL = "qwen3:0.6b" # Bind Ollama to the app port so the platform can route to it. PORT = 8080 file_name = Path(__file__).name # {{docs-fragment ollama-image}} # Install Ollama on top of the default Flyte base image. `install.sh` drops the # `ollama` binary into /usr/local/bin (no systemd is needed inside a container). image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("curl") .with_commands(["curl -fsSL https://ollama.com/install.sh | sh"]) ) # {{/docs-fragment ollama-image}} # {{docs-fragment ollama-app}} ollama_app = flyte.app.AppEnvironment( name="ollama-app", image=image, args=["python", file_name, "--server"], port=PORT, resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU accelerates inference; omit to run small models on CPU disk="20Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), requires_auth=False, ) # {{/docs-fragment ollama-app}} # {{docs-fragment server}} def serve() -> None: """Start `ollama serve`, wait for it, pull the model, then block.""" # Bind to all interfaces so the platform can route to the server. server = subprocess.Popen( ["ollama", "serve"], env={**os.environ, "OLLAMA_HOST": f"0.0.0.0:{PORT}"}, ) # Wait for the server to accept connections. for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{PORT}/api/version", timeout=2) break except Exception: time.sleep(1) # Pull the model so the OpenAI-compatible endpoint can serve it. subprocess.run( ["ollama", "pull", MODEL], env={**os.environ, "OLLAMA_HOST": f"127.0.0.1:{PORT}"}, check=True, ) print(f"Ollama serving '{MODEL}' on port {PORT}") server.wait() # {{/docs-fragment server}} # {{docs-fragment deploy}} if __name__ == "__main__": if "--server" in sys.argv: serve() else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(ollama_app) print(f"Deployed Ollama app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/ollama/basic_ollama.py* The `install.sh` script drops the `ollama` binary into `/usr/local/bin`; no systemd service is needed inside a container. ## Basic Ollama endpoint Define the app with a GPU-backed `AppEnvironment`. The `args` run the script's `--server` entrypoint, which starts Ollama and pulls the model: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A simple Ollama serving app example. Unlike vLLM and SGLang, Ollama has no dedicated ``*AppEnvironment`` plugin, so it is served with the generic ``flyte.app.AppEnvironment``: an image that installs Ollama plus a small ``--server`` entrypoint that launches ``ollama serve`` and pulls the model on startup. Ollama exposes an OpenAI-compatible API, so clients call it exactly like the vLLM / SGLang apps. """ import os import subprocess import sys import time import urllib.request from pathlib import Path import flyte import flyte.app # Any tag from https://ollama.com/library. Small models run fine on CPU; larger # ones benefit from the GPU requested below. MODEL = "qwen3:0.6b" # Bind Ollama to the app port so the platform can route to it. PORT = 8080 file_name = Path(__file__).name # {{docs-fragment ollama-image}} # Install Ollama on top of the default Flyte base image. `install.sh` drops the # `ollama` binary into /usr/local/bin (no systemd is needed inside a container). image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("curl") .with_commands(["curl -fsSL https://ollama.com/install.sh | sh"]) ) # {{/docs-fragment ollama-image}} # {{docs-fragment ollama-app}} ollama_app = flyte.app.AppEnvironment( name="ollama-app", image=image, args=["python", file_name, "--server"], port=PORT, resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU accelerates inference; omit to run small models on CPU disk="20Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), requires_auth=False, ) # {{/docs-fragment ollama-app}} # {{docs-fragment server}} def serve() -> None: """Start `ollama serve`, wait for it, pull the model, then block.""" # Bind to all interfaces so the platform can route to the server. server = subprocess.Popen( ["ollama", "serve"], env={**os.environ, "OLLAMA_HOST": f"0.0.0.0:{PORT}"}, ) # Wait for the server to accept connections. for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{PORT}/api/version", timeout=2) break except Exception: time.sleep(1) # Pull the model so the OpenAI-compatible endpoint can serve it. subprocess.run( ["ollama", "pull", MODEL], env={**os.environ, "OLLAMA_HOST": f"127.0.0.1:{PORT}"}, check=True, ) print(f"Ollama serving '{MODEL}' on port {PORT}") server.wait() # {{/docs-fragment server}} # {{docs-fragment deploy}} if __name__ == "__main__": if "--server" in sys.argv: serve() else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(ollama_app) print(f"Deployed Ollama app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/ollama/basic_ollama.py* The `--server` entrypoint binds Ollama to the app port, waits for it to be ready, and pulls the model so the OpenAI-compatible endpoint can serve it: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A simple Ollama serving app example. Unlike vLLM and SGLang, Ollama has no dedicated ``*AppEnvironment`` plugin, so it is served with the generic ``flyte.app.AppEnvironment``: an image that installs Ollama plus a small ``--server`` entrypoint that launches ``ollama serve`` and pulls the model on startup. Ollama exposes an OpenAI-compatible API, so clients call it exactly like the vLLM / SGLang apps. """ import os import subprocess import sys import time import urllib.request from pathlib import Path import flyte import flyte.app # Any tag from https://ollama.com/library. Small models run fine on CPU; larger # ones benefit from the GPU requested below. MODEL = "qwen3:0.6b" # Bind Ollama to the app port so the platform can route to it. PORT = 8080 file_name = Path(__file__).name # {{docs-fragment ollama-image}} # Install Ollama on top of the default Flyte base image. `install.sh` drops the # `ollama` binary into /usr/local/bin (no systemd is needed inside a container). image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("curl") .with_commands(["curl -fsSL https://ollama.com/install.sh | sh"]) ) # {{/docs-fragment ollama-image}} # {{docs-fragment ollama-app}} ollama_app = flyte.app.AppEnvironment( name="ollama-app", image=image, args=["python", file_name, "--server"], port=PORT, resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU accelerates inference; omit to run small models on CPU disk="20Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), requires_auth=False, ) # {{/docs-fragment ollama-app}} # {{docs-fragment server}} def serve() -> None: """Start `ollama serve`, wait for it, pull the model, then block.""" # Bind to all interfaces so the platform can route to the server. server = subprocess.Popen( ["ollama", "serve"], env={**os.environ, "OLLAMA_HOST": f"0.0.0.0:{PORT}"}, ) # Wait for the server to accept connections. for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{PORT}/api/version", timeout=2) break except Exception: time.sleep(1) # Pull the model so the OpenAI-compatible endpoint can serve it. subprocess.run( ["ollama", "pull", MODEL], env={**os.environ, "OLLAMA_HOST": f"127.0.0.1:{PORT}"}, check=True, ) print(f"Ollama serving '{MODEL}' on port {PORT}") server.wait() # {{/docs-fragment server}} # {{docs-fragment deploy}} if __name__ == "__main__": if "--server" in sys.argv: serve() else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(ollama_app) print(f"Deployed Ollama app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/ollama/basic_ollama.py* Deploy it with `flyte.serve`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # ] # /// """A simple Ollama serving app example. Unlike vLLM and SGLang, Ollama has no dedicated ``*AppEnvironment`` plugin, so it is served with the generic ``flyte.app.AppEnvironment``: an image that installs Ollama plus a small ``--server`` entrypoint that launches ``ollama serve`` and pulls the model on startup. Ollama exposes an OpenAI-compatible API, so clients call it exactly like the vLLM / SGLang apps. """ import os import subprocess import sys import time import urllib.request from pathlib import Path import flyte import flyte.app # Any tag from https://ollama.com/library. Small models run fine on CPU; larger # ones benefit from the GPU requested below. MODEL = "qwen3:0.6b" # Bind Ollama to the app port so the platform can route to it. PORT = 8080 file_name = Path(__file__).name # {{docs-fragment ollama-image}} # Install Ollama on top of the default Flyte base image. `install.sh` drops the # `ollama` binary into /usr/local/bin (no systemd is needed inside a container). image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("curl") .with_commands(["curl -fsSL https://ollama.com/install.sh | sh"]) ) # {{/docs-fragment ollama-image}} # {{docs-fragment ollama-app}} ollama_app = flyte.app.AppEnvironment( name="ollama-app", image=image, args=["python", file_name, "--server"], port=PORT, resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU accelerates inference; omit to run small models on CPU disk="20Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), requires_auth=False, ) # {{/docs-fragment ollama-app}} # {{docs-fragment server}} def serve() -> None: """Start `ollama serve`, wait for it, pull the model, then block.""" # Bind to all interfaces so the platform can route to the server. server = subprocess.Popen( ["ollama", "serve"], env={**os.environ, "OLLAMA_HOST": f"0.0.0.0:{PORT}"}, ) # Wait for the server to accept connections. for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{PORT}/api/version", timeout=2) break except Exception: time.sleep(1) # Pull the model so the OpenAI-compatible endpoint can serve it. subprocess.run( ["ollama", "pull", MODEL], env={**os.environ, "OLLAMA_HOST": f"127.0.0.1:{PORT}"}, check=True, ) print(f"Ollama serving '{MODEL}' on port {PORT}") server.wait() # {{/docs-fragment server}} # {{docs-fragment deploy}} if __name__ == "__main__": if "--server" in sys.argv: serve() else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(ollama_app) print(f"Deployed Ollama app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/ollama/basic_ollama.py* ## Choosing a model `MODEL` can be any tag from the [Ollama library](https://ollama.com/library) โ€” for example `qwen3:0.6b`, `llama3.2:1b`, or `gemma3:1b`. Larger models need more GPU memory and disk; size the `resources` accordingly. > [!NOTE] > Small models run comfortably on CPU. To run without a GPU, drop the `gpu` field from `resources`. A GPU is recommended for larger models or higher throughput. ## Using the OpenAI-compatible API Once deployed, the Ollama endpoint exposes an OpenAI-compatible API. Call it exactly like the vLLM or SGLang endpoints: CODE0 ## Chat UI with Streamlit To put a browser UI in front of the model, run Ollama internally and expose a [Streamlit](../../apps/native-app-integrations/streamlit-app.md) chat interface instead of the raw API. Only the Streamlit port is exposed; the browser talks to Streamlit, and Streamlit talks to Ollama over localhost: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # "openai", # ] # /// """An Ollama chat app fronted by a Streamlit UI. Ollama runs internally as an OpenAI-compatible server; a Streamlit chat interface fronts it. Only the Streamlit port is exposed to the platform โ€” the browser talks to Streamlit, and Streamlit talks to Ollama over localhost. """ import os import subprocess import sys import time import urllib.request from pathlib import Path import flyte import flyte.app MODEL = "qwen3:0.6b" OLLAMA_PORT = 11434 # internal only, not exposed APP_PORT = 8080 # Streamlit UI, exposed to the platform file_name = Path(__file__).name # {{docs-fragment app-env}} image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("curl") .with_commands(["curl -fsSL https://ollama.com/install.sh | sh"]) .with_pip_packages("streamlit==1.41.1", "openai") ) app_env = flyte.app.AppEnvironment( name="ollama-streamlit", image=image, args=["python", file_name, "--server"], port=APP_PORT, resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1", disk="20Gi"), scaling=flyte.app.Scaling(replicas=(0, 1), scaledown_after=300), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment ui}} def render_ui() -> None: """The Streamlit chat UI. Talks to the local Ollama OpenAI-compatible API.""" import streamlit as st from openai import OpenAI st.set_page_config(page_title="Ollama Chat", page_icon="๐Ÿฆ™") st.title("๐Ÿฆ™ Ollama Chat") client = OpenAI(base_url=f"http://127.0.0.1:{OLLAMA_PORT}/v1", api_key="ollama") if "messages" not in st.session_state: st.session_state.messages = [] for msg in st.session_state.messages: st.chat_message(msg["role"]).write(msg["content"]) if prompt := st.chat_input("Ask something..."): st.session_state.messages.append({"role": "user", "content": prompt}) st.chat_message("user").write(prompt) response = client.chat.completions.create( model=MODEL, messages=st.session_state.messages ) answer = response.choices[0].message.content st.session_state.messages.append({"role": "assistant", "content": answer}) st.chat_message("assistant").write(answer) # {{/docs-fragment ui}} # {{docs-fragment server}} def start_ollama() -> None: """Launch `ollama serve` in the background and pull the model.""" subprocess.Popen( ["ollama", "serve"], env={**os.environ, "OLLAMA_HOST": f"0.0.0.0:{OLLAMA_PORT}"}, ) for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{OLLAMA_PORT}/api/version", timeout=2) break except Exception: time.sleep(1) subprocess.run( ["ollama", "pull", MODEL], env={**os.environ, "OLLAMA_HOST": f"127.0.0.1:{OLLAMA_PORT}"}, check=True, ) # {{/docs-fragment server}} # {{docs-fragment deploy}} if __name__ == "__main__": if "--ui" in sys.argv: # Re-entry: Streamlit runs this file to render the UI. render_ui() elif "--server" in sys.argv: # Container entrypoint: start Ollama, then hand the port to Streamlit. start_ollama() subprocess.run( [ "streamlit", "run", file_name, "--server.port", str(APP_PORT), "--server.address", "0.0.0.0", "--", "--ui", ], check=True, ) else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(app_env) print(f"Deployed app: {app.url}") # {{/docs-fragment deploy}} CODE1 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # "openai", # ] # /// """An Ollama chat app fronted by a Streamlit UI. Ollama runs internally as an OpenAI-compatible server; a Streamlit chat interface fronts it. Only the Streamlit port is exposed to the platform โ€” the browser talks to Streamlit, and Streamlit talks to Ollama over localhost. """ import os import subprocess import sys import time import urllib.request from pathlib import Path import flyte import flyte.app MODEL = "qwen3:0.6b" OLLAMA_PORT = 11434 # internal only, not exposed APP_PORT = 8080 # Streamlit UI, exposed to the platform file_name = Path(__file__).name # {{docs-fragment app-env}} image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("curl") .with_commands(["curl -fsSL https://ollama.com/install.sh | sh"]) .with_pip_packages("streamlit==1.41.1", "openai") ) app_env = flyte.app.AppEnvironment( name="ollama-streamlit", image=image, args=["python", file_name, "--server"], port=APP_PORT, resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1", disk="20Gi"), scaling=flyte.app.Scaling(replicas=(0, 1), scaledown_after=300), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment ui}} def render_ui() -> None: """The Streamlit chat UI. Talks to the local Ollama OpenAI-compatible API.""" import streamlit as st from openai import OpenAI st.set_page_config(page_title="Ollama Chat", page_icon="๐Ÿฆ™") st.title("๐Ÿฆ™ Ollama Chat") client = OpenAI(base_url=f"http://127.0.0.1:{OLLAMA_PORT}/v1", api_key="ollama") if "messages" not in st.session_state: st.session_state.messages = [] for msg in st.session_state.messages: st.chat_message(msg["role"]).write(msg["content"]) if prompt := st.chat_input("Ask something..."): st.session_state.messages.append({"role": "user", "content": prompt}) st.chat_message("user").write(prompt) response = client.chat.completions.create( model=MODEL, messages=st.session_state.messages ) answer = response.choices[0].message.content st.session_state.messages.append({"role": "assistant", "content": answer}) st.chat_message("assistant").write(answer) # {{/docs-fragment ui}} # {{docs-fragment server}} def start_ollama() -> None: """Launch `ollama serve` in the background and pull the model.""" subprocess.Popen( ["ollama", "serve"], env={**os.environ, "OLLAMA_HOST": f"0.0.0.0:{OLLAMA_PORT}"}, ) for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{OLLAMA_PORT}/api/version", timeout=2) break except Exception: time.sleep(1) subprocess.run( ["ollama", "pull", MODEL], env={**os.environ, "OLLAMA_HOST": f"127.0.0.1:{OLLAMA_PORT}"}, check=True, ) # {{/docs-fragment server}} # {{docs-fragment deploy}} if __name__ == "__main__": if "--ui" in sys.argv: # Re-entry: Streamlit runs this file to render the UI. render_ui() elif "--server" in sys.argv: # Container entrypoint: start Ollama, then hand the port to Streamlit. start_ollama() subprocess.run( [ "streamlit", "run", file_name, "--server.port", str(APP_PORT), "--server.address", "0.0.0.0", "--", "--ui", ], check=True, ) else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(app_env) print(f"Deployed app: {app.url}") # {{/docs-fragment deploy}} CODE2 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # "openai", # ] # /// """An Ollama chat app fronted by a Streamlit UI. Ollama runs internally as an OpenAI-compatible server; a Streamlit chat interface fronts it. Only the Streamlit port is exposed to the platform โ€” the browser talks to Streamlit, and Streamlit talks to Ollama over localhost. """ import os import subprocess import sys import time import urllib.request from pathlib import Path import flyte import flyte.app MODEL = "qwen3:0.6b" OLLAMA_PORT = 11434 # internal only, not exposed APP_PORT = 8080 # Streamlit UI, exposed to the platform file_name = Path(__file__).name # {{docs-fragment app-env}} image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("curl") .with_commands(["curl -fsSL https://ollama.com/install.sh | sh"]) .with_pip_packages("streamlit==1.41.1", "openai") ) app_env = flyte.app.AppEnvironment( name="ollama-streamlit", image=image, args=["python", file_name, "--server"], port=APP_PORT, resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1", disk="20Gi"), scaling=flyte.app.Scaling(replicas=(0, 1), scaledown_after=300), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment ui}} def render_ui() -> None: """The Streamlit chat UI. Talks to the local Ollama OpenAI-compatible API.""" import streamlit as st from openai import OpenAI st.set_page_config(page_title="Ollama Chat", page_icon="๐Ÿฆ™") st.title("๐Ÿฆ™ Ollama Chat") client = OpenAI(base_url=f"http://127.0.0.1:{OLLAMA_PORT}/v1", api_key="ollama") if "messages" not in st.session_state: st.session_state.messages = [] for msg in st.session_state.messages: st.chat_message(msg["role"]).write(msg["content"]) if prompt := st.chat_input("Ask something..."): st.session_state.messages.append({"role": "user", "content": prompt}) st.chat_message("user").write(prompt) response = client.chat.completions.create( model=MODEL, messages=st.session_state.messages ) answer = response.choices[0].message.content st.session_state.messages.append({"role": "assistant", "content": answer}) st.chat_message("assistant").write(answer) # {{/docs-fragment ui}} # {{docs-fragment server}} def start_ollama() -> None: """Launch `ollama serve` in the background and pull the model.""" subprocess.Popen( ["ollama", "serve"], env={**os.environ, "OLLAMA_HOST": f"0.0.0.0:{OLLAMA_PORT}"}, ) for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{OLLAMA_PORT}/api/version", timeout=2) break except Exception: time.sleep(1) subprocess.run( ["ollama", "pull", MODEL], env={**os.environ, "OLLAMA_HOST": f"127.0.0.1:{OLLAMA_PORT}"}, check=True, ) # {{/docs-fragment server}} # {{docs-fragment deploy}} if __name__ == "__main__": if "--ui" in sys.argv: # Re-entry: Streamlit runs this file to render the UI. render_ui() elif "--server" in sys.argv: # Container entrypoint: start Ollama, then hand the port to Streamlit. start_ollama() subprocess.run( [ "streamlit", "run", file_name, "--server.port", str(APP_PORT), "--server.address", "0.0.0.0", "--", "--ui", ], check=True, ) else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(app_env) print(f"Deployed app: {app.url}") # {{/docs-fragment deploy}} CODE3 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "streamlit", # "openai", # ] # /// """An Ollama chat app fronted by a Streamlit UI. Ollama runs internally as an OpenAI-compatible server; a Streamlit chat interface fronts it. Only the Streamlit port is exposed to the platform โ€” the browser talks to Streamlit, and Streamlit talks to Ollama over localhost. """ import os import subprocess import sys import time import urllib.request from pathlib import Path import flyte import flyte.app MODEL = "qwen3:0.6b" OLLAMA_PORT = 11434 # internal only, not exposed APP_PORT = 8080 # Streamlit UI, exposed to the platform file_name = Path(__file__).name # {{docs-fragment app-env}} image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("curl") .with_commands(["curl -fsSL https://ollama.com/install.sh | sh"]) .with_pip_packages("streamlit==1.41.1", "openai") ) app_env = flyte.app.AppEnvironment( name="ollama-streamlit", image=image, args=["python", file_name, "--server"], port=APP_PORT, resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1", disk="20Gi"), scaling=flyte.app.Scaling(replicas=(0, 1), scaledown_after=300), requires_auth=False, ) # {{/docs-fragment app-env}} # {{docs-fragment ui}} def render_ui() -> None: """The Streamlit chat UI. Talks to the local Ollama OpenAI-compatible API.""" import streamlit as st from openai import OpenAI st.set_page_config(page_title="Ollama Chat", page_icon="๐Ÿฆ™") st.title("๐Ÿฆ™ Ollama Chat") client = OpenAI(base_url=f"http://127.0.0.1:{OLLAMA_PORT}/v1", api_key="ollama") if "messages" not in st.session_state: st.session_state.messages = [] for msg in st.session_state.messages: st.chat_message(msg["role"]).write(msg["content"]) if prompt := st.chat_input("Ask something..."): st.session_state.messages.append({"role": "user", "content": prompt}) st.chat_message("user").write(prompt) response = client.chat.completions.create( model=MODEL, messages=st.session_state.messages ) answer = response.choices[0].message.content st.session_state.messages.append({"role": "assistant", "content": answer}) st.chat_message("assistant").write(answer) # {{/docs-fragment ui}} # {{docs-fragment server}} def start_ollama() -> None: """Launch `ollama serve` in the background and pull the model.""" subprocess.Popen( ["ollama", "serve"], env={**os.environ, "OLLAMA_HOST": f"0.0.0.0:{OLLAMA_PORT}"}, ) for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{OLLAMA_PORT}/api/version", timeout=2) break except Exception: time.sleep(1) subprocess.run( ["ollama", "pull", MODEL], env={**os.environ, "OLLAMA_HOST": f"127.0.0.1:{OLLAMA_PORT}"}, check=True, ) # {{/docs-fragment server}} # {{docs-fragment deploy}} if __name__ == "__main__": if "--ui" in sys.argv: # Re-entry: Streamlit runs this file to render the UI. render_ui() elif "--server" in sys.argv: # Container entrypoint: start Ollama, then hand the port to Streamlit. start_ollama() subprocess.run( [ "streamlit", "run", file_name, "--server.port", str(APP_PORT), "--server.address", "0.0.0.0", "--", "--ui", ], check=True, ) else: flyte.init_from_config(root_dir=Path(__file__).parent) app = flyte.serve(app_env) print(f"Deployed app: {app.url}") # {{/docs-fragment deploy}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/ollama/ollama_streamlit.py* ## Authentication The generic `AppEnvironment` uses Union's platform-level authentication. Leave `requires_auth=True` (the default) to require an authenticated caller, or set `requires_auth=False` for a public endpoint. Ollama has no built-in API-key argument of its own, so prefer platform auth over exposing a public endpoint. For app-managed authentication (verifying a Bearer token yourself with a Flyte secret), see [Secret-based authentication](../../apps/build-apps/secret-based-authentication.md). ### Calling an authenticated app With `requires_auth=True` (the default), callers authenticate with a Union API key. Create one with the CLI: CODE4 This prints an `export FLYTE_API_KEY="..."` command. Pass the key in the `Authorization: Bearer` header when you invoke the endpoint: CODE5 When calling through the OpenAI client, pass the same key as `api_key` โ€” it becomes the `Authorization: Bearer` token (Ollama itself ignores the value). See [Using API keys with Union apps](../../authenticating.md#using-api-keys-with-union-apps) for details. ## Autoscaling Ollama endpoints work well with scale-to-zero, so an idle model server costs nothing: CODE6 Because the model is pulled at startup, a larger `scaledown_after` avoids re-pulling on every cold start. ## Best practices 1. **Right-size resources**: Match GPU memory and disk to the model. Small models run on CPU; drop the `gpu` field to save cost. 2. **Bake big models into the image**: For faster, more reproducible cold starts, `ollama pull` the model in a build command instead of at startup. 3. **Use scale-to-zero**: Set an appropriate `scaledown_after` to balance cost against cold-start latency. 4. **Prefer platform auth**: Ollama has no native API-key auth, so rely on `requires_auth` rather than exposing a public endpoint. 5. **Pick the right runtime**: Use Ollama for lightweight or local-style serving; reach for [vLLM](vllm.md) or [SGLang](sglang.md) for high-throughput production inference. ## Troubleshooting **Model pull fails or times out:** - Verify the `MODEL` tag exists in the [Ollama library](https://ollama.com/library) - Increase `disk` in `resources` for larger models - Review container logs for the `ollama pull` output **Server not reachable:** - Confirm Ollama is bound to `0.0.0.0` on the app port via `OLLAMA_HOST` - Check that the app `port` matches the port Ollama serves on **Slow first response:** - The model is pulled on startup; use a larger `scaledown_after` or bake the model into the image - Use a smaller model, or add a GPU for faster inference === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/self-hosted-endpoints/llamacpp === Serve quantized GGUF models with llama-server as a Flyte app, on GPU or CPU, behind an OpenAI-compatible API. # llama.cpp The `flyteplugins-llamacpp` plugin serves GGUF models with [llama.cpp](https://github.com/ggml-org/llama.cpp)'s `llama-server` as a Flyte app. `LlamaCppAppEnvironment` exposes an OpenAI-compatible API under `/v1` and the llama.cpp Web UI at `/`. Use it for quantized GGUF weights, for models larger than your GPU's VRAM, and for CPU-only serving. For high-throughput serving of full-precision weights, use **Inference > Self-hosted endpoints > vLLM** or **Inference > Self-hosted endpoints > SGLang**. ## Installation ```bash pip install flyteplugins-llamacpp ``` ## Serve a model from Hugging Face Set `model_hf_path` to a GGUF repo, with an optional quantization tag. `llama-server` downloads the weights when the app starts: ``` gemma_app = LlamaCppAppEnvironment( name="gemma-app", model_hf_path="ggml-org/gemma-3-4b-it-GGUF:Q4_K_M", model_id="gemma-3-4b-it", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L4:1", disk="50Gi"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/llamacpp/llamacpp_apps.py* Serve the app: ``` if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(gemma_app) print(f"Deployed llama.cpp app: {app.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/llamacpp/llamacpp_apps.py* ## Serve a model from object storage Set `model_path` to a directory of GGUF weights, or to one `.gguf` file: ``` llama_app = LlamaCppAppEnvironment( name="my-llm-app", # A directory of GGUF weights, or a direct path to one .gguf file. model_path="s3:///models/", model_id="my-model", resources=flyte.Resources(cpu="4", memory="32Gi", gpu="L40s:1", disk="100Gi"), scaling=flyte.app.Scaling(replicas=(0, 1), scaledown_after=300), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/llamacpp/llamacpp_apps.py* The weights are downloaded into the container, so set `disk` to fit them. If the directory holds a sharded model, the app selects the `-00001-of-` shard and `llama-server` finds the rest. If it holds several unrelated `.gguf` files, the app serves the first one by sorted path. `model_path` also accepts a `flyte.app.RunOutput`, to serve the output of a task. See **Inference > Deploy trained models**. It accepts a `flyte.app.ArtifactValue` too, to serve a **Artifacts > Use artifacts in apps**. Set `model_path` or `model_hf_path`, not both. `model_id` is required, and it's the name callers pass as `model`. ## Call the app Use any OpenAI client: ``` from openai import OpenAI client = OpenAI( base_url="https:///v1", api_key="", # A platform API key when the app has requires_auth=True ) response = client.chat.completions.create( model="gemma-3-4b-it", # The app's model_id messages=[{"role": "user", "content": "Hello, how are you?"}], ) print(response.choices[0].message.content) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/llamacpp/call_app.py* `llama-server` checks no key of its own unless you pass `--api-key` in `extra_args`. With `requires_auth=True` (the default), pass a Union API key as `api_key`. See **Inference > Self-hosted endpoints > Ollama > Authentication > Calling an authenticated app**. ## Choose an image The default image compiles `llama-server` from the tip of llama.cpp's default branch, with CUDA for L4 and L40S GPUs (compute capability 8.9), so two builds can produce different servers. The source build makes the first image build slow. To target other GPUs, or to pin a llama.cpp release for reproducible builds, use `build_llama_cpp_image()`: ``` fat_binary_app = LlamaCppAppEnvironment( name="fat-binary-app", model_hf_path="ggml-org/gemma-3-4b-it-GGUF:Q4_K_M", model_id="gemma-3-4b-it", image=build_llama_cpp_image( cuda_arch="80;86;89;90", # A100, A10, L4 and L40S, H100 ref="b6148", # A llama.cpp release tag ), resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L4:1", disk="50Gi"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/llamacpp/llamacpp_apps.py* To serve small models without a GPU, build a CPU-only image: ``` cpu_app = LlamaCppAppEnvironment( name="cpu-app", model_hf_path="ggml-org/Qwen3-0.6B-GGUF:Q8_0", model_id="qwen3-0.6b", image=build_llama_cpp_image(cuda=False), resources=flyte.Resources(cpu="4", memory="8Gi", disk="10Gi"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/llamacpp/llamacpp_apps.py* > [!WARNING] Match the image to the GPU > The default image targets only compute capability 8.9. On another GPU, such as an A100 or H100, set `cuda_arch` to include it. ## Pass arguments to llama-server `extra_args` is appended to the `llama-server` command, as a string or a list: ``` tuned_app = LlamaCppAppEnvironment( name="tuned-app", model_hf_path="ggml-org/gemma-3-4b-it-GGUF:Q4_K_M", model_id="gemma-3-4b-it", extra_args="--ctx-size 32768 --parallel 4 --jinja", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L4:1", disk="50Gi"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/llamacpp/llamacpp_apps.py* | Flag | Purpose | |---|---| | `--ctx-size` | Context length | | `--parallel` | Concurrent request slots | | `--jinja` | Use the model's chat template, which tool calling needs | | `--n-gpu-layers` | Limit GPU offload for a model larger than VRAM | | `--cache-type-k`, `--cache-type-v` | Quantize the KV cache | | `--flash-attn` | Enable flash attention | Values with spaces or JSON are quoted for you. An argument of the form `$MY_VAR` isn't quoted, and Flyte expands it from the app's environment. See the [llama-server docs](https://github.com/ggml-org/llama.cpp/tree/master/tools/server) for all flags. ## Use speculative decoding Set `draft_model_path` or `draft_model_hf_path` to a small draft GGUF, and tune it with `extra_args`: ``` speculative_app = LlamaCppAppEnvironment( name="speculative-app", model_path="s3:///models/qwen3-32b-gguf", model_id="qwen3-32b", draft_model_hf_path="ggml-org/Qwen3-0.6B-GGUF:Q8_0", extra_args="--draft-max 16 --draft-min 1 --gpu-layers-draft 99", resources=flyte.Resources(cpu="8", memory="64Gi", gpu="L40s:1", disk="120Gi"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/llamacpp/llamacpp_apps.py* ## Limitations `LlamaCppAppEnvironment` sets its own command and parameters. Passing `args` or `parameters` raises a `ValueError`, so use `extra_args` and `model_path` instead. ## API reference See the [llama.cpp API reference](../../../api-reference/integrations/llamacpp/_index). === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/self-hosted-endpoints/fastapi === Serve any Python model behind a custom REST API on your own compute with FastAPI, for models and request shapes an LLM server doesn't cover. # FastAPI [FastAPI](https://fastapi.tiangolo.com/) gives you full control over an endpoint's routes, request schema, and pre- and post-processing. Use it for models an LLM server doesn't cover, such as classifiers, embedding models, and scikit-learn or PyTorch models, or when an LLM needs custom logic around it. Flyte's **Apps > Native app integrations > FastAPI app** runs a FastAPI app with Uvicorn on your compute, so you only write the app. Unlike the vLLM, SGLang, Ollama, and llama.cpp endpoints, this endpoint doesn't expose the OpenAI API unless you implement those routes yourself. ## Define the API This example serves a sentiment classifier from Hugging Face. The `lifespan` handler loads the model once per replica, before the app accepts traffic: ``` from contextlib import asynccontextmanager import flyte import flyte.app from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment from pydantic import BaseModel from transformers import pipeline MODEL = "distilbert-base-uncased-finetuned-sst-2-english" state = {} @asynccontextmanager async def lifespan(app: FastAPI): # Load the model once per replica, before the app accepts traffic. state["classifier"] = pipeline("text-classification", model=MODEL) yield app = FastAPI(title="Sentiment endpoint", lifespan=lifespan) class PredictRequest(BaseModel): text: str class PredictResponse(BaseModel): label: str score: float @app.post("/predict") def predict(request: PredictRequest) -> PredictResponse: return PredictResponse(**state["classifier"](request.text)[0]) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/fastapi_endpoint.py* `predict` is a plain `def`, so FastAPI runs it in a thread pool and the blocking model call doesn't hold up the event loop. ## Define the app environment Pass the FastAPI app to the environment, along with the image and the resources the model needs: ``` app_env = FastAPIAppEnvironment( name="fastapi-endpoint", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "torch", "transformers" ), resources=flyte.Resources(cpu="2", memory="4Gi", disk="10Gi"), scaling=flyte.app.Scaling(replicas=(0, 2), scaledown_after=300), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/fastapi_endpoint.py* To run on a GPU, add a `gpu` value to `resources` and pass `device=0` to `pipeline`. ## Deploy ``` if __name__ == "__main__": flyte.init_from_config(root_dir=Path(__file__).parent) deployment = flyte.serve(app_env) print(f"Deployed: {deployment.url}") print(f"API docs: {deployment.url}/docs") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/fastapi_endpoint.py* ## Call the endpoint With `requires_auth=True`, the default, callers authenticate with an API key: ```bash curl -X POST "https://your-app-url/predict" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $FLYTE_API_KEY" \ -d '{"text": "I love this"}' ``` FastAPI also generates interactive API docs at `/docs`. For app-managed authentication, see **Apps > Build apps > Secret-based authentication**. ## Next steps - Load your own weights instead of a Hugging Face model: **Inference > Deploy trained models** - Avoid downloading weights on every cold start: **Inference > Prefetching models** - Tune replicas and scale-to-zero: **Apps > Configure apps > /// script** - Use a dedicated serving framework: **Inference > Self-hosted endpoints > Other frameworks** === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/self-hosted-endpoints/other-frameworks === Serve models with Ray Serve, LitServe, BentoML, or any other ML serving framework by running its server in a generic AppEnvironment. # Other frameworks Any framework that runs an HTTP server can serve a model on your compute. Flyte doesn't need a dedicated integration: a generic **Apps > Build apps > Single-script apps** runs the server and routes traffic to it. Every framework follows the same three steps: 1. **Install the framework in the image**, with `flyte.Image` and `with_pip_packages`. 2. **Start the server with `args`**, using either the framework's CLI or a Python entrypoint. 3. **Bind the server to `0.0.0.0` on the app's `port`**, so the platform can reach it. The default port is `8080`. The examples below serve the same sentiment classifier, so you can compare the frameworks directly. | Framework | Good fit for | |---|---| | **Inference > Self-hosted endpoints > Other frameworks > LitServe** | A small `LitAPI` class with built-in batching and GPU handling | | **Inference > Self-hosted endpoints > Other frameworks > Ray Serve** | Multiple replicas or multi-model pipelines inside one app, using Ray's programming model | | **Inference > Self-hosted endpoints > Other frameworks > BentoML** | Typed service classes with generated API schemas, or an existing Bento service | | **Inference > Self-hosted endpoints > Other frameworks > Any other server** | A framework you already use | ## LitServe [LitServe](https://lightning.ai/docs/litserve) serves a `LitAPI` class. Start it through a `--server` entrypoint in the script: ``` app_env = flyte.app.AppEnvironment( name="litserve-endpoint", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "litserve", "torch", "transformers" ), args=["python", file_name, "--server"], port=PORT, resources=flyte.Resources(cpu="2", memory="4Gi", disk="10Gi"), scaling=flyte.app.Scaling(replicas=(0, 2), scaledown_after=300), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/litserve_endpoint.py* The `--server` entrypoint starts LitServe on the app port: ``` # LitServe pickles the API class into its worker processes, so define it at module level. class Classifier(ls.LitAPI): def setup(self, device): self.classifier = pipeline("text-classification", model=MODEL, device=device) def decode_request(self, request): return request["text"] def predict(self, text): return self.classifier(text)[0] def serve() -> None: server = ls.LitServer(Classifier(), accelerator="auto") server.run(host="0.0.0.0", port=PORT) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/litserve_endpoint.py* Deploy with `flyte.serve`, and run the server when the container passes `--server`: ``` if __name__ == "__main__": if "--server" in sys.argv: serve() else: flyte.init_from_config(root_dir=Path(__file__).parent) deployment = flyte.serve(app_env) print(f"Deployed: {deployment.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/litserve_endpoint.py* LitServe serves `POST /predict` by default. ## Ray Serve [Ray Serve](https://docs.ray.io/en/latest/serve/) runs deployments on a Ray cluster. In this pattern, Ray runs inside a single app replica, so size `resources` for all of the Ray Serve replicas plus Ray's own processes: ``` app_env = flyte.app.AppEnvironment( name="ray-serve-endpoint", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "ray[serve]", "torch", "transformers" ), args=["python", file_name, "--server"], port=PORT, resources=flyte.Resources(cpu="4", memory="8Gi", disk="10Gi"), scaling=flyte.app.Scaling(replicas=(0, 1), scaledown_after=300), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/ray_serve_endpoint.py* `serve.start` binds the Ray Serve proxy to the app port. `serve.run` returns once the deployment is ready, so the entrypoint then blocks to keep the container running: ``` def serve() -> None: from ray import serve as ray_serve from starlette.requests import Request from transformers import pipeline @ray_serve.deployment(num_replicas=2, ray_actor_options={"num_cpus": 1}) class Classifier: def __init__(self): self.classifier = pipeline("text-classification", model=MODEL) async def __call__(self, request: Request) -> dict: body = await request.json() return self.classifier(body["text"])[0] # Bind the Ray Serve proxy to the app port on all interfaces. ray_serve.start(http_options={"host": "0.0.0.0", "port": PORT}) ray_serve.run(Classifier.bind(), route_prefix="/predict") # `serve.run` returns once the deployment is ready. Keep the container alive. while True: time.sleep(60) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/ray_serve_endpoint.py* Keep the app at one replica, as in `replicas=(0, 1)`, and scale with `num_replicas` in the Ray deployment. Each app replica would otherwise start its own independent Ray instance. ## BentoML [BentoML](https://docs.bentoml.com/) defines a service as a class. Each `@bentoml.api` method becomes a `POST` route named after the method: CODE4 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/bentoml_endpoint.py* BentoML has its own CLI, so `args` can start the server directly: ``` app_env = flyte.app.AppEnvironment( name="bentoml-endpoint", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "bentoml", "torch", "transformers" ), # `bentoml serve` imports the service from this module. args=["bentoml", "serve", f"{Path(__file__).stem}:Classifier", "--host", "0.0.0.0", "--port", str(PORT)], port=PORT, resources=flyte.Resources(cpu="2", memory="4Gi", disk="10Gi"), scaling=flyte.app.Scaling(replicas=(0, 2), scaledown_after=300), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/self-hosted-endpoints/bentoml_endpoint.py* ## Any other server The same pattern works for other servers. Point `args` at the command that starts the server and make sure it listens on `0.0.0.0` and the app's `port`: | Framework | What it serves | Notes | |---|---|---| | [MLServer](https://mlserver.readthedocs.io/) | Scikit-learn, XGBoost, LightGBM, and MLflow models | Started with `mlserver start`. Set the port in `settings.json`. | | [MLflow](https://mlflow.org/docs/latest/) | Models in the MLflow format | Started with `mlflow models serve`, which takes `--host` and `--port`. | | [Gradio](https://www.gradio.app/) | A browser demo with an HTTP API | Set `GRADIO_SERVER_NAME` to `0.0.0.0` and `GRADIO_SERVER_PORT` to the app port. | > [!NOTE] > [TorchServe](https://docs.pytorch.org/serve/) is no longer maintained, and its repository was archived in August 2025. For new PyTorch endpoints, use one of the frameworks on this page or a [FastAPI endpoint](fastapi.md). For an LLM, start with the [vLLM](vllm.md), [SGLang](sglang.md), [Ollama](ollama.md), or [llama.cpp](llamacpp.md) endpoints. ## Deploy, call, and scale All of these run as ordinary apps, so the rest of the app documentation applies: - **Authentication**: `requires_auth=True` is the default and sits in front of the framework's own server. See [Secret-based authentication](../../apps/build-apps/secret-based-authentication.md) for app-managed auth. - **Scaling**: See [Autoscaling apps](../../apps/configure-apps/auto-scaling-apps.md). - **Weights**: See [Prefetching models](../prefetching-models.md) and [Deploy trained models](../deploy-trained-models.md). ## Troubleshooting **The app never becomes ready:** - Confirm the server binds `0.0.0.0` rather than `localhost`. Many frameworks default to `localhost` or use their own default port, such as 3000 for BentoML and 8000 for Ray Serve. - Check that the server's port matches `port` on the `AppEnvironment`. - Avoid the reserved ports 8012, 8022, 8112, and 9090. **The server starts, then the container exits:** - The `args` command must stay in the foreground. If the entrypoint only starts a background server, as Ray Serve's does, block afterward. **Slow first response:** - The model loads at startup, so a replica scaling up from zero takes that long to respond. Raise `scaledown_after`, keep a minimum replica, or **Inference > Prefetching models**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/prefetching-models === Download and shard a HuggingFace model before an inference app starts. # Prefetching models Prefetching allows you to download and prepare HuggingFace models (including sharding for multi-GPU inference) before deploying **Inference > Self-hosted endpoints > vLLM** or **Inference > Self-hosted endpoints > SGLang** apps. This speeds up deployment and ensures models are ready when your app starts. ## Why prefetch? Prefetching models provides several benefits: - **Faster deployment**: Models are pre-downloaded, so apps start faster - **Reproducibility**: Models are versioned and stored in Flyte's object store - **Sharding support**: Pre-shard models for multi-GPU tensor parallelism - **Cost efficiency**: Download once, use many times - **Offline support**: Models are cached in your storage backend ## Basic prefetch ### Using Python SDK ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b49", # ] # /// """Prefetch examples for the prefetching-models.md documentation.""" import flyte from flyte.prefetch import ShardConfig, VLLMShardArgs from flyteplugins.vllm import VLLMAppEnvironment # {{docs-fragment basic-prefetch}} # Prefetch a HuggingFace model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") # Wait for prefetch to complete run.wait() # Get the model path model_path = run.outputs()[0].path print(f"Model prefetched to: {model_path}") # {{/docs-fragment basic-prefetch}} # {{docs-fragment using-prefetched-models}} # Prefetch the model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_path=flyte.app.RunOutput( type="directory", run_name=run.name, ), model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), stream_model=True, ) app = flyte.serve(vllm_app) # {{/docs-fragment using-prefetched-models}} # {{docs-fragment custom-artifact-name}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b-model", # Custom name for the stored model ) # {{/docs-fragment custom-artifact-name}} # {{docs-fragment hf-token}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-7b-hf", hf_token_key="HF_TOKEN", # Name of Flyte secret containing HF token ) # {{/docs-fragment hf-token}} # {{docs-fragment with-resources}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", cpu="4", mem="16Gi", ephemeral_storage="100Gi", ) # {{/docs-fragment with-resources}} # {{docs-fragment vllm-sharding}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4"), shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), hf_token_key="HF_TOKEN", ) run.wait() # {{/docs-fragment vllm-sharding}} # {{docs-fragment using-sharded-models}} # Use in vLLM app vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # Match the number of GPUs used for sharding ), extra_args=[ "--tensor-parallel-size", "4", # Match sharding config ], ) if __name__ == "__main__": # Prefetch with sharding run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", accelerator="L40s:4", shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs(tensor_parallel_size=4), ), ) run.wait() flyte.serve( vllm_app.clone_with( name=vllm_app.name, # override the model path to use the prefetched model model_path=flyte.app.RunOutput(type="directory", run_name=run.name), # set the hf_model_path to None hf_model_path=None, # stream the model from flyte object store directly to the GPU stream_model=True, ) ) # {{/docs-fragment using-sharded-models}} # {{docs-fragment complete-example}} # define the app environment vllm_app = VLLMAppEnvironment( name="qwen-serving-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=600, ), requires_auth=False, ) if __name__ == "__main__": # prefetch the model print("Prefetching model...") run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b", cpu="4", mem="16Gi", ephemeral_storage="50Gi", ) # wait for completion print("Waiting for prefetch to complete...") run.wait() print(f"Model prefetched: {run.outputs()[0].path}") # deploy the app print("Deploying app...") flyte.init_from_config() app = flyte.serve( vllm_app.clone_with( name=vllm_app.name, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), hf_model_path=None, stream_model=True, ) ) print(f"App deployed: {app.url}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/prefetch_examples.py* ### Using CLI ```bash flyte prefetch hf-model Qwen/Qwen3-0.6B ``` Wait for completion: ```bash flyte prefetch hf-model Qwen/Qwen3-0.6B --wait ``` ## Using prefetched models Use the prefetched model in your vLLM or SGLang endpoint: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b49", # ] # /// """Prefetch examples for the prefetching-models.md documentation.""" import flyte from flyte.prefetch import ShardConfig, VLLMShardArgs from flyteplugins.vllm import VLLMAppEnvironment # {{docs-fragment basic-prefetch}} # Prefetch a HuggingFace model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") # Wait for prefetch to complete run.wait() # Get the model path model_path = run.outputs()[0].path print(f"Model prefetched to: {model_path}") # {{/docs-fragment basic-prefetch}} # {{docs-fragment using-prefetched-models}} # Prefetch the model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_path=flyte.app.RunOutput( type="directory", run_name=run.name, ), model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), stream_model=True, ) app = flyte.serve(vllm_app) # {{/docs-fragment using-prefetched-models}} # {{docs-fragment custom-artifact-name}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b-model", # Custom name for the stored model ) # {{/docs-fragment custom-artifact-name}} # {{docs-fragment hf-token}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-7b-hf", hf_token_key="HF_TOKEN", # Name of Flyte secret containing HF token ) # {{/docs-fragment hf-token}} # {{docs-fragment with-resources}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", cpu="4", mem="16Gi", ephemeral_storage="100Gi", ) # {{/docs-fragment with-resources}} # {{docs-fragment vllm-sharding}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4"), shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), hf_token_key="HF_TOKEN", ) run.wait() # {{/docs-fragment vllm-sharding}} # {{docs-fragment using-sharded-models}} # Use in vLLM app vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # Match the number of GPUs used for sharding ), extra_args=[ "--tensor-parallel-size", "4", # Match sharding config ], ) if __name__ == "__main__": # Prefetch with sharding run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", accelerator="L40s:4", shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs(tensor_parallel_size=4), ), ) run.wait() flyte.serve( vllm_app.clone_with( name=vllm_app.name, # override the model path to use the prefetched model model_path=flyte.app.RunOutput(type="directory", run_name=run.name), # set the hf_model_path to None hf_model_path=None, # stream the model from flyte object store directly to the GPU stream_model=True, ) ) # {{/docs-fragment using-sharded-models}} # {{docs-fragment complete-example}} # define the app environment vllm_app = VLLMAppEnvironment( name="qwen-serving-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=600, ), requires_auth=False, ) if __name__ == "__main__": # prefetch the model print("Prefetching model...") run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b", cpu="4", mem="16Gi", ephemeral_storage="50Gi", ) # wait for completion print("Waiting for prefetch to complete...") run.wait() print(f"Model prefetched: {run.outputs()[0].path}") # deploy the app print("Deploying app...") flyte.init_from_config() app = flyte.serve( vllm_app.clone_with( name=vllm_app.name, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), hf_model_path=None, stream_model=True, ) ) print(f"App deployed: {app.url}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/prefetch_examples.py* > [!TIP] > You can also use prefetched models as parameters to your generic `[[AppEnvironment]]`s or `FastAPIAppEnvironment`s. ## Prefetch options ### Custom artifact name ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b49", # ] # /// """Prefetch examples for the prefetching-models.md documentation.""" import flyte from flyte.prefetch import ShardConfig, VLLMShardArgs from flyteplugins.vllm import VLLMAppEnvironment # {{docs-fragment basic-prefetch}} # Prefetch a HuggingFace model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") # Wait for prefetch to complete run.wait() # Get the model path model_path = run.outputs()[0].path print(f"Model prefetched to: {model_path}") # {{/docs-fragment basic-prefetch}} # {{docs-fragment using-prefetched-models}} # Prefetch the model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_path=flyte.app.RunOutput( type="directory", run_name=run.name, ), model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), stream_model=True, ) app = flyte.serve(vllm_app) # {{/docs-fragment using-prefetched-models}} # {{docs-fragment custom-artifact-name}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b-model", # Custom name for the stored model ) # {{/docs-fragment custom-artifact-name}} # {{docs-fragment hf-token}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-7b-hf", hf_token_key="HF_TOKEN", # Name of Flyte secret containing HF token ) # {{/docs-fragment hf-token}} # {{docs-fragment with-resources}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", cpu="4", mem="16Gi", ephemeral_storage="100Gi", ) # {{/docs-fragment with-resources}} # {{docs-fragment vllm-sharding}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4"), shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), hf_token_key="HF_TOKEN", ) run.wait() # {{/docs-fragment vllm-sharding}} # {{docs-fragment using-sharded-models}} # Use in vLLM app vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # Match the number of GPUs used for sharding ), extra_args=[ "--tensor-parallel-size", "4", # Match sharding config ], ) if __name__ == "__main__": # Prefetch with sharding run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", accelerator="L40s:4", shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs(tensor_parallel_size=4), ), ) run.wait() flyte.serve( vllm_app.clone_with( name=vllm_app.name, # override the model path to use the prefetched model model_path=flyte.app.RunOutput(type="directory", run_name=run.name), # set the hf_model_path to None hf_model_path=None, # stream the model from flyte object store directly to the GPU stream_model=True, ) ) # {{/docs-fragment using-sharded-models}} # {{docs-fragment complete-example}} # define the app environment vllm_app = VLLMAppEnvironment( name="qwen-serving-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=600, ), requires_auth=False, ) if __name__ == "__main__": # prefetch the model print("Prefetching model...") run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b", cpu="4", mem="16Gi", ephemeral_storage="50Gi", ) # wait for completion print("Waiting for prefetch to complete...") run.wait() print(f"Model prefetched: {run.outputs()[0].path}") # deploy the app print("Deploying app...") flyte.init_from_config() app = flyte.serve( vllm_app.clone_with( name=vllm_app.name, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), hf_model_path=None, stream_model=True, ) ) print(f"App deployed: {app.url}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/prefetch_examples.py* ### With HuggingFace token If the model requires authentication: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b49", # ] # /// """Prefetch examples for the prefetching-models.md documentation.""" import flyte from flyte.prefetch import ShardConfig, VLLMShardArgs from flyteplugins.vllm import VLLMAppEnvironment # {{docs-fragment basic-prefetch}} # Prefetch a HuggingFace model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") # Wait for prefetch to complete run.wait() # Get the model path model_path = run.outputs()[0].path print(f"Model prefetched to: {model_path}") # {{/docs-fragment basic-prefetch}} # {{docs-fragment using-prefetched-models}} # Prefetch the model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_path=flyte.app.RunOutput( type="directory", run_name=run.name, ), model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), stream_model=True, ) app = flyte.serve(vllm_app) # {{/docs-fragment using-prefetched-models}} # {{docs-fragment custom-artifact-name}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b-model", # Custom name for the stored model ) # {{/docs-fragment custom-artifact-name}} # {{docs-fragment hf-token}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-7b-hf", hf_token_key="HF_TOKEN", # Name of Flyte secret containing HF token ) # {{/docs-fragment hf-token}} # {{docs-fragment with-resources}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", cpu="4", mem="16Gi", ephemeral_storage="100Gi", ) # {{/docs-fragment with-resources}} # {{docs-fragment vllm-sharding}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4"), shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), hf_token_key="HF_TOKEN", ) run.wait() # {{/docs-fragment vllm-sharding}} # {{docs-fragment using-sharded-models}} # Use in vLLM app vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # Match the number of GPUs used for sharding ), extra_args=[ "--tensor-parallel-size", "4", # Match sharding config ], ) if __name__ == "__main__": # Prefetch with sharding run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", accelerator="L40s:4", shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs(tensor_parallel_size=4), ), ) run.wait() flyte.serve( vllm_app.clone_with( name=vllm_app.name, # override the model path to use the prefetched model model_path=flyte.app.RunOutput(type="directory", run_name=run.name), # set the hf_model_path to None hf_model_path=None, # stream the model from flyte object store directly to the GPU stream_model=True, ) ) # {{/docs-fragment using-sharded-models}} # {{docs-fragment complete-example}} # define the app environment vllm_app = VLLMAppEnvironment( name="qwen-serving-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=600, ), requires_auth=False, ) if __name__ == "__main__": # prefetch the model print("Prefetching model...") run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b", cpu="4", mem="16Gi", ephemeral_storage="50Gi", ) # wait for completion print("Waiting for prefetch to complete...") run.wait() print(f"Model prefetched: {run.outputs()[0].path}") # deploy the app print("Deploying app...") flyte.init_from_config() app = flyte.serve( vllm_app.clone_with( name=vllm_app.name, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), hf_model_path=None, stream_model=True, ) ) print(f"App deployed: {app.url}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/prefetch_examples.py* The default value for `hf_token_key` is `HF_TOKEN`, where `HF_TOKEN` is the name of the Flyte secret containing your HuggingFace token. If this secret doesn't exist, you can create a secret using the **Tasks > Configure tasks > Secrets**. Public models need no token at all. Pass `hf_token_key=None` to prefetch anonymously, and no secret is attached to the prefetch task. ### With resources By default, the prefetch task uses minimal resources (2 CPUs, 8GB of memory, 50Gi of disk storage), using filestreaming logic to move the model weights from HuggingFace to your storage backend directly. In some cases, the HuggingFace model may not support filestreaming, in which case the prefetch task will fallback to downloading the model weights to the task pod's disk storage first, then uploading them to your storage backend. In this case, you can specify custom resources for the prefetch task to override the default resources. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b49", # ] # /// """Prefetch examples for the prefetching-models.md documentation.""" import flyte from flyte.prefetch import ShardConfig, VLLMShardArgs from flyteplugins.vllm import VLLMAppEnvironment # {{docs-fragment basic-prefetch}} # Prefetch a HuggingFace model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") # Wait for prefetch to complete run.wait() # Get the model path model_path = run.outputs()[0].path print(f"Model prefetched to: {model_path}") # {{/docs-fragment basic-prefetch}} # {{docs-fragment using-prefetched-models}} # Prefetch the model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_path=flyte.app.RunOutput( type="directory", run_name=run.name, ), model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), stream_model=True, ) app = flyte.serve(vllm_app) # {{/docs-fragment using-prefetched-models}} # {{docs-fragment custom-artifact-name}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b-model", # Custom name for the stored model ) # {{/docs-fragment custom-artifact-name}} # {{docs-fragment hf-token}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-7b-hf", hf_token_key="HF_TOKEN", # Name of Flyte secret containing HF token ) # {{/docs-fragment hf-token}} # {{docs-fragment with-resources}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", cpu="4", mem="16Gi", ephemeral_storage="100Gi", ) # {{/docs-fragment with-resources}} # {{docs-fragment vllm-sharding}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4"), shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), hf_token_key="HF_TOKEN", ) run.wait() # {{/docs-fragment vllm-sharding}} # {{docs-fragment using-sharded-models}} # Use in vLLM app vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # Match the number of GPUs used for sharding ), extra_args=[ "--tensor-parallel-size", "4", # Match sharding config ], ) if __name__ == "__main__": # Prefetch with sharding run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", accelerator="L40s:4", shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs(tensor_parallel_size=4), ), ) run.wait() flyte.serve( vllm_app.clone_with( name=vllm_app.name, # override the model path to use the prefetched model model_path=flyte.app.RunOutput(type="directory", run_name=run.name), # set the hf_model_path to None hf_model_path=None, # stream the model from flyte object store directly to the GPU stream_model=True, ) ) # {{/docs-fragment using-sharded-models}} # {{docs-fragment complete-example}} # define the app environment vllm_app = VLLMAppEnvironment( name="qwen-serving-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=600, ), requires_auth=False, ) if __name__ == "__main__": # prefetch the model print("Prefetching model...") run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b", cpu="4", mem="16Gi", ephemeral_storage="50Gi", ) # wait for completion print("Waiting for prefetch to complete...") run.wait() print(f"Model prefetched: {run.outputs()[0].path}") # deploy the app print("Deploying app...") flyte.init_from_config() app = flyte.serve( vllm_app.clone_with( name=vllm_app.name, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), hf_model_path=None, stream_model=True, ) ) print(f"App deployed: {app.url}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/prefetch_examples.py* ## Sharding models for multi-GPU ### vLLM sharding Shard a model for tensor parallelism: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b49", # ] # /// """Prefetch examples for the prefetching-models.md documentation.""" import flyte from flyte.prefetch import ShardConfig, VLLMShardArgs from flyteplugins.vllm import VLLMAppEnvironment # {{docs-fragment basic-prefetch}} # Prefetch a HuggingFace model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") # Wait for prefetch to complete run.wait() # Get the model path model_path = run.outputs()[0].path print(f"Model prefetched to: {model_path}") # {{/docs-fragment basic-prefetch}} # {{docs-fragment using-prefetched-models}} # Prefetch the model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_path=flyte.app.RunOutput( type="directory", run_name=run.name, ), model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), stream_model=True, ) app = flyte.serve(vllm_app) # {{/docs-fragment using-prefetched-models}} # {{docs-fragment custom-artifact-name}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b-model", # Custom name for the stored model ) # {{/docs-fragment custom-artifact-name}} # {{docs-fragment hf-token}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-7b-hf", hf_token_key="HF_TOKEN", # Name of Flyte secret containing HF token ) # {{/docs-fragment hf-token}} # {{docs-fragment with-resources}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", cpu="4", mem="16Gi", ephemeral_storage="100Gi", ) # {{/docs-fragment with-resources}} # {{docs-fragment vllm-sharding}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4"), shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), hf_token_key="HF_TOKEN", ) run.wait() # {{/docs-fragment vllm-sharding}} # {{docs-fragment using-sharded-models}} # Use in vLLM app vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # Match the number of GPUs used for sharding ), extra_args=[ "--tensor-parallel-size", "4", # Match sharding config ], ) if __name__ == "__main__": # Prefetch with sharding run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", accelerator="L40s:4", shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs(tensor_parallel_size=4), ), ) run.wait() flyte.serve( vllm_app.clone_with( name=vllm_app.name, # override the model path to use the prefetched model model_path=flyte.app.RunOutput(type="directory", run_name=run.name), # set the hf_model_path to None hf_model_path=None, # stream the model from flyte object store directly to the GPU stream_model=True, ) ) # {{/docs-fragment using-sharded-models}} # {{docs-fragment complete-example}} # define the app environment vllm_app = VLLMAppEnvironment( name="qwen-serving-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=600, ), requires_auth=False, ) if __name__ == "__main__": # prefetch the model print("Prefetching model...") run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b", cpu="4", mem="16Gi", ephemeral_storage="50Gi", ) # wait for completion print("Waiting for prefetch to complete...") run.wait() print(f"Model prefetched: {run.outputs()[0].path}") # deploy the app print("Deploying app...") flyte.init_from_config() app = flyte.serve( vllm_app.clone_with( name=vllm_app.name, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), hf_model_path=None, stream_model=True, ) ) print(f"App deployed: {app.url}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/prefetch_examples.py* Currently, the `flyte.prefetch.hf_model` function only supports sharding models using the `vllm` engine. Once sharded, these models can be loaded with other frameworks such as `transformers`, `torch`, or `sglang`. ### Using shard config via CLI You can also use a YAML file for sharding configuration to use with the `flyte prefetch hf-model` CLI command: ```yaml # shard_config.yaml engine: vllm args: tensor_parallel_size: 8 dtype: auto trust_remote_code: true ``` Then run the CLI command: ```bash flyte prefetch hf-model meta-llama/Llama-2-70b-hf \ --shard-config shard_config.yaml \ --gpu L40s:8 \ --hf-token-key HF_TOKEN ``` ## Using prefetched sharded models After prefetching and sharding, serve the model in your app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b49", # ] # /// """Prefetch examples for the prefetching-models.md documentation.""" import flyte from flyte.prefetch import ShardConfig, VLLMShardArgs from flyteplugins.vllm import VLLMAppEnvironment # {{docs-fragment basic-prefetch}} # Prefetch a HuggingFace model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") # Wait for prefetch to complete run.wait() # Get the model path model_path = run.outputs()[0].path print(f"Model prefetched to: {model_path}") # {{/docs-fragment basic-prefetch}} # {{docs-fragment using-prefetched-models}} # Prefetch the model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_path=flyte.app.RunOutput( type="directory", run_name=run.name, ), model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), stream_model=True, ) app = flyte.serve(vllm_app) # {{/docs-fragment using-prefetched-models}} # {{docs-fragment custom-artifact-name}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b-model", # Custom name for the stored model ) # {{/docs-fragment custom-artifact-name}} # {{docs-fragment hf-token}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-7b-hf", hf_token_key="HF_TOKEN", # Name of Flyte secret containing HF token ) # {{/docs-fragment hf-token}} # {{docs-fragment with-resources}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", cpu="4", mem="16Gi", ephemeral_storage="100Gi", ) # {{/docs-fragment with-resources}} # {{docs-fragment vllm-sharding}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4"), shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), hf_token_key="HF_TOKEN", ) run.wait() # {{/docs-fragment vllm-sharding}} # {{docs-fragment using-sharded-models}} # Use in vLLM app vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # Match the number of GPUs used for sharding ), extra_args=[ "--tensor-parallel-size", "4", # Match sharding config ], ) if __name__ == "__main__": # Prefetch with sharding run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", accelerator="L40s:4", shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs(tensor_parallel_size=4), ), ) run.wait() flyte.serve( vllm_app.clone_with( name=vllm_app.name, # override the model path to use the prefetched model model_path=flyte.app.RunOutput(type="directory", run_name=run.name), # set the hf_model_path to None hf_model_path=None, # stream the model from flyte object store directly to the GPU stream_model=True, ) ) # {{/docs-fragment using-sharded-models}} # {{docs-fragment complete-example}} # define the app environment vllm_app = VLLMAppEnvironment( name="qwen-serving-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=600, ), requires_auth=False, ) if __name__ == "__main__": # prefetch the model print("Prefetching model...") run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b", cpu="4", mem="16Gi", ephemeral_storage="50Gi", ) # wait for completion print("Waiting for prefetch to complete...") run.wait() print(f"Model prefetched: {run.outputs()[0].path}") # deploy the app print("Deploying app...") flyte.init_from_config() app = flyte.serve( vllm_app.clone_with( name=vllm_app.name, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), hf_model_path=None, stream_model=True, ) ) print(f"App deployed: {app.url}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/prefetch_examples.py* ## CLI options Complete CLI usage: ```bash flyte prefetch hf-model \ --artifact-name \ --architecture \ --task \ --modality text \ --format safetensors \ --model-type transformer \ --short-description "Description" \ --force 0 \ --wait \ --hf-token-key HF_TOKEN \ --cpu 4 \ --mem 16Gi \ --disk 100Gi \ --gpu L40s:4 \ --shm auto \ --raw-data-path s3://my-bucket/models \ --shard-config shard_config.yaml ``` ## Complete example Here's a complete example of prefetching and using a model: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0b52", # "flyteplugins-vllm>=2.0.0b49", # ] # /// """Prefetch examples for the prefetching-models.md documentation.""" import flyte from flyte.prefetch import ShardConfig, VLLMShardArgs from flyteplugins.vllm import VLLMAppEnvironment # {{docs-fragment basic-prefetch}} # Prefetch a HuggingFace model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") # Wait for prefetch to complete run.wait() # Get the model path model_path = run.outputs()[0].path print(f"Model prefetched to: {model_path}") # {{/docs-fragment basic-prefetch}} # {{docs-fragment using-prefetched-models}} # Prefetch the model run = flyte.prefetch.hf_model(repo="Qwen/Qwen3-0.6B") run.wait() # Use the prefetched model vllm_app = VLLMAppEnvironment( name="my-llm-app", model_path=flyte.app.RunOutput( type="directory", run_name=run.name, ), model_id="qwen3-0.6b", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1"), stream_model=True, ) app = flyte.serve(vllm_app) # {{/docs-fragment using-prefetched-models}} # {{docs-fragment custom-artifact-name}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b-model", # Custom name for the stored model ) # {{/docs-fragment custom-artifact-name}} # {{docs-fragment hf-token}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-7b-hf", hf_token_key="HF_TOKEN", # Name of Flyte secret containing HF token ) # {{/docs-fragment hf-token}} # {{docs-fragment with-resources}} run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", cpu="4", mem="16Gi", ephemeral_storage="100Gi", ) # {{/docs-fragment with-resources}} # {{docs-fragment vllm-sharding}} run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", resources=flyte.Resources(cpu="8", memory="32Gi", gpu="L40s:4"), shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs( tensor_parallel_size=4, dtype="auto", trust_remote_code=True, ), ), hf_token_key="HF_TOKEN", ) run.wait() # {{/docs-fragment vllm-sharding}} # {{docs-fragment using-sharded-models}} # Use in vLLM app vllm_app = VLLMAppEnvironment( name="multi-gpu-llm-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="llama-2-70b", resources=flyte.Resources( cpu="8", memory="32Gi", gpu="L40s:4", # Match the number of GPUs used for sharding ), extra_args=[ "--tensor-parallel-size", "4", # Match sharding config ], ) if __name__ == "__main__": # Prefetch with sharding run = flyte.prefetch.hf_model( repo="meta-llama/Llama-2-70b-hf", accelerator="L40s:4", shard_config=ShardConfig( engine="vllm", args=VLLMShardArgs(tensor_parallel_size=4), ), ) run.wait() flyte.serve( vllm_app.clone_with( name=vllm_app.name, # override the model path to use the prefetched model model_path=flyte.app.RunOutput(type="directory", run_name=run.name), # set the hf_model_path to None hf_model_path=None, # stream the model from flyte object store directly to the GPU stream_model=True, ) ) # {{/docs-fragment using-sharded-models}} # {{docs-fragment complete-example}} # define the app environment vllm_app = VLLMAppEnvironment( name="qwen-serving-app", # this will download the model from HuggingFace into the app container's filesystem model_hf_path="Qwen/Qwen3-0.6B", model_id="qwen3-0.6b", resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=600, ), requires_auth=False, ) if __name__ == "__main__": # prefetch the model print("Prefetching model...") run = flyte.prefetch.hf_model( repo="Qwen/Qwen3-0.6B", artifact_name="qwen-0.6b", cpu="4", mem="16Gi", ephemeral_storage="50Gi", ) # wait for completion print("Waiting for prefetch to complete...") run.wait() print(f"Model prefetched: {run.outputs()[0].path}") # deploy the app print("Deploying app...") flyte.init_from_config() app = flyte.serve( vllm_app.clone_with( name=vllm_app.name, model_path=flyte.app.RunOutput(type="directory", run_name=run.name), hf_model_path=None, stream_model=True, ) ) print(f"App deployed: {app.url}") # {{/docs-fragment complete-example}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/serve-and-deploy-apps/prefetch_examples.py* ## Prefetched models are artifacts A successful prefetch registers the weights as a versioned model artifact, with the Hugging Face commit as its version and the repo README as its model card. For what that means for the registry, how to retrieve a prefetched model by name or by source repo, and how it appears in lineage, see **Artifacts > Prefetch Hugging Face models**. ## Best practices 1. **Prefetch before deployment**: Prefetch models before deploying apps for faster startup 2. **Version models**: Use meaningful artifact names to easily identify the model in object store paths 3. **Shard appropriately**: Shard models for the GPU configuration you'll use for inference 4. **Cache prefetched models**: Once prefetched, models are cached in your storage backend for faster serving ## Troubleshooting **Prefetch fails:** - Check HuggingFace token (if required) - Verify model repo exists and is accessible - Check resource availability - Review prefetch task logs **Sharding fails:** - Ensure accelerator matches shard config - Check GPU memory is sufficient - Verify `tensor_parallel_size` matches GPU count - Review prefetch task logs for sharding-related errors **Model not found in app:** - Verify RunOutput references correct run name - Check that prefetch completed successfully - Ensure model_path is set correctly - Review app startup logs === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/deploy-trained-models === Serve a model trained in a Flyte task behind an endpoint, with vLLM, SGLang, or your own FastAPI app. # Deploy trained models A model trained in a task can go straight to an endpoint. The task saves the weights to object storage, and an app mounts them when it starts, so you never copy weights by hand or bake them into an image. ## Publish the model as an artifact Return the weights from the training task and wrap them with `flyte.artifacts.new()`. Every run registers a new version of the artifact: ``` import flyte from flyte import artifacts from flyte.io import Dir env = flyte.TaskEnvironment( name="training", image=flyte.Image.from_debian_base().with_pip_packages( "torch", "transformers", "accelerate" ), resources=flyte.Resources(cpu="4", memory="32Gi", gpu="L40s:1", disk="100Gi"), ) @env.task(produces_artifacts=True) async def finetune(base_model: str) -> Dir: from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(base_model) model = AutoModelForCausalLM.from_pretrained(base_model) # Add your training loop here. model.save_pretrained("model") tokenizer.save_pretrained("model") weights = await Dir.from_local("model") return artifacts.new( weights, artifacts.Metadata.create_model_metadata( name="support-llm", framework="PyTorch", task="text-generation", serial_format="safetensors", ), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/deploy-trained-models/train_artifact.py* The task must set `produces_artifacts=True`. Without it, no artifact is registered and the app has nothing to resolve. See **Artifacts > Task outputs as artifacts**. ## Serve an LLM with vLLM Pass the artifact to `VLLMAppEnvironment` as `model_path`. `SGLangAppEnvironment` takes the same argument: ``` import flyte import flyte.app from flyte.remote import App from flyteplugins.vllm import VLLMAppEnvironment app_env = VLLMAppEnvironment( name="support-llm", model_path=flyte.app.ArtifactValue(name="support-llm", type="directory"), model_id="support-llm", resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L40s:1", disk="50Gi"), scaling=flyte.app.Scaling(replicas=(0, 1), scaledown_after=600), ) if __name__ == "__main__": flyte.init_from_config() flyte.deploy(app_env) App.get(name=app_env.name).activate() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/deploy-trained-models/serve_artifact_vllm.py* The directory must be in a format the engine can load, such as the output of `save_pretrained()`. A PEFT adapter saved on its own is not enough, so merge it into the base model first. Call the deployed app with any OpenAI client. See **Inference > Self-hosted endpoints > vLLM > Using the OpenAI-compatible API**. ## Serve any other model with FastAPI For a model vLLM and SGLang don't serve, such as a classifier, publish it the same way: ``` classifier_env = flyte.TaskEnvironment( name="classifier", image=flyte.Image.from_debian_base().with_pip_packages("joblib", "scikit-learn"), resources=flyte.Resources(cpu="2", memory="4Gi"), ) @classifier_env.task(produces_artifacts=True) async def train_classifier() -> Dir: import os import joblib from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression features, labels = make_classification(n_samples=500, n_features=4, random_state=0) model = LogisticRegression().fit(features, labels) os.makedirs("classifier", exist_ok=True) joblib.dump(model, "classifier/model.joblib") weights = await Dir.from_local("classifier") return artifacts.new( weights, artifacts.Metadata.create_model_metadata( name="churn-classifier", framework="scikit-learn", task="classification", serial_format="joblib", ), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/deploy-trained-models/train_artifact.py* Run the task once on your cluster before you deploy the app, because the app resolves its model at deploy time. Running `finetune` doesn't train the classifier: ```bash flyte run train_artifact.py train_classifier ``` Then mount the artifact into a `FastAPIAppEnvironment` with a parameter: ``` from contextlib import asynccontextmanager import flyte import flyte.app import joblib from fastapi import FastAPI from flyte.app import Parameter from flyte.app.extras import FastAPIAppEnvironment from flyte.remote import App MODEL_DIR = "/tmp/model" state = {} @asynccontextmanager async def lifespan(app: FastAPI): state["model"] = joblib.load(f"{MODEL_DIR}/model.joblib") yield app = FastAPI(lifespan=lifespan) @app.post("/predict") async def predict(features: list[float]) -> dict: return {"prediction": state["model"].predict([features]).tolist()[0]} app_env = FastAPIAppEnvironment( name="churn-classifier", app=app, image=flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "joblib", "scikit-learn"), resources=flyte.Resources(cpu="2", memory="4Gi"), parameters=[ Parameter( name="model", value=flyte.app.ArtifactValue(name="churn-classifier", type="directory"), mount=MODEL_DIR, ), ], ) if __name__ == "__main__": flyte.init_from_config() flyte.deploy(app_env) App.get(name=app_env.name).activate() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/deploy-trained-models/serve_artifact_fastapi.py* `mount` is always a directory. A `flyte.io.File` artifact is downloaded into it, and a `flyte.io.Dir` artifact appears at it. An artifact used as an app parameter must store one of those two types. See **Artifacts > Use artifacts in apps**. ## Pin and roll back a version An app resolves the latest artifact version when you deploy it and keeps that version until you deploy again. A version published later doesn't change a running app. To roll back, deploy with an explicit version: ``` def roll_back(version: str) -> None: pinned_env = app_env.clone_with( name=app_env.name, model_path=flyte.app.ArtifactValue(name="support-llm", type="directory", version=version), ) flyte.deploy(pinned_env) App.get(name=pinned_env.name).activate() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/deploy-trained-models/serve_artifact_vllm.py* List the versions with `flyte get artifact support-llm`. The artifact's **Artifacts > Automatic lineage tracking** shows which app deployment serves each version and which run produced it. ## Automate training through deployment To retrain, check, and deploy in one step, with an accuracy gate or a person's approval before release, use a factory. See **Factories > End in an app**. ## Choose an app type | Model | App | Details | |---|---|---| | LLM, high throughput | `VLLMAppEnvironment` | **Inference > Self-hosted endpoints > vLLM** | | LLM, structured generation | `SGLangAppEnvironment` | **Inference > Self-hosted endpoints > SGLang** | | Anything else | `FastAPIAppEnvironment` | **Apps > Native app integrations > FastAPI app** | === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/batch-inference === Keep expensive GPUs busy during batch inference instead of idle and waiting. # Maximize GPU utilization for batch inference GPUs are expensive. When running batch inference, the single biggest cost driver is **idle GPU time**: cycles where the GPU sits waiting with nothing to do. Understanding why this happens and how to fix it is the key to cost-effective batch inference. ## Why GPU utilization drops A typical inference task does three things: 1. **Load data**: read from storage, deserialize, preprocess (CPU/IO-bound) 2. **Run inference**: forward pass through the model (GPU-bound) 3. **Post-process**: format results, write outputs (CPU/IO-bound) When these steps run sequentially, the GPU is idle during steps 1 and 3. For many workloads, data loading and preprocessing dominate wall-clock time, leaving the GPU busy for only a fraction of the total: ```mermaid gantt title Sequential execution โ€” GPU idle during CPU/IO work dateFormat X axisFormat %s section Task 1 Load data (CPU/IO) :a1, 0, 3 Inference (GPU) :a2, after a1, 2 Post-process (CPU/IO) :a3, after a2, 1 section Task 2 Load data (CPU/IO) :b1, after a3, 3 Inference (GPU) :b2, after b1, 2 Post-process (CPU/IO) :b3, after b2, 1 section GPU Idle :crit, g1, 0, 3 Busy :active, g2, 3, 5 Idle :crit, g3, 5, 9 Busy :active, g4, 9, 11 Idle :crit, g5, 11, 12 ``` In this example, the GPU is busy for only 4 out of 12 time units: **33% utilization**. The rest is wasted waiting for CPU and IO operations. ## Serving vs in-process batch inference There are two common approaches to batch inference: sending requests to a **hosted model server** (serving), or running the model **in-process** alongside data loading. Each has distinct trade-offs: | | Hosted serving | In-process (Flyte) | |---|---|---| | **Architecture** | Separate inference server (e.g. Triton, vLLM server, TGI) accessed over the network | Model loaded directly in the task process, inference via `DynamicBatcher` | | **Data transfer** | Every request serialized over the network; large payloads add latency | Zero-copy: data stays in-process, no serialization overhead | | **Backpressure** | Hard to implement; push-based architecture can overwhelm the server or drop requests | Two levels: `DynamicBatcher` queue blocks producers when full, and Flyte's task scheduling automatically queues new inference tasks when replicas are busy; backpressure propagates end-to-end without any extra code | | **Utilization** | Servers are often over-provisioned to maintain availability, leading to low average utilization | Batcher continuously fills the GPU with work from concurrent producers | | **Multi-model** | Each model needs its own serving deployment, load balancer, and scaling config | Multiple models can time-share the same GPU: when one model finishes, the next is loaded automatically via reusable containers, no container orchestration required | | **Scaling** | Requires separate infrastructure for the serving layer (load balancers, autoscalers, health checks) | Scales with Flyte: replicas auto-scale based on demand | | **Cost** | Pay for always-on serving infrastructure even during low-traffic periods | Pay only for the duration of the batch job | | **Fault tolerance** | Need retries, circuit breakers, and timeout handling for network failures | Failures are local; Flyte handles retries and recovery at the task level | | **Best for** | Real-time / low-latency serving with unpredictable request patterns | Large-scale batch processing with known datasets | For batch workloads, in-process inference eliminates the network overhead and infrastructure complexity of a serving layer while achieving higher GPU utilization through intelligent batching. ## Solution: `DynamicBatcher` `DynamicBatcher` from `flyte.extras` solves the utilization problem by **separating data loading from inference** and running them concurrently. Multiple async producers load and preprocess data while a single consumer feeds the GPU in optimally-sized batches: ```mermaid flowchart LR subgraph producers ["Concurrent producers (CPU/IO)"] P1["Stream 1: load + preprocess"] P2["Stream 2: load + preprocess"] P3["Stream N: load + preprocess"] end subgraph batcher ["DynamicBatcher"] Q["Queue with backpressure"] A["Aggregation loop
(assembles cost-budgeted batches)"] Q --> A end subgraph consumer ["Processing loop (GPU)"] G["process_fn / inference_fn
(batched forward pass)"] end P1 --> Q P2 --> Q P3 --> Q A --> G ``` The batcher runs two internal loops: 1. **Aggregation loop**: drains the submission queue and assembles batches that respect a cost budget (`target_batch_cost`), a maximum size (`max_batch_size`), and a timeout (`batch_timeout_s`). This ensures the GPU always receives optimally-sized batches. 2. **Processing loop**: pulls assembled batches and calls your processing function, resolving each record's future with its result. This pipelining means the GPU is processing batch N while data for batch N+1 is being loaded and assembled, **eliminating idle time**. ### Basic usage ```python from flyte.extras import DynamicBatcher async def process(batch: list[dict]) -> list[str]: """Your batch processing function. Must return results in the same order as the input.""" return [heavy_computation(item) for item in batch] async with DynamicBatcher( process_fn=process, target_batch_cost=1000, # cost budget per batch max_batch_size=64, # hard cap on records per batch batch_timeout_s=0.05, # max wait time before dispatching a partial batch max_queue_size=5_000, # queue size for backpressure ) as batcher: futures = [] for record in my_records: future = await batcher.submit(record, estimated_cost=10) futures.append(future) results = await asyncio.gather(*futures) ``` Each call to `submit()` is non-blocking; it enqueues the record and immediately returns a `Future`. When the queue is full, `submit()` awaits until space is available, providing natural backpressure to prevent producers from overwhelming the GPU. ### Cost estimation The batcher uses cost estimates to decide how many records to group into each batch. You can provide costs in several ways (checked in order of precedence): 1. **Explicit**: pass `estimated_cost` to `submit()` 2. **Estimator function**: pass `cost_estimator` to the constructor 3. **Protocol**: implement `estimate_cost()` on your record type 4. **Default**: falls back to `default_cost` (default: 1) ## `TokenBatcher` for LLM inference For LLM workloads, `TokenBatcher` is a convenience subclass that uses token-aware parameter names: ```python from dataclasses import dataclass from flyte.extras import TokenBatcher @dataclass class Prompt: text: str def estimate_tokens(self) -> int: """Rough token estimate (~4 chars per token).""" return len(self.text) // 4 + 1 async def inference(batch: list[Prompt]) -> list[str]: """Run batched inference through your model.""" texts = [p.text for p in batch] outputs = model.generate(texts, sampling_params) return [o.outputs[0].text for o in outputs] async with TokenBatcher( inference_fn=inference, target_batch_tokens=32_000, # token budget per batch max_batch_size=256, ) as batcher: future = await batcher.submit(Prompt(text="What is 2+2?")) result = await future ``` `TokenBatcher` checks the `TokenEstimator` protocol (`estimate_tokens()`) in addition to `CostEstimator` (`estimate_cost()`), making it natural to work with prompt types. ## Combining with reusable containers `DynamicBatcher` on its own improves utilization within a single task. When combined with **Tasks > Configure tasks > Reusable containers**, it adds three capabilities: - **Amortized model loading**: the model is loaded once per container and reused across many task invocations, avoiding repeated download and initialization costs - **Cross-task batching**: with `ReusePolicy(concurrency=N)`, multiple task invocations run concurrently on the same replica, all feeding records into the **same shared batcher**. This means the GPU always has a full queue of work. - **Automatic scaling**: replicas scale between min and max based on demand, and each replica maintains its own model + batcher ```mermaid flowchart TB D["Driver task
fans out chunks"] --> |chunk 1| R1 D --> |chunk 2| R1 D --> |chunk 3| R2 D --> |chunk ...| R1 D --> |chunk N| R2 subgraph R1 ["GPU Replica 1"] direction TB M1["Model (loaded once via alru_cache)"] B1["Shared TokenBatcher"] T1a["infer_batch call 1"] --> B1 T1b["infer_batch call 2"] --> B1 T1c["infer_batch call ..."] --> B1 B1 --> M1 end subgraph R2 ["GPU Replica 2"] direction TB M2["Model (loaded once via alru_cache)"] B2["Shared TokenBatcher"] T2a["infer_batch call 1"] --> B2 T2b["infer_batch call 2"] --> B2 T2c["infer_batch call ..."] --> B2 B2 --> M2 end ``` The key technique is using `@alru_cache` to create **process-level singletons**: the model and batcher are initialized on the first task invocation and reused by all subsequent invocations on that replica. ### Example: batch LLM inference with vLLM This example loads math problems from HuggingFace's gsm8k dataset and solves them using batched vLLM inference across GPU replicas. #### 1. Define the environment ```python import flyte from flyte.extras import TokenBatcher image = ( flyte.Image.from_debian_base() .with_pip_packages("vllm", "hf-transfer", "unionai-reuse") .with_env_vars({"HF_HUB_ENABLE_HF_TRANSFER": "1"}) ) gpu_env = flyte.TaskEnvironment( name="gpu_worker", resources=flyte.Resources(cpu=4, memory="16Gi", gpu="A10G:1"), image=image, reusable=flyte.ReusePolicy( replicas=2, # 2 GPU replicas concurrency=10, # 10 concurrent tasks per replica ), ) driver_env = flyte.TaskEnvironment( name="driver", resources=flyte.Resources(cpu=2, memory="2Gi"), image=image, depends_on=[gpu_env], ) ``` With `replicas=2` and `concurrency=10`, up to 20 `infer_batch` calls run simultaneously across 2 GPUs, all sharing their replica's model and batcher. #### 2. Create process-level singletons ```python from async_lru import alru_cache from dataclasses import dataclass @dataclass class Prompt: task_id: str index: int text: str def estimate_tokens(self) -> int: return len(self.text) // 4 + 1 @alru_cache(maxsize=1) async def get_inference_fn(): """Load the model once per container lifetime.""" from vllm import LLM, SamplingParams llm = LLM(model="Qwen/Qwen2.5-7B-Instruct", gpu_memory_utilization=0.9, max_model_len=4096) params = SamplingParams(temperature=0.7, max_tokens=512) async def inference(batch: list[Prompt]) -> list[str]: texts = [p.text for p in batch] outputs = llm.generate(texts, params) return [o.outputs[0].text for o in outputs] return inference @alru_cache(maxsize=1) async def get_batcher() -> TokenBatcher[Prompt, str]: """Create a single batcher per container โ€” shared across all concurrent tasks.""" inference_fn = await get_inference_fn() batcher = TokenBatcher[Prompt, str]( inference_fn=inference_fn, target_batch_tokens=32_000, max_batch_size=256, batch_timeout_s=0.05, max_queue_size=5_000, ) await batcher.start() return batcher ``` To stream the model's weights from object storage instead of downloading them from the Hugging Face Hub, see **Inference > Stream model weights**. #### 3. Define the GPU worker task ```python import asyncio import logging logger = logging.getLogger(__name__) @gpu_env.task async def infer_batch(prompts: list[str], task_id: str) -> list[str]: """Submit prompts to the shared batcher and return completions.""" batcher = await get_batcher() futures: list[asyncio.Future[str]] = [] for idx, text in enumerate(prompts): record = Prompt(task_id=task_id, index=idx, text=text) future = await batcher.submit(record) futures.append(future) results = await asyncio.gather(*futures) logger.info( "[%s] completed %d records | utilization: %.1f%% | batches: %d", task_id, len(results), batcher.stats.utilization * 100, batcher.stats.total_batches, ) return list(results) ``` Every concurrent `infer_batch` call on the same replica feeds into the same batcher. The batcher continuously assembles token-budgeted batches from all concurrent callers, keeping the GPU saturated. #### 4. Define the driver task ```python @driver_env.task async def main(num_questions: int = 500, chunk_size: int = 50) -> dict[str, list[str]]: """Fetch questions and fan out across GPU replicas.""" questions = await fetch_questions(num_questions) chunks = [questions[i:i + chunk_size] for i in range(0, len(questions), chunk_size)] task_ids = [f"chunk_{i:03d}" for i in range(len(chunks))] all_results = await asyncio.gather( *(infer_batch(chunk, tid) for chunk, tid in zip(chunks, task_ids)) ) return dict(zip(task_ids, all_results)) ``` ## Monitoring utilization `DynamicBatcher` exposes a `stats` property with real-time metrics: ```python stats = batcher.stats print(f"Utilization: {stats.utilization:.1%}") # fraction of time spent processing print(f"Records processed: {stats.total_completed}") print(f"Batches dispatched: {stats.total_batches}") print(f"Avg batch size: {stats.avg_batch_size:.1f}") print(f"Busy time: {stats.busy_time_s:.1f}s") print(f"Idle time: {stats.idle_time_s:.1f}s") ``` | Metric | Description | |---|---| | `utilization` | Fraction of wall-clock time spent inside `process_fn` (0.0 to 1.0). Target: > 0.9. | | `total_submitted` | Total records submitted via `submit()` | | `total_completed` | Total records whose futures have been resolved | | `total_batches` | Number of batches dispatched to `process_fn` | | `avg_batch_size` | Running average records per batch | | `avg_batch_cost` | Running average cost per batch | | `busy_time_s` | Cumulative seconds spent inside `process_fn` | | `idle_time_s` | Cumulative seconds the processing loop waited for batches | If utilization is low, consider: - **Increasing concurrency**: more concurrent producers means the batcher has more records to assemble into batches - **Reducing `batch_timeout_s`**: dispatch partial batches faster instead of waiting - **Increasing `max_queue_size`**: allow more records to be buffered ahead of the GPU - **Adding more data streams**: ensure the GPU always has work queued up === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/stream-model-weights === Load a model's safetensors weights from object storage onto the GPU inside a task, without writing them to local disk. # Stream model weights `flyte.extras.model_streamer` loads a model's safetensors weights from object storage tensor by tensor, inside a task. Use it when a GPU task loads a large model, for example in an `alru_cache`d bootstrap on reusable containers (see **Inference > Maximize GPU utilization for batch inference > Combining with reusable containers**). The safetensors weights are not written to local disk. `load_hf_model()` and the vLLM `engine_args()` download every other file under the model's object-store prefix (config, tokenizer, and any non-safetensors files) to local disk. Requires `flyte` 2.11.1 or later. The streamer needs `torch`, `load_hf_model()` also needs `transformers`, and the vLLM load format needs `vllm` and `flyteplugins-vllm` 2.11.1 or later. ## Model location Every entry point takes `path`, the object-store prefix of a Hugging Faceโ€“style model directory, such as `s3://bucket/models/qwen2.5-7b`. The prefix holds the `*.safetensors` files, optionally a `model.safetensors.index.json`, and the config and tokenizer files. To copy a Hub model there, use `flyte.prefetch.hf_model()` (see **Inference > Prefetching models**). A task that takes the model as a `flyte.io.Dir` passes `model.path`. A local filesystem path, with or without `file://`, is not supported. ## Load a Hugging Face model `flyte.extras.model_streamer.load_hf_model()` is async. It builds a `transformers` model with its parameters on the `meta` device, then streams each weight onto `device` as it arrives. It returns the model in eval mode and the local directory holding the config and tokenizer files, so you can load the tokenizer with `AutoTokenizer.from_pretrained(local_dir)`. | Parameter | Default | Description | |-----------|---------|-------------| | `path` | | Object-store prefix of the model. | | `device` | `"cuda"` | Device the weights are placed on. | | `dtype` | `None` | Casts floating-point weights. `None` keeps the checkpoint's dtype. | | `model_class` | `AutoModelForCausalLM` | Any `Auto*` class or concrete `PreTrainedModel` subclass. | | `local_dir` | A new temporary directory | Where the config and tokenizer files are downloaded. | | `trust_remote_code` | `False` | Passed to `transformers`. | | `chunk_size`, `max_concurrency` | 16 MiB, 32 | Byte-range size and number of ranges fetched in parallel. Set `FLYTE_MODEL_LOADER_CHUNK_SIZE` and `FLYTE_MODEL_LOADER_MAX_CONCURRENCY` in the environment to change the defaults. | Checkpoint tensors that the model has no parameter for are logged and ignored. A parameter that no tensor fills raises `KeyError`. This task embeds text on a reusable GPU container, and `alru_cache` loads the model once per container: ``` import flyte from async_lru import alru_cache from flyte.io import Dir env = flyte.TaskEnvironment( name="streamed-embedder", image=flyte.Image.from_debian_base().with_pip_packages("async-lru", "torch", "transformers", "unionai-reuse"), resources=flyte.Resources(cpu=4, memory="8Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=1, concurrency=8), ) @alru_cache(maxsize=1) async def get_model(model_path: str): """Load the model once per container.""" import torch from flyte.extras.model_streamer import load_hf_model from transformers import AutoModel, AutoTokenizer model, local_dir = await load_hf_model(model_path, model_class=AutoModel, device="cuda", dtype=torch.float16) return model, AutoTokenizer.from_pretrained(local_dir) @env.task async def embed(model: Dir, texts: list[str]) -> list[list[float]]: import torch hf_model, tokenizer = await get_model(model.path) batch = tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors="pt").to("cuda") with torch.inference_mode(): cls = hf_model(**batch).last_hidden_state[:, 0] return torch.nn.functional.normalize(cls, dim=-1).float().cpu().tolist() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/stream-model-weights/load_hf_model.py* ## Stream into any module `ModelStreamer(path, chunk_size=None, max_concurrency=None)` is the streamer underneath, for models that are not `transformers` models. It uses the same `chunk_size` and `max_concurrency` defaults as `load_hf_model()`. - `stream(device=None, dtype=None)`: an async iterator of `(name, tensor)` pairs, in the order the tensors finish downloading. With `device`, each tensor is moved there as it arrives. With `dtype`, floating-point tensors are cast. - `stream_sync(device=None, dtype=None)`: the same, as a regular iterator. It works from any thread, including one with a running event loop. - `state_dict(device=None, dtype=None)`: collects every tensor into a dict. - `load_into(module, device=None, dtype=None, strict=True, key_mapping=None)`: streams the weights into a module's parameters and buffers, replacing each entry as it arrives. Build the module with `with empty_weights():` so its parameters are on `meta` and never allocated twice. Then pass `device`: a `meta` entry with no `device` raises `ValueError`. After the stream ends, `load_into()` calls the module's `tie_weights()` if it has one. With `strict=True`, a parameter left on `meta` or an unmatched checkpoint tensor raises `KeyError`. With `strict=False`, it returns a `LoadResult` listing `missing_keys` and `unexpected_keys`. - `download_metadata(local_dir)`: downloads everything under the prefix except the `*.safetensors` files. This task streams a checkpoint into a PyTorch module: ``` import flyte from flyte.io import Dir env = flyte.TaskEnvironment( name="streamed-classifier", image=flyte.Image.from_debian_base().with_pip_packages("torch"), resources=flyte.Resources(cpu=4, memory="8Gi", gpu="L4:1"), ) @env.task async def predict(model: Dir, features: list[float]) -> list[float]: import torch from flyte.extras.model_streamer import ModelStreamer, empty_weights # The parameters stay on the meta device until their tensors arrive. with empty_weights(): classifier = torch.nn.Sequential(torch.nn.Linear(4, 16), torch.nn.ReLU(), torch.nn.Linear(16, 2)) await ModelStreamer(model.path).load_into(classifier, device="cuda") with torch.inference_mode(): return classifier(torch.tensor([features], device="cuda")).softmax(dim=-1)[0].tolist() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/stream-model-weights/load_into.py* ## Load weights into vLLM `flyteplugins-vllm` registers a vLLM load format, `flyte-streaming`, through vLLM's `vllm.general_plugins` entry point. `flyteplugins.vllm.model_streamer.engine_args(path)` downloads the non-safetensors files under `path` and returns the `LLM` keyword arguments that select the load format: `model`, `load_format`, and `model_loader_extra_config`. Pass any other engine arguments alongside them. It takes the same `local_dir`, `chunk_size`, and `max_concurrency` arguments as `load_hf_model()`. In an async task, build the engine off the event loop, for example `await asyncio.to_thread(LLM, **args, max_model_len=4096)`, because `LLM()` blocks for the whole load. This task builds the engine once per reusable container and shares it between calls: ``` import asyncio import flyte from async_lru import alru_cache from flyte.io import Dir from flyteplugins.vllm import DEFAULT_VLLM_IMAGE env = flyte.TaskEnvironment( name="streamed-vllm", image=DEFAULT_VLLM_IMAGE.clone(name="streamed-vllm").with_pip_packages("async-lru", "unionai-reuse"), resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=1, concurrency=4), ) @alru_cache(maxsize=1) async def get_llm(model_path: str): """Build the engine once per container.""" from flyteplugins.vllm.model_streamer import engine_args from vllm import LLM args = await engine_args(model_path) # LLM() blocks for the whole load, so run it off the event loop. return await asyncio.to_thread(LLM, **args, max_model_len=4096) # Concurrent calls on a replica share the engine, and the offline LLM isn't re-entrant. generate_lock = asyncio.Lock() @env.task async def generate(model: Dir, prompts: list[str]) -> list[str]: from vllm import SamplingParams llm = await get_llm(model.path) messages = [[{"role": "user", "content": prompt}] for prompt in prompts] async with generate_lock: outputs = await asyncio.to_thread(llm.chat, messages, SamplingParams(max_tokens=128)) return [output.outputs[0].text for output in outputs] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/inference/stream-model-weights/vllm_task.py* `engine_args()` also sets `VLLM_WORKER_MULTIPROC_METHOD=spawn` unless it is already set. Keep it at `spawn`. obstore's runtime does not survive `fork()`, and vLLM forks its engine-core process by default. `ModelStreamer` detects a process forked from one that has already streamed or downloaded metadata and raises `RuntimeError` instead of hanging on the first read. ## Gotchas - A prefix with no `*.safetensors` files raises `ValueError: No files found matching pattern: *.safetensors`. - Weights in other formats under the prefix, such as `pytorch_model.bin` or an `original/*.pth` directory, are downloaded to local disk with the config and tokenizer. Keep weights in other formats out of the prefix. ## Related pages To serve a model behind an endpoint instead of loading it inside a task, use `stream_model=True` on a **Inference > Self-hosted endpoints > vLLM > Model streaming** or an **Inference > Self-hosted endpoints > SGLang > Model streaming**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway === One endpoint in your own cloud for every model call, with virtual keys and budgets, fallbacks when a provider fails, and guardrails on every prompt and answer. # Inference Gateway The Union Inference Gateway puts one OpenAI-compatible endpoint in front of every model provider you use. Every task, app, and laptop calls the gateway instead of calling providers directly, and the gateway applies your policy to every call. ## Why use a gateway **One provider key, many virtual keys.** You store each provider's API key once, as a Union secret. Teams, apps, and developers get *virtual keys* (`sk-un-...`) instead. Each virtual key has its own budget, rate limit, and list of allowed models. When a key reaches its budget the gateway rejects further calls, so a runaway agent loop costs what you allowed and no more, however many gateway replicas are running. Revoking a virtual key never means rotating the provider key that everyone else depends on. **Fallbacks when a provider fails.** A request can name fallback models, for example `anthropic/claude-haiku-4-5` behind `openai/gpt-4.1-mini`. If the primary provider errors, is down, or rejects the call for that key, the gateway tries the next model in the list. Your application keeps answering through a provider outage. **Guardrails before and after every call.** A *pre-call* guardrail sees each prompt before it reaches a model and can block it, or answer it from your own cache. A *post-call* guardrail sees each answer before it reaches the caller and can withhold it. Guardrails are global: they apply to every key on the gateway, so no team can forget to add them. You write them as small Union apps, in Python with `GuardrailAppEnvironment` or in any language that speaks HTTP. ## One endpoint for everything The gateway is a single endpoint for all of your LLM traffic: - **Tasks and apps** in every Union cluster call it with a virtual key stored as a secret. See **Inference > Inference Gateway > Use from tasks and apps**. - **Laptops** call it too, so notebooks, coding assistants, and scripts get the same budgets and guardrails as production. You can expose the endpoint publicly, or keep it behind Union sign-in and reach it with `flyte proxy app`. See **Inference > Inference Gateway > Use from your laptop**. - **Self-hosted models** served with vLLM or SGLang on Union sit behind the same endpoint as hosted providers, so callers switch between them by changing a model name. Spend, token counts, latency, and blocked requests for every key show up in one place: **Settings โ†’ Inference Gateway** in the Union console. ## Runs in your cloud The gateway runs in your data plane, on your compute, as a Union app. ```mermaid flowchart LR subgraph dp["Your cloud (data plane)"] tasks["Tasks and apps"] --> gw["Inference Gateway"] gw <--> gr["Guardrail apps"] gw --> self["vLLM / SGLang apps"] end laptop["Laptops"] --> gw gw --> providers["Model providers
OpenAI, Anthropic, Bedrock, ..."] gw -. "usage counts" .-> cp["Union control plane"] cp -. "policy" .-> gw ``` - **Prompts and answers never reach Union's control plane.** Traffic goes from your callers to the gateway to the provider, and nowhere else. The control plane sends the gateway its policy (providers, keys, budgets, guardrails) and receives usage records: which key, which model, how many tokens, what it cost, how long it took. A usage record never contains a prompt or an answer. - **Provider credentials stay in your data plane.** Provider API keys are Union secrets mounted on the gateway. The policy refers to them by environment variable name and never carries the value. - **Zero trust.** Every call presents a virtual key. The gateway reaches guardrail apps and self-hosted models over cluster-local addresses, not through ingress. The gateway pulls its policy from the control plane, and the control plane never connects in to the gateway. See [Zero Trust security](../../../security/_index). - **Built for proxying.** The gateway is a lightweight proxy written in Go. It scales out with request rate. ## In this section ****Inference > Inference Gateway > Deploy the gateway**** Choose a cluster, size the gateway, and decide who can reach it. ****Inference > Inference Gateway > Providers**** Add hosted providers such as OpenAI and Anthropic, and self-hosted models served on Union. ****Inference > Inference Gateway > Virtual keys**** Issue keys with budgets, rate limits, model allowlists, and fallbacks. ****Inference > Inference Gateway > Use from tasks and apps**** Call the gateway from code running on Union. ****Inference > Inference Gateway > Use from your laptop**** Reach the gateway from any local tool, with or without exposing it publicly. **[Guardrails](./guardrails/_index)** Check every prompt and every answer with your own code. ****Inference > Inference Gateway > Decisions**** Ask a model typed questions about a state with `POST /v1/decisions`. {{< subpage-cards >}} ## Subpages - **Inference > Inference Gateway > Deploy the gateway** - Place the Inference Gateway on a cluster, size it for your request rate, and choose who can reach it. - **Inference > Inference Gateway > Providers** - Add hosted model providers and self-hosted vLLM or SGLang models to the Inference Gateway. - **Inference > Inference Gateway > Virtual keys** - Issue Inference Gateway keys with budgets, rate limits, model allowlists, and fallbacks. - **Inference > Inference Gateway > Use from tasks and apps** - Call models through the Inference Gateway from tasks and apps running on Union. - **Inference > Inference Gateway > Use from your laptop** - Reach the Inference Gateway from local tools, either through a public endpoint or behind Union sign-in with flyte proxy app. - **Inference > Inference Gateway > Guardrails** - Check every prompt before it reaches a model, and every answer before it reaches the caller, with your own code. - **Inference > Inference Gateway > Decisions** - Send a state and named questions to the Inference Gateway's POST /v1/decisions endpoint and get a typed answer to each. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/deploy-gateway === Place the Inference Gateway on a cluster, size it for your request rate, and choose who can reach it. # Deploy the gateway Deploy a gateway on the cluster where your LLM traffic originates. It runs as a Union app in your data plane, and every task, app, and laptop then calls its endpoint. ## Deploy from the console 1. Open **Settings โ†’ Inference Gateway** in the Union console and start a new gateway. 2. Fill in the gateway: | Field | Meaning | |---|---| | **Name** | Lowercase letters, digits, and dashes, for example `llm-gateway`. It also names the gateway's app and subdomain. | | **Cluster pool** | Where the gateway runs. | | **Cluster (optional)** | Pins the gateway to one named cluster, for organizations with several clusters. | | **Allow anonymous access** | Whether callers need Union sign-in. See **Inference > Inference Gateway > Deploy the gateway > Choose who can reach the gateway**. | | **Providers** | Optional. Providers you add here are mounted on the first deploy. See **Inference > Inference Gateway > Providers**. | 3. Deploy the gateway. You can't change the placement after the gateway is created. The console shows the gateway's endpoint when it is running. Callers use this URL, with `/v1` appended, as the base URL of any OpenAI-compatible client. Self-hosted models and guardrail apps must run on the same cluster as the gateway, because the gateway reaches them over cluster-local addresses. Pick the placement with that in mind. ## Size the gateway You size the gateway in requests per second, not replicas. Edit the gateway to set: | Setting | Meaning | Default | |---|---|---| | **Min requests/sec** | Capacity that is always running. | 1,000 | | **Max requests/sec** | The ceiling the gateway scales out to under load. Up to 10,000. | The minimum | Union runs one replica per 1,000 rps and autoscales between the two bounds on the observed request rate. Redeploying without changing these values keeps the current sizing. Each replica gets its share of a key's budget from the control plane, which never grants more in total than the key's budget. Two consequences follow: - Running more than one replica doesn't let a key spend more than its budget. - A replica restart doesn't reset a key's spend for the current budget window. The share the replica held before the restart stays counted against the budget, as if spent, so after a restart a key can be refused with `402` before its actual spend reaches the budget. The spend history in the console is computed separately, from usage records. ## Choose who can reach the gateway | Access mode | Who reaches the endpoint | Use it when | |---|---|---| | **Allow anonymous access** checked (default) | Anyone with the URL. The virtual key is the only credential. | Callers outside Union need a plain API-key style endpoint, for example a third-party SaaS tool. | | **Allow anonymous access** unchecked | Only callers with a Union identity. They still present a virtual key. | You want the endpoint closed to the internet. Developers reach it from laptops with `flyte proxy app`. | With anonymous access, a leaked virtual key can be used by anyone until you revoke it, up to that key's budget and allowed models. Keep budgets tight on keys that leave your organization. See **Inference > Inference Gateway > Use from your laptop** for how each mode works from a developer machine. Redeploying without changing the access mode keeps the current setting. ## Permissions | Action | Required permission | |---|---| | View the gateway, providers, keys, and guardrails | View LLM gateway | | Deploy the gateway, add providers, set guardrails | Manage LLM gateway | | Create, read, and revoke virtual keys; view usage | Manage LLM gateway keys | ## How changes reach the gateway Every change you make, such as a new key, a revoked key, a budget, a provider, or a guardrail, is part of the gateway's *policy*. The gateway keeps a watch open on the control plane, which checks for policy changes every 15 seconds, so a change reaches the gateway within about 15 seconds. The control plane never connects in to the gateway. Adding a hosted provider changes what is mounted on the gateway, so the gateway redeploys automatically. If that redeploy fails, the provider shows **Pending deploy** until you deploy the gateway again. Updating the gateway's proxy image needs a redeploy. The console shows when a newer image is available. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/providers === Add hosted model providers and self-hosted vLLM or SGLang models to the Inference Gateway. # Providers A provider is a source of models behind the gateway: a hosted API such as OpenAI or Anthropic, or a model you serve yourself on Union with vLLM or SGLang. Callers address every model as `provider/model`, for example `openai/gpt-4.1-mini` or `anthropic/claude-sonnet-4-5`, so moving a workload between providers means changing one string. ## Add a hosted provider 1. Store the provider's API key as a Union secret: ```bash flyte create secret openai-api-key ``` The command prompts for the value, so the key stays out of your shell history. 2. Open **Settings โ†’ Inference Gateway โ†’ Providers** and click **Add provider**. 3. Fill in the provider: | Field | Meaning | |---|---| | **Provider** | One of the supported providers listed below. | | **API key secret** | The Union secret that holds the API key, for example `openai-api-key`. | | **Models** | A comma-separated allowlist, for example `gpt-4.1, gpt-4.1-mini`. Leave it empty to allow every model. | | **Weight** | The load-balancing weight of the provider's API key among that provider's keys. The gateway gives each hosted provider one key, so the weight doesn't split traffic between providers. Defaults to `1`. | When you add the provider, the gateway redeploys automatically to mount the new secret, and the provider shows **Deployed**. If that redeploy fails, the provider shows **Pending deploy** until you deploy the gateway again. The secret is mounted on the gateway and stays in your data plane. The control plane never reads it, and the gateway's policy refers to it only by name. The gateway meters hosted providers from its built-in price catalog, so budgets count their spend without any setup. ### Supported providers `openai`, `anthropic`, `azure`, `bedrock`, `vertex`, `gemini`, `mistral`, `cohere`, `groq`, `deepseek`, `xai`, `perplexity`, `cerebras`, `fireworks`, `openrouter`, `huggingface`, `nebius`, `sarvam`, `elevenlabs`, `runway`, `wafer`, `typesafe`. The console lists the providers your gateway supports when you add one. To call a provider directly from a task or app instead, without the gateway, see [Providers](../providers/_index) in the Inference section. ## Add a self-hosted model You can put a model you serve on Union behind the gateway, next to hosted providers. Callers reach it with the same client, the same virtual keys, and the same guardrails. 1. Deploy the model as a **Inference > Self-hosted endpoints > vLLM** or **Inference > Self-hosted endpoints > SGLang** app on the gateway's cluster. 2. In **Settings โ†’ Inference Gateway โ†’ Providers**, click **Add provider** and choose **Union LLM (vLLM / SGLang app)**. 3. Fill in the provider: | Field | Meaning | |---|---| | **Serving app** | The vLLM or SGLang app. Only apps on the gateway's cluster are listed. | | **Model id** | The model the app serves (its `--served-model-name`). Filled in from the app when it records one. | | **Name** | The provider name, which callers use as the model prefix. | | **Cost** | USD per 1 million input tokens and per 1 million output tokens. | | **Answers decisions** | Lets callers send this app `POST /v1/decisions`. The model must support tool calling. See **Inference > Inference Gateway > Decisions**. | | **Weight** | Stored with the provider, but not sent to the gateway, so it has no effect. Defaults to `1`. | A provider named `qwen` whose app serves `qwen3-8b` is called as `qwen/qwen3-8b`. The gateway reaches the app over its cluster-local address, so no API key or public URL is involved. The app must be running when you add it. > [!WARNING] Set a cost for self-hosted models you want to budget > A self-hosted provider with no cost is treated as free: its calls never count against any virtual key's budget. To change the cost later, remove the provider and add it again. ## Remove a provider Delete the provider in **Settings โ†’ Inference Gateway โ†’ Providers**. Virtual keys that list it can no longer reach its models; requests to them fail, or go to a fallback if the request names one. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/virtual-keys === Issue Inference Gateway keys with budgets, rate limits, model allowlists, and fallbacks. # Virtual keys A virtual key (`sk-un-...`) is the credential every caller presents to the gateway. Give each team, app, or developer their own key. For example, the support bot gets a key limited to `claude-sonnet-4-5` with a $200 monthly budget, and the research team gets a key for any model with $2,000 a month. Neither ever sees a provider API key, and revoking one key affects no one else. ## Issue a key 1. Open **Settings โ†’ Inference Gateway โ†’ Virtual keys** and issue a new key. 2. Fill in the key: | Field | Meaning | |---|---| | **Name** | Who or what the key is for, for example `ml-platform-team`. | | **Description** | Optional. | | **Providers** | The providers this key may use. Selecting none allows all of them. | | **Allowed models** | A comma-separated allowlist, for example `gpt-4.1-mini, claude-sonnet-4-5`. Leave it empty to allow every model. | | **Fallbacks** | An ordered list of provider and model pairs to try when the primary fails. See **Inference > Inference Gateway > Virtual keys > Fallbacks**. | | **Budget (USD)** | The most the key may spend per day, week, or month. Empty means unlimited. | | **Rate limit (req/min)** | The most requests the key may send per minute. Empty means unlimited. | 3. Copy the key value from the confirmation dialog and store it where the caller reads it, for example as a Union secret: ```bash flyte create secret support-bot-llm-key --value sk-un-... ``` Callers send the key the way any OpenAI-compatible client sends an API key, as `Authorization: Bearer sk-un-...`. ## Budgets A budget is a dollar ceiling per window: per day, per week, or per month. The gateway keeps a running total for each key and rejects calls with `402` as soon as the ceiling is reached. The total resets at the start of each window. Spend is computed from token counts and each provider's price. A self-hosted provider with no cost set is not metered. See **Inference > Inference Gateway > Providers**. For how replicas and restarts affect the running total, see **Inference > Inference Gateway > Deploy the gateway > Size the gateway**. ## Fallbacks Fallbacks keep a caller working when its primary model fails. A request names an ordered list of `provider/model` strings. If the primary call fails, the gateway tries each fallback in turn until one succeeds. The caller sends the list with each request, in the `fallbacks` field of the request body. With the OpenAI Python SDK: ```python response = client.chat.completions.create( model="openai/gpt-4.1-mini", messages=[{"role": "user", "content": "Summarize this ticket."}], extra_body={"fallbacks": ["anthropic/claude-haiku-4-5", "bedrock/amazon.nova-lite-v1:0"]}, ) ``` The **Fallbacks** list on a key records the chain that key's callers should send. Each entry must use one of the key's providers. The gateway does not add the list to requests on its own. Fallbacks cover: - provider errors and outages, and - rejections by the key's own policy, such as a primary model that is not on the key's allowlist. A guardrail block is never retried on a fallback. A prompt your guardrail refuses is refused for every model. ## Attribute spend with custom dimensions Add `x-un-dim-` headers to tag requests, for example `x-un-dim-team: search` or `x-un-dim-customer: acme`. The gateway records the values with each request's usage and passes them to guardrails as `metadata`. Use them to break down the spend of one key, without issuing more keys. ## Errors | Status | Meaning | |---|---| | `401` | The request has no virtual key, or the key is unknown or revoked. | | `402` | The key has reached its budget for the current window. | | `403` `model_blocked` | The model is not on the key's allowlist. | | `403` `guardrail_blocked` | A guardrail refused the prompt or the answer. See [Guardrails](./guardrails/_index). | | `503` `guardrail_unavailable` | A guardrail could not be reached and is set to block on failure. | A request that exceeds the key's rate limit is rejected until the minute window resets. ## Change or revoke a key Keys can't be edited. To change a key's providers, models, fallbacks, budget, or rate limit, issue a new key with the settings you want, update the callers' secret, then revoke the old key. Revoking a key in **Settings โ†’ Inference Gateway โ†’ Virtual keys** takes effect on the gateway within about 15 seconds. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/use-from-tasks-and-apps === Call models through the Inference Gateway from tasks and apps running on Union. # Use from tasks and apps Tasks and apps on any of your Union clusters call the gateway like any OpenAI-compatible API: set the base URL to the gateway's endpoint and pass a virtual key as the API key. A summarization task, a RAG app, and an agent all share one endpoint, and each gets its own budget through its own key. ## Prerequisites - A deployed gateway and its endpoint, from **Settings โ†’ Inference Gateway**. See **Inference > Inference Gateway > Deploy the gateway**. - A **Inference > Inference Gateway > Virtual keys** for the task or app, stored as a Union secret: ```bash flyte create secret llm-gateway-key --value sk-un-... ``` ## Call the gateway from a task Mount the secret on the environment: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.10.1", # "openai>=1.60", # ] # /// """Call models through the Union LLM gateway from a task.""" import os import pathlib import flyte # {{docs-fragment env}} # The gateway's endpoint, from Settings > LLM Gateway in the Union console. GATEWAY_URL = "https://" env = flyte.TaskEnvironment( name="llm-gateway-task", image=flyte.Image.from_debian_base().with_pip_packages("openai"), # Store the virtual key once with: flyte create secret llm-gateway-key sk-un-... secrets=flyte.Secret(key="llm-gateway-key", as_env_var="LLM_GATEWAY_KEY"), ) # {{/docs-fragment env}} # {{docs-fragment task}} @env.task async def summarize(text: str) -> str: from openai import AsyncOpenAI client = AsyncOpenAI(base_url=f"{GATEWAY_URL}/v1", api_key=os.environ["LLM_GATEWAY_KEY"]) response = await client.chat.completions.create( # Models are addressed as provider/model. model="openai/gpt-4.1-mini", messages=[{"role": "user", "content": f"Summarize in one sentence:\n\n{text}"}], # Tried in order if the primary model fails or is rejected for this key. extra_body={"fallbacks": ["anthropic/claude-haiku-4-5"]}, ) return response.choices[0].message.content # {{/docs-fragment task}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(summarize, text="Flyte is a workflow orchestrator for data and ML pipelines.") print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/llm-gateway/call_from_task.py* Then point the client at the gateway. Address models as `provider/model`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.10.1", # "openai>=1.60", # ] # /// """Call models through the Union LLM gateway from a task.""" import os import pathlib import flyte # {{docs-fragment env}} # The gateway's endpoint, from Settings > LLM Gateway in the Union console. GATEWAY_URL = "https://" env = flyte.TaskEnvironment( name="llm-gateway-task", image=flyte.Image.from_debian_base().with_pip_packages("openai"), # Store the virtual key once with: flyte create secret llm-gateway-key sk-un-... secrets=flyte.Secret(key="llm-gateway-key", as_env_var="LLM_GATEWAY_KEY"), ) # {{/docs-fragment env}} # {{docs-fragment task}} @env.task async def summarize(text: str) -> str: from openai import AsyncOpenAI client = AsyncOpenAI(base_url=f"{GATEWAY_URL}/v1", api_key=os.environ["LLM_GATEWAY_KEY"]) response = await client.chat.completions.create( # Models are addressed as provider/model. model="openai/gpt-4.1-mini", messages=[{"role": "user", "content": f"Summarize in one sentence:\n\n{text}"}], # Tried in order if the primary model fails or is rejected for this key. extra_body={"fallbacks": ["anthropic/claude-haiku-4-5"]}, ) return response.choices[0].message.content # {{/docs-fragment task}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(summarize, text="Flyte is a workflow orchestrator for data and ML pipelines.") print(run.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/llm-gateway/call_from_task.py* The `fallbacks` list is optional. If `openai/gpt-4.1-mini` fails, the gateway retries the call on `anthropic/claude-haiku-4-5`. See **Inference > Inference Gateway > Virtual keys > Fallbacks**. ## Call the gateway from an app Apps use the same pattern. This FastAPI app has its own key, so its budget and allowed models are separate from every task's. The `x-un-dim-app` header tags its requests for **Inference > Inference Gateway > Virtual keys > Attribute spend with custom dimensions**: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.10.1", # "openai>=1.60", # "fastapi", # "uvicorn", # ] # /// """Call models through the Union LLM gateway from an app.""" import os import pathlib import flyte from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment GATEWAY_URL = "https://" # {{docs-fragment app}} app = FastAPI() @app.get("/ask") async def ask(question: str) -> dict[str, str]: from openai import AsyncOpenAI client = AsyncOpenAI( base_url=f"{GATEWAY_URL}/v1", api_key=os.environ["LLM_GATEWAY_KEY"], # Tag requests so the console can break down spend by app. default_headers={"x-un-dim-app": "support-bot"}, ) response = await client.chat.completions.create( model="anthropic/claude-sonnet-4-5", messages=[{"role": "user", "content": question}], ) return {"answer": response.choices[0].message.content} env = FastAPIAppEnvironment( name="support-bot", app=app, image=flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "openai"), # Each app gets its own virtual key, so its budget and allowed models are its own. secrets=flyte.Secret(key="support-bot-llm-key", as_env_var="LLM_GATEWAY_KEY"), ) # {{/docs-fragment app}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployed = flyte.serve(env) print(deployed.url) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/llm-gateway/call_from_app.py* ## Use other clients Any client that speaks the OpenAI API works against the gateway's `/v1` base URL: - **Anthropic models through the OpenAI SDK.** Use `model="anthropic/"`. The gateway translates the request. - **LiteLLM.** Use the `openai/` prefix so LiteLLM sends an OpenAI-format request, set `api_base` to the gateway's `/v1` URL, and pass the virtual key as `api_key`. - **LangChain.** Use `ChatOpenAI(base_url=..., api_key=..., model="provider/model")`. - **curl.** ```bash curl https:///v1/chat/completions \ -H "Authorization: Bearer $LLM_GATEWAY_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "openai/gpt-4.1-mini", "messages": [{"role": "user", "content": "Hello"}]}' ``` List the models a key can reach with `GET /v1/models`. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/use-from-laptop === Reach the Inference Gateway from local tools, either through a public endpoint or behind Union sign-in with flyte proxy app. # Use from your laptop Developers use the same gateway from their laptops as production does: notebooks, scripts, coding assistants, and any tool that accepts an OpenAI-compatible base URL. Local experiments then draw on the same budgets, appear in the same usage view, and pass through the same guardrails as production traffic. How a laptop reaches the gateway depends on the gateway's access mode. See **Inference > Inference Gateway > Deploy the gateway > Choose who can reach the gateway**. | | Public endpoint | Behind Union sign-in | |---|---|---| | **Allow anonymous access** | Checked | Unchecked | | Credentials a caller needs | A virtual key | A Union sign-in and a virtual key | | Base URL on the laptop | The gateway's endpoint | `http://127.0.0.1:8600`, through `flyte proxy app` | | If a virtual key leaks | Anyone on the internet can spend it, up to its budget, until you revoke it | It is useless without a Union sign-in | ## Public endpoint When anonymous access is allowed, the gateway's endpoint is reachable from anywhere and the virtual key works like a provider API key. Configure any tool with the endpoint and the key: ```bash export OPENAI_BASE_URL=https:///v1 export OPENAI_API_KEY=sk-un-... ``` ```python from openai import OpenAI client = OpenAI() # reads OPENAI_BASE_URL and OPENAI_API_KEY response = client.chat.completions.create( model="openai/gpt-4.1-mini", messages=[{"role": "user", "content": "Hello"}], ) ``` This mode is the simplest, and it suits tools that can only send an API key. The virtual key is the only thing standing between the internet and your spend. Give laptop keys small budgets and only the models they need, and revoke a key as soon as you suspect it leaked. ## Behind Union sign-in When anonymous access is off, only callers signed in to Union reach the gateway. A standard OpenAI client can't do that on its own: it sends the virtual key in the `Authorization` header, which is the header Union sign-in uses. `flyte proxy app` (in `flyte` 2.10.1 or later) solves this. It opens a local port that forwards to the gateway, adding your Union credential to every request: ```bash flyte proxy app --url https:// --port 8600 ``` You can also pass the gateway's app name instead of `--url`. The proxy runs in the foreground; stop it with Ctrl-C. Then point any tool at the local port and keep using your virtual key as the API key: ```bash export OPENAI_BASE_URL=http://127.0.0.1:8600/v1 export OPENAI_API_KEY=sk-un-... ``` ```bash curl http://127.0.0.1:8600/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "openai/gpt-4.1-mini", "messages": [{"role": "user", "content": "Hello"}]}' ``` On each request, the proxy: - moves an `Authorization: Bearer sk-un-...` virtual key into the header the gateway reads it from, so the key still identifies the caller and its budget applies, - adds your Union credential, using the same sign-in as the `flyte` CLI, and - refreshes the credential when it expires and retries the request once. Responses stream back unchanged, so streaming completions work. ### Proxy options | Option | Default | Meaning | |---|---|---| | `NAME` | | The gateway's app name. Use `--url` instead to give the endpoint directly. | | `--url` | | The gateway's endpoint. | | `--port` | `8600` | The local port. `0` picks a free one. | | `--address` | `127.0.0.1` | The local address to listen on. | | `--emit-mcp-config` | | Print an MCP client configuration that points at the local port. | | `-v`, `--verbose` | | Log each request. Credentials are never logged. | > [!WARNING] Keep the proxy on localhost > Anyone who can reach the proxy's port uses the gateway with your Union identity. Leave `--address` at `127.0.0.1` unless you mean to share it, and the proxy warns if you bind it to any other address. See the **Flyte CLI > flyte proxy > flyte proxy app** for every option. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/guardrails === Check every prompt before it reaches a model, and every answer before it reaches the caller, with your own code. # Guardrails A guardrail is your own code, run by the gateway around every model call. Use one to keep personal data out of third-party models, to withhold answers that leak credentials, to refuse off-limits topics, or to answer common questions from your own cache without paying for a model call. Guardrails are global. One guardrail applies to every virtual key on the gateway, so a new team or app is covered from its first request. ## How guardrails work A gateway has at most two guardrails: - **Pre-call**, run before the model. It sees the prompt and returns one of three verdicts: - **pass**: the call goes to the model. - **fail**: the call is refused, and the model is never called. - **cache hit**: the guardrail supplies the answer itself, and the model is never called. - **Post-call**, run after the model. It sees the answer and returns one of two verdicts: - **pass**: the answer goes to the caller. - **fail**: the answer is withheld. A refused call returns `403` with error type `guardrail_blocked` and the message your guardrail chose. A refused call is never retried on a **Inference > Inference Gateway > Virtual keys > Fallbacks**. A guardrail can't rewrite a prompt or an answer. To redact rather than refuse, have the pre-call guardrail fail with a message that tells the caller what to remove. Each guardrail is a Union app of type `Guardrail`, running on the gateway's cluster. The gateway calls it over the cluster-local network with a plain HTTP request, so you can write it in any language: - **Python:** use `GuardrailAppEnvironment` from `flyteplugins-union` 0.19.1 or later. Write a function that returns a verdict; the class handles the HTTP side. See **Inference > Inference Gateway > Guardrails > Python guardrails**. - **Any other language:** implement two HTTP endpoints. See **Inference > Inference Gateway > Guardrails > Guardrail protocol**. ## Register a guardrail 1. Deploy the guardrail app on the gateway's cluster. 2. Open **Settings โ†’ Inference Gateway โ†’ Guardrails**, and choose the pre-call or post-call stage. 3. Fill in the guardrail: | Field | Meaning | |---|---| | **Guardrail app** | The app to call. The list shows apps of type `Guardrail` on the gateway's cluster in any state; a gray dot marks an app that isn't active. Saving fails for an app that has never been placed on a cluster, but succeeds for one that has failed or stopped, so check that the app is active. | | **Timeout (ms)** | How long the gateway waits for a verdict. Defaults to 5,000. At most 30,000. | | **Fail open** | What happens when the guardrail can't answer. See **Inference > Inference Gateway > Guardrails > When a guardrail fails**. | The gateway picks up the guardrail within about 15 seconds. To use one app for both stages, register it under each stage. ## When a guardrail fails A guardrail *fails* when it times out, returns a status other than `200`, or returns a body the gateway can't read. What happens next depends on **Fail open**: | Fail open | Effect | Use it when | |---|---|---| | Off (default) | The call is refused with `503` `guardrail_unavailable`. | The guardrail enforces a rule you can't break, such as keeping personal data in-house. | | On | The call proceeds as if the guardrail returned pass. The failure is recorded. | The guardrail is advisory, and availability matters more. | Every guardrail outcome other than pass is recorded with the request's usage, with the `reason` your guardrail returned, so blocks per key show up in the console. ## What guardrails see - **Request types.** Chat completions, text completions, the Responses API, and, on the pre-call stage only, decisions. Embeddings, audio, and image requests are never sent to a guardrail. - **Messages.** The pre-call stage gets the conversation as a flat list of text messages. The post-call stage gets the answer text, and not the prompt. If a post-call check needs the prompt, look it up by `request_id` from state your pre-call check saved. - **Caller context.** The virtual key's ID and name, the provider and model, and the caller's **Inference > Inference Gateway > Virtual keys > Attribute spend with custom dimensions**. ## Streaming For a streamed answer, the post-call check runs once, on the full text, after the last chunk. Chunks already sent to the caller can't be recalled: a fail ends the stream with an error event, after the text that was already delivered. If your post-call guardrail must stop text from ever reaching the caller, have callers turn off streaming. The gateway buffers at most 1 MiB of text per stream and 64 MiB across all streams on a replica. To change both limits, click **Edit** at the top of the gateway's page and set **Stream buffering**. Past either limit, the check sees a prefix of the answer with `truncated` set. A cache hit on a streamed request is delivered as a single chunk. ## Keep guardrails fast Every guarded call waits for the guardrail, so its latency adds to every request. Keep checks in memory where you can, keep at least one replica running so calls never wait for a cold start, and set the timeout close to your guardrail's real worst case. {{< subpage-cards >}} ## Subpages - **Inference > Inference Gateway > Guardrails > Python guardrails** - Write an Inference Gateway guardrail as a Python function with GuardrailAppEnvironment. - **Inference > Inference Gateway > Guardrails > Guardrail protocol** - The HTTP contract between the Inference Gateway and a guardrail, for writing guardrails in any language. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/guardrails/python-guardrails === Write an Inference Gateway guardrail as a Python function with GuardrailAppEnvironment. # Python guardrails `GuardrailAppEnvironment` turns a Python function into a guardrail app. You write a function that takes the request and returns a verdict. The class serves the HTTP endpoints the gateway calls, and gives the app the `Guardrail` type the console looks for. ## Install ```bash pip install 'flyteplugins-union[guardrails]>=0.19.1' ``` Requires `flyteplugins-union` 0.19.1 or later. The `guardrails` extra adds FastAPI and uvicorn. ## Write a pre-call guardrail This guardrail refuses prompts that contain a Social Security number or an email address, and answers one known question from a cache: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.10.1", # "flyteplugins-union[guardrails]>=0.19.1", # ] # /// """A pre-call guardrail that blocks personal data and answers known questions from a cache.""" import pathlib import re import flyte from flyteplugins.union.guardrails import GuardrailAppEnvironment, GuardrailRequest, Verdict # {{docs-fragment checks}} SSN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b") EMAIL = re.compile(r"\b[\w.%+-]+@[\w.-]+\.[A-Za-z]{2,}\b") # Questions answered without calling a model. CACHE = { "what is our refund window?": "Refunds are accepted within 30 days of purchase.", } def check_prompt(request: GuardrailRequest) -> Verdict: prompt = request.last_user_message() if SSN.search(prompt): return Verdict.block("Remove the Social Security number and try again.", reason="pii_ssn") if EMAIL.search(prompt): return Verdict.block("Remove the email address and try again.", reason="pii_email") if answer := CACHE.get(prompt.strip().lower()): return Verdict.cached(answer) return Verdict.allow() # {{/docs-fragment checks}} # {{docs-fragment env}} env = GuardrailAppEnvironment( name="pii-guardrail", pre=check_prompt, resources=flyte.Resources(cpu=1, memory="512Mi"), # Keep a replica warm: every guarded call waits on this app. scaling=flyte.app.Scaling(replicas=(1, 4)), ) # {{/docs-fragment env}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployed = flyte.deploy(env) print(deployed) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/llm-gateway/pii_guardrail.py* A check receives a `GuardrailRequest` and returns a `Verdict`: | Return | Effect | |---|---| | `Verdict.allow()` | The call proceeds. | | `Verdict.block(message, reason)` | The caller gets `403` `guardrail_blocked` with `message`. `reason` is a short label recorded with the request's usage. | | `Verdict.cached(content)` | The caller gets `content` as the model's answer, and the model is never called. Pre-call stage only. | `reason` must be lowercase letters, digits, `_`, or `-`, up to 64 characters, for example `pii_ssn`. It is recorded, so it must never contain user content. `Verdict.block()` raises `ValueError` for any other value. `message` is shown to the caller and is not recorded. `GuardrailRequest` carries the fields described in the **Inference > Inference Gateway > Guardrails > Guardrail protocol > Request**, plus two helpers: - `last_user_message()` returns the most recent `user` message. - `text()` returns the text the stage is about: all message content on the pre-call stage, the model's answer on the post-call stage. ## Deploy it Wrap the check in a `GuardrailAppEnvironment`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.10.1", # "flyteplugins-union[guardrails]>=0.19.1", # ] # /// """A pre-call guardrail that blocks personal data and answers known questions from a cache.""" import pathlib import re import flyte from flyteplugins.union.guardrails import GuardrailAppEnvironment, GuardrailRequest, Verdict # {{docs-fragment checks}} SSN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b") EMAIL = re.compile(r"\b[\w.%+-]+@[\w.-]+\.[A-Za-z]{2,}\b") # Questions answered without calling a model. CACHE = { "what is our refund window?": "Refunds are accepted within 30 days of purchase.", } def check_prompt(request: GuardrailRequest) -> Verdict: prompt = request.last_user_message() if SSN.search(prompt): return Verdict.block("Remove the Social Security number and try again.", reason="pii_ssn") if EMAIL.search(prompt): return Verdict.block("Remove the email address and try again.", reason="pii_email") if answer := CACHE.get(prompt.strip().lower()): return Verdict.cached(answer) return Verdict.allow() # {{/docs-fragment checks}} # {{docs-fragment env}} env = GuardrailAppEnvironment( name="pii-guardrail", pre=check_prompt, resources=flyte.Resources(cpu=1, memory="512Mi"), # Keep a replica warm: every guarded call waits on this app. scaling=flyte.app.Scaling(replicas=(1, 4)), ) # {{/docs-fragment env}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployed = flyte.deploy(env) print(deployed) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/llm-gateway/pii_guardrail.py* `GuardrailAppEnvironment` accepts every `flyte.app.AppEnvironment` option, such as `resources`, `scaling`, `secrets`, and `image`. The default image installs `flyteplugins-union[guardrails]`. If your checks need more packages, pass your own image and include `flyteplugins-union[guardrails]>=0.19.1` in it. Deploy it on the gateway's cluster: ```bash flyte deploy pii_guardrail.py env ``` Then [register it](./_index#register-a-guardrail) in **Settings โ†’ Inference Gateway โ†’ Guardrails** as the pre-call guardrail. Leave `requires_auth` at its default. The gateway reaches the app over the cluster-local network and never goes through the app's public endpoint. ## Check answers after the model Pass a `post` function to check the model's answer. One app can serve both stages. Checks can be `async`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.10.1", # "flyteplugins-union[guardrails]>=0.19.1", # ] # /// """A guardrail with both stages: block leaked credentials in prompts and in answers.""" import pathlib import re import flyte from flyteplugins.union.guardrails import GuardrailAppEnvironment, GuardrailRequest, Verdict # {{docs-fragment checks}} # AWS access key IDs and PEM private keys. CREDENTIAL = re.compile(r"\bAKIA[0-9A-Z]{16}\b|-----BEGIN [A-Z ]*PRIVATE KEY-----") async def check_prompt(request: GuardrailRequest) -> Verdict: if CREDENTIAL.search(request.text()): return Verdict.block("Prompts may not contain credentials.", reason="credential_in_prompt") return Verdict.allow() async def check_answer(request: GuardrailRequest) -> Verdict: # On the post stage, request.text() is the model's answer. if CREDENTIAL.search(request.text()): return Verdict.block("The answer contained a credential and was withheld.", reason="credential_in_answer") return Verdict.allow() env = GuardrailAppEnvironment( name="credential-guardrail", pre=check_prompt, post=check_answer, scaling=flyte.app.Scaling(replicas=(1, 4)), ) # {{/docs-fragment checks}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) print(flyte.deploy(env)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/llm-gateway/post_guardrail.py* Register the app under both stages to use both checks. A stage with no function returns pass. ## Add guardrail routes to an existing FastAPI app If you already run a FastAPI app, mount the guardrail routes on it with `guardrail_router()`, and give the environment the `Guardrail` type: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.10.1", # "flyteplugins-union[guardrails]>=0.19.1", # ] # /// """Add guardrail routes to a FastAPI app you already have.""" import pathlib import flyte from fastapi import FastAPI from flyte.app.extras import FastAPIAppEnvironment from flyteplugins.union.guardrails import GuardrailRequest, Verdict, guardrail_router BANNED_TOPICS = ("competitor pricing", "unreleased roadmap") def check_prompt(request: GuardrailRequest) -> Verdict: prompt = request.last_user_message().lower() for topic in BANNED_TOPICS: if topic in prompt: return Verdict.block(f"Questions about {topic} are not allowed.", reason="banned_topic") return Verdict.allow() # {{docs-fragment router}} app = FastAPI() @app.get("/topics") def topics() -> list[str]: return list(BANNED_TOPICS) app.include_router(guardrail_router(pre=check_prompt)) env = FastAPIAppEnvironment( name="topic-guardrail", app=app, # The gateway only accepts apps of type "Guardrail" as guardrails. type="Guardrail", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-union[guardrails]>=0.19.1"), ) # {{/docs-fragment router}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) print(flyte.deploy(env)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/llm-gateway/fastapi_guardrail.py* `GuardrailAppEnvironment` also accepts an existing app, as `app=`, and adds the routes to it. ## Test locally The guardrail is an ordinary FastAPI app, so you can test it without deploying, using FastAPI's test client: ```python from fastapi.testclient import TestClient from pii_guardrail import env client = TestClient(env.app) verdict = client.post( "/guardrail/pre", json={"stage": "pre", "input": {"messages": [{"role": "user", "content": "My SSN is 123-45-6789"}]}}, ).json() assert verdict["decision"] == "fail" ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/guardrails/protocol === The HTTP contract between the Inference Gateway and a guardrail, for writing guardrails in any language. # Guardrail protocol A guardrail is an HTTP server with two endpoints. The gateway sends each one a JSON description of the call and reads back a JSON verdict. Implement this contract in any language: reuse a Go policy engine your security team already runs, or a Node service that calls a moderation model. For Python, `GuardrailAppEnvironment` implements this contract for you. See **Inference > Inference Gateway > Guardrails > Python guardrails**. ## Endpoints | Method and path | Called | |---|---| | `POST /guardrail/pre` | Before the model, if the app is the pre-call guardrail. | | `POST /guardrail/post` | After the model, if the app is the post-call guardrail. | | `GET /guardrail/health` | Optional. The gateway never calls it. Use it for your own probes. | The gateway sends `Content-Type: application/json` and no credentials. It reaches the app over the cluster-local network, never through the app's public endpoint. Return `200` with a verdict for every check, including a block. Any other status is a [guardrail failure](./_index#when-a-guardrail-fails), not a block. ## Request Both endpoints receive the same envelope. Ignore fields you don't recognize, because the gateway may add new ones. | Field | Type | Meaning | |---|---|---| | `request_id` | string | The gateway's ID for the call. The same on the pre-call and post-call checks of one call. | | `stage` | string | `pre` or `post`. | | `virtual_key` | object | `{"id": ..., "name": ...}` of the caller's virtual key. | | `provider` | string | The provider the call is routed to, for example `openai`. | | `model` | string | The model, without the provider prefix, for example `gpt-4.1-mini`. | | `request_type` | string | `chat_completion`, `text_completion`, `responses`, or, on the pre-call stage only, `decisions`. | | `stream` | boolean | Whether the caller asked for a streamed answer. | | `input.messages` | array | The conversation as `{"role", "content"}` objects, with `content` flattened to text. Empty on the post-call stage. | | `output` | object | The model's answer. Post-call stage only. See below. | | `metadata` | object | The caller's `x-un-dim-` header values, keyed by ``. | `output` has these fields: | Field | Type | Meaning | |---|---|---| | `content` | string | The answer text. For a streamed answer, the full accumulated text. | | `finish_reason` | string | The model's finish reason, for example `stop`. | | `response` | object | The full OpenAI `chat.completion` object. Non-streamed chat completions only. | | `truncated` | boolean | `true` if a streamed answer outgrew the gateway's buffer and `content` is a prefix. | How inputs become messages: - Chat content blocks are joined with newlines. - A text completion becomes one `user` message. - A Responses API input maps each item's text to a message. - A decision becomes a `system` message holding its questions as JSON, followed by a `user` message holding its state. A pre-call request: ```json { "request_id": "b3f4c2d1", "stage": "pre", "virtual_key": {"id": "vk_7d2a", "name": "support-bot"}, "provider": "openai", "model": "gpt-4.1-mini", "request_type": "chat_completion", "stream": false, "input": { "messages": [ {"role": "system", "content": "You are a support assistant."}, {"role": "user", "content": "What is our refund window?"} ] }, "metadata": {"team": "support"} } ``` A post-call request: ```json { "request_id": "b3f4c2d1", "stage": "post", "virtual_key": {"id": "vk_7d2a", "name": "support-bot"}, "provider": "openai", "model": "gpt-4.1-mini", "request_type": "chat_completion", "stream": true, "input": {"messages": []}, "output": {"content": "Refunds are accepted within 30 days.", "finish_reason": "stop"}, "metadata": {"team": "support"} } ``` ## Verdict | Field | Type | Meaning | |---|---|---| | `decision` | string | `pass`, `fail`, or, on the pre-call stage only, `cache_hit`. Required. | | `message` | string | On `fail`, the message shown to the caller. Not recorded. Defaults to `Request blocked by guardrail`. | | `reason` | string | On `fail`, a short label recorded with the request's usage. Must match `^[a-z0-9_-]{1,64}$`. Any other value is dropped. Never put user content in it. | | `response` | object | On `cache_hit`, the answer to return, as an OpenAI `chat.completion` object. | ```json {"decision": "pass"} ``` ```json {"decision": "fail", "message": "Remove the email address and try again.", "reason": "pii_email"} ``` ```json { "decision": "cache_hit", "response": { "choices": [ {"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "Refunds are accepted within 30 days."}} ] } } ``` The gateway fills in `id`, `object`, `model`, `created`, and an empty `usage` if the `cache_hit` response leaves them out, so `choices[0].message` is the minimum. Rules: - `cache_hit` is honored for chat completions only. For other request types it counts as `pass`. - A `cache_hit` response the gateway can't use is ignored, and the call proceeds to the model. - A missing, empty, or unknown `decision` is a guardrail failure. - The response body may be at most 4 MiB. - The gateway waits for the registered timeout: 5 seconds by default, at most 30 seconds. ## Example: a guardrail in Go This guardrail refuses prompts that contain an AWS access key ID: ```go package main import ( "encoding/json" "net/http" "regexp" ) var awsKey = regexp.MustCompile(`\bAKIA[0-9A-Z]{16}\b`) type message struct { Role string `json:"role"` Content string `json:"content"` } type request struct { Stage string `json:"stage"` Input struct { Messages []message `json:"messages"` } `json:"input"` } type verdict struct { Decision string `json:"decision"` Message string `json:"message,omitempty"` Reason string `json:"reason,omitempty"` } func pre(w http.ResponseWriter, r *http.Request) { var req request if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } v := verdict{Decision: "pass"} for _, m := range req.Input.Messages { if awsKey.MatchString(m.Content) { v = verdict{Decision: "fail", Message: "Prompts may not contain AWS keys.", Reason: "aws_key"} break } } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(v) } func main() { http.HandleFunc("POST /guardrail/pre", pre) http.HandleFunc("GET /guardrail/health", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"status":"ok"}`)) }) http.ListenAndServe(":8080", nil) } ``` ## Deploy a guardrail in any language Build the server into a container image, then deploy it as an app of type `Guardrail`. The type is what makes the app selectable as a guardrail in the console: ```python import flyte import flyte.app env = flyte.app.AppEnvironment( name="aws-key-guardrail", type="Guardrail", image="/aws-key-guardrail:1.0.0", # The server's start command inside the image. Set it, because the image doesn't contain flyte. command=["/usr/local/bin/aws-key-guardrail"], port=8080, scaling=flyte.app.Scaling(replicas=(1, 4)), ) ``` ```bash flyte deploy guardrail_app.py env ``` Deploy it on the gateway's cluster, then [register it](./_index#register-a-guardrail). === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/inference-gateway/decisions === Send a state and named questions to the Inference Gateway's POST /v1/decisions endpoint and get a typed answer to each. # Decisions `POST /v1/decisions` asks a model several typed questions about one piece of state in a single call. Each named question gets its own answer: a probability or a chosen option. Use it for the narrow judgments described in [Decision models](../decision-models/_index), such as routing, moderation, and guards, through the same endpoint and virtual keys as the rest of your model traffic. ## Call the endpoint ```bash curl https:///v1/decisions \ -H "Authorization: Bearer sk-un-..." \ -H "Content-Type: application/json" \ -d '{ "model": "typesafe/", "state": "Customer: I was charged twice for one order.", "questions": { "is_billing": { "kind": "noul", "instructions": "Is this a billing issue?" }, "urgency": { "kind": "choice", "instructions": "How urgent is it?", "criteria": { "low": "can wait", "high": "reply today" } } } }' ``` If the gateway is behind Union sign-in, run `flyte proxy app` first and call `http://127.0.0.1:8600/v1/decisions` instead. See **Inference > Inference Gateway > Use from your laptop**. Replace `` with your gateway's endpoint from **Settings โ†’ Inference Gateway**, `sk-un-...` with a virtual key, and `` with a model your `typesafe` provider allows. When the gateway has a deployed `typesafe` provider, or a vLLM or SGLang provider with **Answers decisions** on, the gateway's overview in **Settings โ†’ Inference Gateway** shows this command with your endpoint and a model filled in. ## The request | Field | Meaning | |---|---| | `model` | The `provider/model` that answers, for example `typesafe/` or `qwen/qwen3-8b`. The provider must answer decisions; see **Inference > Inference Gateway > Decisions > Which providers answer decisions**. | | `state` | The text the questions are about. | | `questions` | The questions, keyed by name. | Each question has a `kind` and `instructions`, the question itself: | `kind` | Answer | `criteria` | |---|---|---| | `noul` | A probability. | Not needed. | | `choice` | One of the options. | A mapping of each option to a description of when it applies. | ## Which providers answer decisions | Provider | Answers decisions | |---|---| | `typesafe` | Yes. TypeSafe's decision models answer decisions only, not chat or completions. | | Hosted LLM providers | Chat models that support tool calling. The gateway asks the model through one forced tool call. | | vLLM and SGLang apps | Only when the provider was added with **Answers decisions** on. The gateway asks the model through one forced tool call on chat completions, so the model must support tool calling. With the setting off, the gateway refuses decision requests for that provider. See **Inference > Inference Gateway > Providers > Add a self-hosted model**. | A gateway on an older image may not serve `/v1/decisions`. If the gateway's overview shows an update available, redeploy the gateway. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/decision-models === Answer many typed questions in one call, with calibrated confidence, and decide what happens next in code. # Decision models Most of what a program asks a model is not open-ended: - "Is this request hostile?" - "Which of these five intents is it?" - "Does this record mention a deadline?" - "Is there enough information to answer yet?" A knowledgeable person answers each of those in a couple of seconds, and none of them need prose. A **System One model** is built for exactly that shape. You give it some state and a set of typed questions; it answers them in parallel, in isolation from each other, and attaches a calibrated probability to every answer. It never writes text. The property worth designing around is that **adding questions barely changes the response time**. The eleventh question costs almost nothing, so the right move is to ask everything at once โ€” including the questions you will not branch on โ€” and compose the result in ordinary Python. ## The types Those answers arrive as three types, each carrying its value *and* the model's calibrated confidence in it. They are ordinary Python objects: you declare them in a dataclass, get real instances back, and branch on them directly. | Type | Holds | You branch with | |---|---|---| | `Choice` | the picked member of your enum, plus the whole probability distribution | `.certain(threshold)` | | `Score` | the picked rung of your ordered `IntEnum`, plus where on the scale it actually landed | `.at_least(rung)` | | `Noul` | truthfulness in 0..1 | `.at(threshold)` | They register with Flyte's type engine, so they also work as task inputs and outputs โ€” a classification step can be its own cached, retryable task. **Inference > Decision models > Typed decisions with Jev** covers all three in full. ## The battery Those types are the fields. A **battery** is the whole set of questions you ask in one call, declared as one dataclass โ€” the word borrowed from psychometrics, where a test battery is a set of tests administered together in a single sitting. Here the sitting is a single request. The distinction worth holding onto is that a battery is **a type, not a prompt**. That is what makes it behave like the rest of your Flyte code: - **It is an ordinary dataclass**, so it crosses a task boundary as a struct. A task can return a battery, take one as an input, and pass it to the next step with nothing registered and nothing to parse. - **Its fields are the questions.** Adding one is adding a field, so it lands in the task's interface and in the diff, where a reviewer sees it โ€” not in an edited string that nothing type-checks. - **It is the unit of one request.** One battery is one call no matter how many fields it has, which is exactly why the eleventh question is nearly free. That last point leaves two axes of parallelism in play, and they are worth telling apart: the battery fans out *inside* one call, while Flyte fans out *across* calls โ€” one durable task per record, each asking its own battery once. Widening the battery costs almost nothing; widening the fan-out costs more containers. Concretely, with **Inference > Decision models > Typed decisions with Jev**: ```python import enum from dataclasses import dataclass, field from flyteplugins.typesafe_ai import Choice, Noul, Score, ask class Intent(enum.Enum): """What is this customer asking for?""" REFUND = "refund" """they want money back for something already paid for""" DELIVERY = "delivery status" """they are asking where an order is""" class Severity(enum.IntEnum): """How badly is this customer blocked?""" NONE = 0 MINOR = 1 BLOCKING = 2 @dataclass class Triage: """The battery. Each field is one question; the whole class is one request.""" intent: Choice[Intent] severity: Score[Severity] hostile: Noul = field(metadata={"question": "Is the customer hostile?"}) t: Triage = await ask(Triage, {"ticket": ticket}) if t.hostile.at(0.8): # a threshold you chose route = "escalate" elif t.intent.value is Intent.REFUND: # a real enum member route = "refunds" if t.severity.at_least(Severity.BLOCKING) else "queue" ``` The enums carry their own questions โ€” a class docstring is the question, a member docstring is the criterion โ€” so only `hostile` needs metadata, because a yes/no has no vocabulary to describe itself with. Adding a fourth field would add a fourth answer and still be one call. ## Two models, two jobs A generative model is the System 2 half: open-ended reasoning, and prose a person reads. It is expensive, sequential, and has to emit every field one token at a time. Pointing it at a yes/no question means paying for a generation plus a parser to get the answer back out. ```mermaid flowchart LR S1(["System One"]) -->|"typed answers,
in parallel"| A["guards, routing, labels,
thresholds, stop conditions"] S2(["System 2"]) -->|"open-ended
reasoning"| B["the answer,
the review, the reply"] classDef s1 fill:#3b82f633,stroke:#3b82f6,stroke-width:1.5px classDef s1out fill:#3b82f61a,stroke:#60a5fa,stroke-width:1px classDef s2 fill:#f9731633,stroke:#f97316,stroke-width:1.5px classDef s2out fill:#f973161a,stroke:#fb923c,stroke-width:1px classDef io fill:#94a3b826,stroke:#94a3b8,stroke-width:1px classDef gate fill:#eab30833,stroke:#eab308,stroke-width:1.5px classDef stop fill:#ef444433,stroke:#ef4444,stroke-width:1.5px class S1 s1 class A s1out class S2 s2 class B s2out ``` Splitting them along that line usually does three things at once: - **Cheaper and faster.** The decision costs one short call instead of a generation plus a parser. - **Reproducible.** The same input yields the same typed answer, where free-text classification drifts between runs. - **Less generation overall.** A confident abstention means the expensive half never runs at all. ## Where it fits This is not only an agent technique. Anywhere a program currently asks a generative model a narrow question and parses the answer back out, a typed call does the same job for less. ### In a data pipeline ```mermaid flowchart TD IN["backlog of records"] --> S1(["System One
the whole battery, one call per record"]) S1 --> LBL["labels and facets
on every record"] S1 --> SEV["severity as an ordered rubric:
a number you can sort and threshold"] S1 --> GATE{"quality gate"} GATE -->|"consistent"| NEXT["next pipeline stage"] GATE -->|"inconsistent"| HOLD["hold for review"] classDef s1 fill:#3b82f633,stroke:#3b82f6,stroke-width:1.5px classDef s1out fill:#3b82f61a,stroke:#60a5fa,stroke-width:1px classDef s2 fill:#f9731633,stroke:#f97316,stroke-width:1.5px classDef s2out fill:#f973161a,stroke:#fb923c,stroke-width:1px classDef io fill:#94a3b826,stroke:#94a3b8,stroke-width:1px classDef gate fill:#eab30833,stroke:#eab308,stroke-width:1.5px classDef stop fill:#ef444433,stroke:#ef4444,stroke-width:1.5px class IN io class S1 s1 class LBL,SEV s1out class GATE gate class NEXT io class HOLD stop ``` | Use case | The questions | |---|---| | **Labeling and enrichment at volume** | Twenty facets of one record, at once. Per-item latency barely moves as the battery grows, so scoring a whole backlog stays affordable. | | **Quality gates between stages** | Is this row internally consistent? Does the extracted field match the source text? A gate that costs a generation is a gate you will be tempted to skip. | | **Triage and prioritization** | Severity as an ordered rubric, plus the symptoms behind it โ€” so the queue is sorted on a number you can threshold, not a sentence you have to read. | ### In an agent loop ```mermaid flowchart TD REQ["request"] --> GUARD{"guard:
hostile? asks for credentials?"} GUARD -->|"unsafe"| STOP["refuse or escalate"] GUARD -->|"safe"| PLAN(["route, then pick tools:
one question per tool"]) PLAN --> RUN["run the selected tools"] RUN --> MORE{"enough to answer?
still making progress?"} MORE -->|"no"| PLAN MORE -->|"yes"| GEN["System 2 writes the answer"] classDef s1 fill:#3b82f633,stroke:#3b82f6,stroke-width:1.5px classDef s1out fill:#3b82f61a,stroke:#60a5fa,stroke-width:1px classDef s2 fill:#f9731633,stroke:#f97316,stroke-width:1.5px classDef s2out fill:#f973161a,stroke:#fb923c,stroke-width:1px classDef io fill:#94a3b826,stroke:#94a3b8,stroke-width:1px classDef gate fill:#eab30833,stroke:#eab308,stroke-width:1.5px classDef stop fill:#ef444433,stroke:#ef4444,stroke-width:1.5px class REQ io class GUARD,MORE gate class STOP stop class PLAN s1 class RUN io class GEN s2 ``` | Use case | The questions | |---|---| | **Input guard** | Is this hostile? Does it ask for credentials? Does it contain instructions aimed at the assistant? | | **Intent routing** | Which of these N intents is it, and how confident? The answer is an enum member you branch on, not a string a typo breaks. | | **Tool selection** | One question per tool: would this one help here? Because each tool gets its own question, one request can select several. | | **Loop control** | Is there enough to answer? Did the last step add anything? Is this action safe? "Did the loop stop making progress" is otherwise the failure you discover from the bill. | ### In an app or service ```mermaid flowchart TD REQ["incoming request"] --> RT(["route:
handler, model tier, queue"]) RT --> MOD{"moderation:
publishable? how harmful?"} MOD -->|"blocked"| REJ["reject or hold"] MOD -->|"allowed"| WORK["the expensive path"] WORK --> CHK{"output check:
grounded? contradicted?"} CHK -->|"fails"| FIX["revise or hand over"] CHK -->|"passes"| OUT["respond"] classDef s1 fill:#3b82f633,stroke:#3b82f6,stroke-width:1.5px classDef s1out fill:#3b82f61a,stroke:#60a5fa,stroke-width:1px classDef s2 fill:#f9731633,stroke:#f97316,stroke-width:1.5px classDef s2out fill:#f973161a,stroke:#fb923c,stroke-width:1px classDef io fill:#94a3b826,stroke:#94a3b8,stroke-width:1px classDef gate fill:#eab30833,stroke:#eab308,stroke-width:1.5px classDef stop fill:#ef444433,stroke:#ef4444,stroke-width:1.5px class REQ io class RT s1 class MOD,CHK gate class REJ,FIX stop class WORK s2 class OUT io ``` | Use case | The questions | |---|---| | **Request routing** | Which handler, which model tier, which queue โ€” decided in milliseconds, before the expensive path is chosen. | | **Moderation** | Is this publishable? How harmful, on an ordered scale? Directed at a specific person? | | **Output checks** | Is the draft grounded in the retrieved context? Does anything contradict it? A cheap gate between generating an answer and returning it. | ## The discipline that makes it work Three rules, and they matter more than which model you use: **Ask about symptoms, not conclusions.** Do not ask for the verdict. Ask one question per observable fact, each answered in isolation, and derive the verdict yourself. A System One model is for judgments a knowledgeable person makes in seconds โ€” not for weighing nineteen facts against each other. **Compose in code, not in a prompt.** Because the composition is a function, it is unit-testable against hand-labelled cases, reviewable in a pull request, and changeable without re-validating a model's behavior. Changing what your team considers blocking becomes a diff. **Gate on confidence, and let it abstain.** Every answer carries calibrated confidence, which gives routing a second axis beyond the answer itself. Make the lowest tier a real abstention โ€” stop, hand over to a human, and never spend a generative call on a decision the pipeline is not sure about. Thresholds should scale with risk: a support reply can gate at 0.70; a merge, a refund, or a signature should gate at 0.85 or higher. ## When not to reach for one - **The answer is genuinely open-ended.** Writing the reply, summarizing a document, producing code โ€” that is what a generative model is for. Use both: typed answers to decide, prose to deliver. - **The judgment needs multi-factor reasoning that no decomposition captures.** If a question needs a chain of inference, either break it into symptoms and compose, or hand it to System 2. - **You have exactly one yes/no question and no plans to add more.** The fan-out is where the advantage lives; a single question is just a cheap classifier. ## Implementations ### **Inference > Decision models > Typed decisions with Jev** Coerce unstructured state into a typed Python object with TypeSafe's System One model, and branch on the result. ## Worked example Everything on this page โ€” the battery, the composition rule, the confidence gate โ€” wired together three ways and measured against a one-shot generative baseline. ### **Agents > Typed decisions for agentic pipelines** Interleave a System One model with a generative one โ€” typed guards, tool fan-out, a durable loop, and an A/B that prices both arms. ## Related - [TypeSafe AI integration](../../../integrations/typesafe-ai/_index): installation, the full API, and how answer types are serialized. - [Typed decisions for agentic pipelines](../../../tutorials/agents/system-one-agents/_index): three pipelines and a measured A/B against a one-shot generative baseline. - [Agents](../../agents/_index): the loop these decisions most often sit inside. - [Tasks](../../tasks/_index): the unit each call runs in. - **Inference > Inference Gateway > Decisions**: call `POST /v1/decisions` through the gateway, with TypeSafe models, hosted LLMs, or your own vLLM and SGLang apps. ## Subpages - **Inference > Decision models > Typed decisions with Jev** - Coerce unstructured state into a typed Python object with TypeSafe's System One model, and branch on the result. === PAGE: https://www.union.ai/docs/v2/union/user-guide/inference/decision-models/typed-decisions-with-jev === Coerce unstructured state into a typed Python object with TypeSafe's System One model, and branch on the result. # Typed decisions with Jev [TypeSafe](https://docs.typesafe.ai/introduction)'s System One model ("Jev") is reached through the `flyteplugins-typesafe-ai` plugin. The shape it gives you is worth naming precisely: **type coercion**. An ordinary coercion turns a string into an `int` by applying a rule. `ask()` turns a ticket, a diff, or any other blob of state into an instance of a dataclass you declared โ€” by asking a model one question per field, all in the same request: ```python triage: Triage = await ask(Triage, {"ticket": ticket}) ``` `Triage` is your type. Its fields are the questions. What comes back is a real instance, with an enum member where you declared an enum and a probability where you declared a `Noul` โ€” not a JSON blob you have to validate, and not prose you have to parse. From there you are writing normal Python against a normal object. ```bash pip install flyteplugins-typesafe-ai ``` > [!NOTE] > This page is the how-to. For the category โ€” what a System One model is, where it fits, and the discipline that makes it pay off โ€” see [Decision models](./_index). For installation detail and the full API, see the [TypeSafe AI integration](../../../integrations/typesafe-ai/_index). ## The three field types These are what you coerce *into*. Each is a plain dataclass carrying the answer plus its calibrated confidence. | Type | Holds | Useful members | |---|---|---| | `Choice` | the picked member of your enum, `confidence`, the whole `probabilities` distribution | `.certain(threshold)`, `.runner_up()` | | `Score` | the picked rung of your `IntEnum`, the unrounded `position` on the scale, `confidence` | `.at_least(rung)` | | `Noul` | truthfulness in 0..1 | `.at(threshold)` | `Choice` comes back as the **enum member**, not a string, so you branch on `t.intent.value is Intent.REFUND` rather than on a string comparison that a typo silently breaks. `Score` keeps both representations on purpose: `value` is the rung you branch on, `position` is where on the scale the answer actually landed, which is what you sort and threshold by. `Noul` deliberately has no `__bool__`. `if noul:` would treat 0.02 and 0.98 alike, and picking the threshold is precisely the part that belongs in reviewable code. ## Declare the target type The dataclass is the schema. Where each question comes from depends on the field's type, and the split is worth knowing before you write your first battery: | Field | Question | Criteria | |---|---|---| | `Choice[YourEnum]` | inferred โ€” the enum's **class docstring** | inferred โ€” each **member's docstring** | | `Score[YourIntEnum]` | inferred โ€” the enum's **class docstring** | inferred โ€” each **rung's docstring**, in order | | `Noul` | **field metadata, required** | field metadata, optional | `Choice` and `Score` are parameterized by an `enum.Enum` and an `enum.IntEnum` respectively, and that enum *is* the vocabulary. The plugin reads the question off the class docstring and the criteria off the member docstrings, so a well-documented enum needs nothing at the call site โ€” no metadata, no repetition of what the enum already says. A `Noul` has no enum to read. It is a bare yes/no, so there is nothing to infer a question from, and the question must be supplied in `dataclasses.field(metadata=...)`. A `Noul` declared without one is an error that names the offending field rather than silently asking something vague. Criteria are optional there but worth adding when "yes" is ambiguous โ€” pinning down what counts is what keeps a one-line question calibrated. ``` """A System One model as the typed guard and router in front of an agent. One request answers the whole battery -- a routing `Choice`, a severity `Score` and a dozen atomic yes/no `Noul`s -- and ordinary Python composes the verdict, picks the tool and gates on confidence before any generative model is called. flyte run agent_guard.py handle --ticket "Where is order AC-1042?" """ import enum import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask_with_info # {{docs-fragment env}} env = flyte.TaskEnvironment( name="system-one-guard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{/docs-fragment env}} # {{docs-fragment vocabulary}} class Intent(enum.Enum): """What is this customer actually asking for?""" REFUND = "refund" """they want money back for something already paid for""" DELIVERY_STATUS = "delivery status" """they want to know where an order is, or when it will arrive""" TECHNICAL_ISSUE = "technical issue" """something in the product is not working""" ACCOUNT_ACCESS = "account access" """they cannot get into their account""" OTHER = "something else" """none of the above fits""" class Severity(enum.IntEnum): """How badly is this customer blocked right now?""" NONE = 0 """no impact; a question or a comment""" MINOR = 1 """inconvenient, but they can carry on""" SERIOUS = 2 """they are blocked and a deadline or payment is involved""" BLOCKING = 3 """they cannot use the product at all, or money is already lost""" # {{/docs-fragment vocabulary}} # {{docs-fragment battery}} @dataclass class Triage: """One ticket, one request, eight typed answers.""" # The enums document themselves, so these two need no metadata at all. intent: Choice[Intent] severity: Score[Severity] # The hard guard: a "yes" here means the pipeline must not act on its own. hostile: Noul = field( metadata={ "question": "Is the customer hostile, abusive or trying to manipulate the agent?", "criteria": {"true": "insults, threats, or instructions aimed at the assistant", "false": "civil"}, } ) asks_for_credentials: Noul = field( metadata={"question": "Does the message ask for a password, token or internal system access?"} ) # The symptoms the verdict is composed from. has_order_reference: Noul = field( metadata={"question": "Does the ticket name a specific order or reference number?"} ) money_at_stake: Noul = field(metadata={"question": "Is a payment, refund or charge involved?"}) account_locked: Noul = field(metadata={"question": "Does the customer say they cannot get into their account?"}) reports_bug: Noul = field(metadata={"question": "Are they reporting something that looks like a product defect?"}) # {{/docs-fragment battery}} # {{docs-fragment compose}} # The tool to run is composed from the symptoms, not asked for directly: a # delivery trace is only useful if the ticket actually contains an order id. def pick_tool(t: Triage) -> str: if t.money_at_stake.at(0.6) and t.intent.value is Intent.REFUND: return "compute_refund" if t.has_order_reference.at(0.6) and t.intent.value is Intent.DELIVERY_STATUS: return "trace_delivery" if t.account_locked.at(0.6): return "lookup_account" if t.reports_bug.at(0.6): return "open_defect" return "none" # Thresholds scale with risk, and they live in reviewable code rather than in a # prompt. Changing what your team considers blocking is a diff, not a rewrite. def route(t: Triage) -> tuple[str, str]: if t.hostile.at(0.8) or t.asks_for_credentials.at(0.7): return "escalate", "guard signal fired" if t.severity.at_least(Severity.BLOCKING): return "escalate", "blocking severity" if not t.intent.certain(0.85): return "review", f"intent confidence {t.intent.confidence:.2f} below 0.85" return "auto", "clear intent, no guard signal" # {{/docs-fragment compose}} # {{docs-fragment guard-task}} @env.task async def guard(ticket: str) -> Triage: """One System One request answers the whole battery.""" answered, info = await ask_with_info(Triage, {"ticket": ticket}) print(f"{info.questions} questions in one call: {info.latency_s:.2f}s, {info.input_tokens} input tokens") return answered # {{/docs-fragment guard-task}} # {{docs-fragment handle}} @env.task async def handle(ticket: str) -> str: t = await guard(ticket) tier, why = route(t) tool = pick_tool(t) if tier == "escalate": # A real abstention: hand over, and never spend a generation on a # decision the pipeline is not sure about. return f"escalate ({why}) โ€” no tool run, no model called" # ... call your tool task and your generative model here, with the typed # answers as clean structured input rather than a re-parsed blob of prose. fired = sorted(name for name, a in vars(t).items() if isinstance(a, Noul) and a.at(0.5)) return ( f"{tier} ({why}) intent={t.intent.value.value} p={t.intent.confidence:.2f} " f"severity={t.severity.value.name}@{t.severity.position:.1f} tool={tool} fired={fired}" ) # {{/docs-fragment handle}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(handle, ticket="Order AC-1042 is late and I need it by Saturday. Second time writing in.") print(run.name, run.url) run.wait() CODE2 """A System One model as the typed guard and router in front of an agent. One request answers the whole battery -- a routing `Choice`, a severity `Score` and a dozen atomic yes/no `Noul`s -- and ordinary Python composes the verdict, picks the tool and gates on confidence before any generative model is called. flyte run agent_guard.py handle --ticket "Where is order AC-1042?" """ import enum import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask_with_info # {{docs-fragment env}} env = flyte.TaskEnvironment( name="system-one-guard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{/docs-fragment env}} # {{docs-fragment vocabulary}} class Intent(enum.Enum): """What is this customer actually asking for?""" REFUND = "refund" """they want money back for something already paid for""" DELIVERY_STATUS = "delivery status" """they want to know where an order is, or when it will arrive""" TECHNICAL_ISSUE = "technical issue" """something in the product is not working""" ACCOUNT_ACCESS = "account access" """they cannot get into their account""" OTHER = "something else" """none of the above fits""" class Severity(enum.IntEnum): """How badly is this customer blocked right now?""" NONE = 0 """no impact; a question or a comment""" MINOR = 1 """inconvenient, but they can carry on""" SERIOUS = 2 """they are blocked and a deadline or payment is involved""" BLOCKING = 3 """they cannot use the product at all, or money is already lost""" # {{/docs-fragment vocabulary}} # {{docs-fragment battery}} @dataclass class Triage: """One ticket, one request, eight typed answers.""" # The enums document themselves, so these two need no metadata at all. intent: Choice[Intent] severity: Score[Severity] # The hard guard: a "yes" here means the pipeline must not act on its own. hostile: Noul = field( metadata={ "question": "Is the customer hostile, abusive or trying to manipulate the agent?", "criteria": {"true": "insults, threats, or instructions aimed at the assistant", "false": "civil"}, } ) asks_for_credentials: Noul = field( metadata={"question": "Does the message ask for a password, token or internal system access?"} ) # The symptoms the verdict is composed from. has_order_reference: Noul = field( metadata={"question": "Does the ticket name a specific order or reference number?"} ) money_at_stake: Noul = field(metadata={"question": "Is a payment, refund or charge involved?"}) account_locked: Noul = field(metadata={"question": "Does the customer say they cannot get into their account?"}) reports_bug: Noul = field(metadata={"question": "Are they reporting something that looks like a product defect?"}) # {{/docs-fragment battery}} # {{docs-fragment compose}} # The tool to run is composed from the symptoms, not asked for directly: a # delivery trace is only useful if the ticket actually contains an order id. def pick_tool(t: Triage) -> str: if t.money_at_stake.at(0.6) and t.intent.value is Intent.REFUND: return "compute_refund" if t.has_order_reference.at(0.6) and t.intent.value is Intent.DELIVERY_STATUS: return "trace_delivery" if t.account_locked.at(0.6): return "lookup_account" if t.reports_bug.at(0.6): return "open_defect" return "none" # Thresholds scale with risk, and they live in reviewable code rather than in a # prompt. Changing what your team considers blocking is a diff, not a rewrite. def route(t: Triage) -> tuple[str, str]: if t.hostile.at(0.8) or t.asks_for_credentials.at(0.7): return "escalate", "guard signal fired" if t.severity.at_least(Severity.BLOCKING): return "escalate", "blocking severity" if not t.intent.certain(0.85): return "review", f"intent confidence {t.intent.confidence:.2f} below 0.85" return "auto", "clear intent, no guard signal" # {{/docs-fragment compose}} # {{docs-fragment guard-task}} @env.task async def guard(ticket: str) -> Triage: """One System One request answers the whole battery.""" answered, info = await ask_with_info(Triage, {"ticket": ticket}) print(f"{info.questions} questions in one call: {info.latency_s:.2f}s, {info.input_tokens} input tokens") return answered # {{/docs-fragment guard-task}} # {{docs-fragment handle}} @env.task async def handle(ticket: str) -> str: t = await guard(ticket) tier, why = route(t) tool = pick_tool(t) if tier == "escalate": # A real abstention: hand over, and never spend a generation on a # decision the pipeline is not sure about. return f"escalate ({why}) โ€” no tool run, no model called" # ... call your tool task and your generative model here, with the typed # answers as clean structured input rather than a re-parsed blob of prose. fired = sorted(name for name, a in vars(t).items() if isinstance(a, Noul) and a.at(0.5)) return ( f"{tier} ({why}) intent={t.intent.value.value} p={t.intent.confidence:.2f} " f"severity={t.severity.value.name}@{t.severity.position:.1f} tool={tool} fired={fired}" ) # {{/docs-fragment handle}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(handle, ticket="Order AC-1042 is late and I need it by Saturday. Second time writing in.") print(run.name, run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/system-one/agent_guard.py* Notice which fields carry metadata and which do not: `intent` and `severity` say nothing beyond their type, because `Intent` and `Severity` above already document themselves, while every `Noul` spells out its question. Two fields route the ticket, two guard it, and the rest are the symptoms the tool choice is composed from. Adding another question would be another field and still one request โ€” the [tutorial battery](../../../tutorials/agents/system-one-agents/_index) pushes the same shape to nineteen fields, eight of which are never read, because in one call they cost almost nothing. ## Coerce ``` """A System One model as the typed guard and router in front of an agent. One request answers the whole battery -- a routing `Choice`, a severity `Score` and a dozen atomic yes/no `Noul`s -- and ordinary Python composes the verdict, picks the tool and gates on confidence before any generative model is called. flyte run agent_guard.py handle --ticket "Where is order AC-1042?" """ import enum import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask_with_info # {{docs-fragment env}} env = flyte.TaskEnvironment( name="system-one-guard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{/docs-fragment env}} # {{docs-fragment vocabulary}} class Intent(enum.Enum): """What is this customer actually asking for?""" REFUND = "refund" """they want money back for something already paid for""" DELIVERY_STATUS = "delivery status" """they want to know where an order is, or when it will arrive""" TECHNICAL_ISSUE = "technical issue" """something in the product is not working""" ACCOUNT_ACCESS = "account access" """they cannot get into their account""" OTHER = "something else" """none of the above fits""" class Severity(enum.IntEnum): """How badly is this customer blocked right now?""" NONE = 0 """no impact; a question or a comment""" MINOR = 1 """inconvenient, but they can carry on""" SERIOUS = 2 """they are blocked and a deadline or payment is involved""" BLOCKING = 3 """they cannot use the product at all, or money is already lost""" # {{/docs-fragment vocabulary}} # {{docs-fragment battery}} @dataclass class Triage: """One ticket, one request, eight typed answers.""" # The enums document themselves, so these two need no metadata at all. intent: Choice[Intent] severity: Score[Severity] # The hard guard: a "yes" here means the pipeline must not act on its own. hostile: Noul = field( metadata={ "question": "Is the customer hostile, abusive or trying to manipulate the agent?", "criteria": {"true": "insults, threats, or instructions aimed at the assistant", "false": "civil"}, } ) asks_for_credentials: Noul = field( metadata={"question": "Does the message ask for a password, token or internal system access?"} ) # The symptoms the verdict is composed from. has_order_reference: Noul = field( metadata={"question": "Does the ticket name a specific order or reference number?"} ) money_at_stake: Noul = field(metadata={"question": "Is a payment, refund or charge involved?"}) account_locked: Noul = field(metadata={"question": "Does the customer say they cannot get into their account?"}) reports_bug: Noul = field(metadata={"question": "Are they reporting something that looks like a product defect?"}) # {{/docs-fragment battery}} # {{docs-fragment compose}} # The tool to run is composed from the symptoms, not asked for directly: a # delivery trace is only useful if the ticket actually contains an order id. def pick_tool(t: Triage) -> str: if t.money_at_stake.at(0.6) and t.intent.value is Intent.REFUND: return "compute_refund" if t.has_order_reference.at(0.6) and t.intent.value is Intent.DELIVERY_STATUS: return "trace_delivery" if t.account_locked.at(0.6): return "lookup_account" if t.reports_bug.at(0.6): return "open_defect" return "none" # Thresholds scale with risk, and they live in reviewable code rather than in a # prompt. Changing what your team considers blocking is a diff, not a rewrite. def route(t: Triage) -> tuple[str, str]: if t.hostile.at(0.8) or t.asks_for_credentials.at(0.7): return "escalate", "guard signal fired" if t.severity.at_least(Severity.BLOCKING): return "escalate", "blocking severity" if not t.intent.certain(0.85): return "review", f"intent confidence {t.intent.confidence:.2f} below 0.85" return "auto", "clear intent, no guard signal" # {{/docs-fragment compose}} # {{docs-fragment guard-task}} @env.task async def guard(ticket: str) -> Triage: """One System One request answers the whole battery.""" answered, info = await ask_with_info(Triage, {"ticket": ticket}) print(f"{info.questions} questions in one call: {info.latency_s:.2f}s, {info.input_tokens} input tokens") return answered # {{/docs-fragment guard-task}} # {{docs-fragment handle}} @env.task async def handle(ticket: str) -> str: t = await guard(ticket) tier, why = route(t) tool = pick_tool(t) if tier == "escalate": # A real abstention: hand over, and never spend a generation on a # decision the pipeline is not sure about. return f"escalate ({why}) โ€” no tool run, no model called" # ... call your tool task and your generative model here, with the typed # answers as clean structured input rather than a re-parsed blob of prose. fired = sorted(name for name, a in vars(t).items() if isinstance(a, Noul) and a.at(0.5)) return ( f"{tier} ({why}) intent={t.intent.value.value} p={t.intent.confidence:.2f} " f"severity={t.severity.value.name}@{t.severity.position:.1f} tool={tool} fired={fired}" ) # {{/docs-fragment handle}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(handle, ticket="Order AC-1042 is late and I need it by Saturday. Second time writing in.") print(run.name, run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/system-one/agent_guard.py* `ask()` compiles the whole dataclass into a **single** request. Three separate `ask()` calls are three round trips; one battery is one. `ask_with_info()` returns the model name, question count, token usage and latency alongside the answers, which is what you want when you are measuring the fan-out. The environment mounts the API key as an environment variable and nothing else: ``` """A System One model as the typed guard and router in front of an agent. One request answers the whole battery -- a routing `Choice`, a severity `Score` and a dozen atomic yes/no `Noul`s -- and ordinary Python composes the verdict, picks the tool and gates on confidence before any generative model is called. flyte run agent_guard.py handle --ticket "Where is order AC-1042?" """ import enum import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask_with_info # {{docs-fragment env}} env = flyte.TaskEnvironment( name="system-one-guard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{/docs-fragment env}} # {{docs-fragment vocabulary}} class Intent(enum.Enum): """What is this customer actually asking for?""" REFUND = "refund" """they want money back for something already paid for""" DELIVERY_STATUS = "delivery status" """they want to know where an order is, or when it will arrive""" TECHNICAL_ISSUE = "technical issue" """something in the product is not working""" ACCOUNT_ACCESS = "account access" """they cannot get into their account""" OTHER = "something else" """none of the above fits""" class Severity(enum.IntEnum): """How badly is this customer blocked right now?""" NONE = 0 """no impact; a question or a comment""" MINOR = 1 """inconvenient, but they can carry on""" SERIOUS = 2 """they are blocked and a deadline or payment is involved""" BLOCKING = 3 """they cannot use the product at all, or money is already lost""" # {{/docs-fragment vocabulary}} # {{docs-fragment battery}} @dataclass class Triage: """One ticket, one request, eight typed answers.""" # The enums document themselves, so these two need no metadata at all. intent: Choice[Intent] severity: Score[Severity] # The hard guard: a "yes" here means the pipeline must not act on its own. hostile: Noul = field( metadata={ "question": "Is the customer hostile, abusive or trying to manipulate the agent?", "criteria": {"true": "insults, threats, or instructions aimed at the assistant", "false": "civil"}, } ) asks_for_credentials: Noul = field( metadata={"question": "Does the message ask for a password, token or internal system access?"} ) # The symptoms the verdict is composed from. has_order_reference: Noul = field( metadata={"question": "Does the ticket name a specific order or reference number?"} ) money_at_stake: Noul = field(metadata={"question": "Is a payment, refund or charge involved?"}) account_locked: Noul = field(metadata={"question": "Does the customer say they cannot get into their account?"}) reports_bug: Noul = field(metadata={"question": "Are they reporting something that looks like a product defect?"}) # {{/docs-fragment battery}} # {{docs-fragment compose}} # The tool to run is composed from the symptoms, not asked for directly: a # delivery trace is only useful if the ticket actually contains an order id. def pick_tool(t: Triage) -> str: if t.money_at_stake.at(0.6) and t.intent.value is Intent.REFUND: return "compute_refund" if t.has_order_reference.at(0.6) and t.intent.value is Intent.DELIVERY_STATUS: return "trace_delivery" if t.account_locked.at(0.6): return "lookup_account" if t.reports_bug.at(0.6): return "open_defect" return "none" # Thresholds scale with risk, and they live in reviewable code rather than in a # prompt. Changing what your team considers blocking is a diff, not a rewrite. def route(t: Triage) -> tuple[str, str]: if t.hostile.at(0.8) or t.asks_for_credentials.at(0.7): return "escalate", "guard signal fired" if t.severity.at_least(Severity.BLOCKING): return "escalate", "blocking severity" if not t.intent.certain(0.85): return "review", f"intent confidence {t.intent.confidence:.2f} below 0.85" return "auto", "clear intent, no guard signal" # {{/docs-fragment compose}} # {{docs-fragment guard-task}} @env.task async def guard(ticket: str) -> Triage: """One System One request answers the whole battery.""" answered, info = await ask_with_info(Triage, {"ticket": ticket}) print(f"{info.questions} questions in one call: {info.latency_s:.2f}s, {info.input_tokens} input tokens") return answered # {{/docs-fragment guard-task}} # {{docs-fragment handle}} @env.task async def handle(ticket: str) -> str: t = await guard(ticket) tier, why = route(t) tool = pick_tool(t) if tier == "escalate": # A real abstention: hand over, and never spend a generation on a # decision the pipeline is not sure about. return f"escalate ({why}) โ€” no tool run, no model called" # ... call your tool task and your generative model here, with the typed # answers as clean structured input rather than a re-parsed blob of prose. fired = sorted(name for name, a in vars(t).items() if isinstance(a, Noul) and a.at(0.5)) return ( f"{tier} ({why}) intent={t.intent.value.value} p={t.intent.confidence:.2f} " f"severity={t.severity.value.name}@{t.severity.position:.1f} tool={tool} fired={fired}" ) # {{/docs-fragment handle}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(handle, ticket="Order AC-1042 is late and I need it by Saturday. Second time writing in.") print(run.name, run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/system-one/agent_guard.py* ## Derive the verdict from the fields Do not add a `verdict` field and let the model fill it in. Coerce the symptoms, then derive: ``` """A System One model as the typed guard and router in front of an agent. One request answers the whole battery -- a routing `Choice`, a severity `Score` and a dozen atomic yes/no `Noul`s -- and ordinary Python composes the verdict, picks the tool and gates on confidence before any generative model is called. flyte run agent_guard.py handle --ticket "Where is order AC-1042?" """ import enum import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask_with_info # {{docs-fragment env}} env = flyte.TaskEnvironment( name="system-one-guard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{/docs-fragment env}} # {{docs-fragment vocabulary}} class Intent(enum.Enum): """What is this customer actually asking for?""" REFUND = "refund" """they want money back for something already paid for""" DELIVERY_STATUS = "delivery status" """they want to know where an order is, or when it will arrive""" TECHNICAL_ISSUE = "technical issue" """something in the product is not working""" ACCOUNT_ACCESS = "account access" """they cannot get into their account""" OTHER = "something else" """none of the above fits""" class Severity(enum.IntEnum): """How badly is this customer blocked right now?""" NONE = 0 """no impact; a question or a comment""" MINOR = 1 """inconvenient, but they can carry on""" SERIOUS = 2 """they are blocked and a deadline or payment is involved""" BLOCKING = 3 """they cannot use the product at all, or money is already lost""" # {{/docs-fragment vocabulary}} # {{docs-fragment battery}} @dataclass class Triage: """One ticket, one request, eight typed answers.""" # The enums document themselves, so these two need no metadata at all. intent: Choice[Intent] severity: Score[Severity] # The hard guard: a "yes" here means the pipeline must not act on its own. hostile: Noul = field( metadata={ "question": "Is the customer hostile, abusive or trying to manipulate the agent?", "criteria": {"true": "insults, threats, or instructions aimed at the assistant", "false": "civil"}, } ) asks_for_credentials: Noul = field( metadata={"question": "Does the message ask for a password, token or internal system access?"} ) # The symptoms the verdict is composed from. has_order_reference: Noul = field( metadata={"question": "Does the ticket name a specific order or reference number?"} ) money_at_stake: Noul = field(metadata={"question": "Is a payment, refund or charge involved?"}) account_locked: Noul = field(metadata={"question": "Does the customer say they cannot get into their account?"}) reports_bug: Noul = field(metadata={"question": "Are they reporting something that looks like a product defect?"}) # {{/docs-fragment battery}} # {{docs-fragment compose}} # The tool to run is composed from the symptoms, not asked for directly: a # delivery trace is only useful if the ticket actually contains an order id. def pick_tool(t: Triage) -> str: if t.money_at_stake.at(0.6) and t.intent.value is Intent.REFUND: return "compute_refund" if t.has_order_reference.at(0.6) and t.intent.value is Intent.DELIVERY_STATUS: return "trace_delivery" if t.account_locked.at(0.6): return "lookup_account" if t.reports_bug.at(0.6): return "open_defect" return "none" # Thresholds scale with risk, and they live in reviewable code rather than in a # prompt. Changing what your team considers blocking is a diff, not a rewrite. def route(t: Triage) -> tuple[str, str]: if t.hostile.at(0.8) or t.asks_for_credentials.at(0.7): return "escalate", "guard signal fired" if t.severity.at_least(Severity.BLOCKING): return "escalate", "blocking severity" if not t.intent.certain(0.85): return "review", f"intent confidence {t.intent.confidence:.2f} below 0.85" return "auto", "clear intent, no guard signal" # {{/docs-fragment compose}} # {{docs-fragment guard-task}} @env.task async def guard(ticket: str) -> Triage: """One System One request answers the whole battery.""" answered, info = await ask_with_info(Triage, {"ticket": ticket}) print(f"{info.questions} questions in one call: {info.latency_s:.2f}s, {info.input_tokens} input tokens") return answered # {{/docs-fragment guard-task}} # {{docs-fragment handle}} @env.task async def handle(ticket: str) -> str: t = await guard(ticket) tier, why = route(t) tool = pick_tool(t) if tier == "escalate": # A real abstention: hand over, and never spend a generation on a # decision the pipeline is not sure about. return f"escalate ({why}) โ€” no tool run, no model called" # ... call your tool task and your generative model here, with the typed # answers as clean structured input rather than a re-parsed blob of prose. fired = sorted(name for name, a in vars(t).items() if isinstance(a, Noul) and a.at(0.5)) return ( f"{tier} ({why}) intent={t.intent.value.value} p={t.intent.confidence:.2f} " f"severity={t.severity.value.name}@{t.severity.position:.1f} tool={tool} fired={fired}" ) # {{/docs-fragment handle}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(handle, ticket="Order AC-1042 is late and I need it by Saturday. Second time writing in.") print(run.name, run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/system-one/agent_guard.py* Because the composition is a function rather than a prompt, it is unit-testable against hand-labelled cases, reviewable in a pull request, and changeable without re-validating a model's behavior. ## Gate on confidence, and mean it Every `Choice` and `Score` field carries calibrated confidence, which gives routing a second axis beyond the answer itself: ``` """A System One model as the typed guard and router in front of an agent. One request answers the whole battery -- a routing `Choice`, a severity `Score` and a dozen atomic yes/no `Noul`s -- and ordinary Python composes the verdict, picks the tool and gates on confidence before any generative model is called. flyte run agent_guard.py handle --ticket "Where is order AC-1042?" """ import enum import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask_with_info # {{docs-fragment env}} env = flyte.TaskEnvironment( name="system-one-guard", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{/docs-fragment env}} # {{docs-fragment vocabulary}} class Intent(enum.Enum): """What is this customer actually asking for?""" REFUND = "refund" """they want money back for something already paid for""" DELIVERY_STATUS = "delivery status" """they want to know where an order is, or when it will arrive""" TECHNICAL_ISSUE = "technical issue" """something in the product is not working""" ACCOUNT_ACCESS = "account access" """they cannot get into their account""" OTHER = "something else" """none of the above fits""" class Severity(enum.IntEnum): """How badly is this customer blocked right now?""" NONE = 0 """no impact; a question or a comment""" MINOR = 1 """inconvenient, but they can carry on""" SERIOUS = 2 """they are blocked and a deadline or payment is involved""" BLOCKING = 3 """they cannot use the product at all, or money is already lost""" # {{/docs-fragment vocabulary}} # {{docs-fragment battery}} @dataclass class Triage: """One ticket, one request, eight typed answers.""" # The enums document themselves, so these two need no metadata at all. intent: Choice[Intent] severity: Score[Severity] # The hard guard: a "yes" here means the pipeline must not act on its own. hostile: Noul = field( metadata={ "question": "Is the customer hostile, abusive or trying to manipulate the agent?", "criteria": {"true": "insults, threats, or instructions aimed at the assistant", "false": "civil"}, } ) asks_for_credentials: Noul = field( metadata={"question": "Does the message ask for a password, token or internal system access?"} ) # The symptoms the verdict is composed from. has_order_reference: Noul = field( metadata={"question": "Does the ticket name a specific order or reference number?"} ) money_at_stake: Noul = field(metadata={"question": "Is a payment, refund or charge involved?"}) account_locked: Noul = field(metadata={"question": "Does the customer say they cannot get into their account?"}) reports_bug: Noul = field(metadata={"question": "Are they reporting something that looks like a product defect?"}) # {{/docs-fragment battery}} # {{docs-fragment compose}} # The tool to run is composed from the symptoms, not asked for directly: a # delivery trace is only useful if the ticket actually contains an order id. def pick_tool(t: Triage) -> str: if t.money_at_stake.at(0.6) and t.intent.value is Intent.REFUND: return "compute_refund" if t.has_order_reference.at(0.6) and t.intent.value is Intent.DELIVERY_STATUS: return "trace_delivery" if t.account_locked.at(0.6): return "lookup_account" if t.reports_bug.at(0.6): return "open_defect" return "none" # Thresholds scale with risk, and they live in reviewable code rather than in a # prompt. Changing what your team considers blocking is a diff, not a rewrite. def route(t: Triage) -> tuple[str, str]: if t.hostile.at(0.8) or t.asks_for_credentials.at(0.7): return "escalate", "guard signal fired" if t.severity.at_least(Severity.BLOCKING): return "escalate", "blocking severity" if not t.intent.certain(0.85): return "review", f"intent confidence {t.intent.confidence:.2f} below 0.85" return "auto", "clear intent, no guard signal" # {{/docs-fragment compose}} # {{docs-fragment guard-task}} @env.task async def guard(ticket: str) -> Triage: """One System One request answers the whole battery.""" answered, info = await ask_with_info(Triage, {"ticket": ticket}) print(f"{info.questions} questions in one call: {info.latency_s:.2f}s, {info.input_tokens} input tokens") return answered # {{/docs-fragment guard-task}} # {{docs-fragment handle}} @env.task async def handle(ticket: str) -> str: t = await guard(ticket) tier, why = route(t) tool = pick_tool(t) if tier == "escalate": # A real abstention: hand over, and never spend a generation on a # decision the pipeline is not sure about. return f"escalate ({why}) โ€” no tool run, no model called" # ... call your tool task and your generative model here, with the typed # answers as clean structured input rather than a re-parsed blob of prose. fired = sorted(name for name, a in vars(t).items() if isinstance(a, Noul) and a.at(0.5)) return ( f"{tier} ({why}) intent={t.intent.value.value} p={t.intent.confidence:.2f} " f"severity={t.severity.value.name}@{t.severity.position:.1f} tool={tool} fired={fired}" ) # {{/docs-fragment handle}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(handle, ticket="Order AC-1042 is late and I need it by Saturday. Second time writing in.") print(run.name, run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/system-one/agent_guard.py* `escalate` is a real abstention, not a label. The pipeline stops, hands over to a human, and never spends a generative call on a decision it is not sure about. That is where most of the cost saving comes from in practice โ€” not from the cheaper model, but from the calls that never happen. ## Coerce the agent's next move The same coercion drives a loop. Instead of an all-purpose model picking the next move in free text and a regex fishing it back out, one `Step` object per turn carries the action, the confidence, and the stop conditions: ``` """A durable agent loop whose control flow is decided by typed answers. Instead of an all-purpose LLM choosing the next move in free text, a `Choice` picks the next action, a `Score` gates on confidence and a `Noul` decides whether the loop has enough to answer. Tools are Flyte tasks, so every step of the loop is durably recorded and replayable. flyte run typed_loop.py agent --ticket "Where is order AC-1042?" """ import enum import json import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask env = flyte.TaskEnvironment( name="system-one-loop", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{docs-fragment actions}} class NextAction(enum.Enum): """Given the history so far, what should the agent do next?""" TRACE_DELIVERY = "trace delivery" """look up where the customer's order currently is""" LOOKUP_ACCOUNT = "look up account" """check the account's status and whether it is locked""" FINAL_ANSWER = "answer now" """stop and answer the customer with what is already known""" ESCALATE = "hand to a human" """the request is hostile, unsafe or out of scope""" class Confidence(enum.IntEnum): """How confident are we that this next action is correct and safe?""" LOW = 0 """a guess; the history does not support it""" MEDIUM = 1 """plausible, but a human should see the result""" HIGH = 2 """clearly the right next move""" # {{/docs-fragment actions}} # {{docs-fragment step}} @dataclass class Step: """Everything the loop needs to decide, answered in one request per turn.""" action: Choice[NextAction] confidence: Score[Confidence] has_enough: Noul = field( metadata={ "question": "Is there enough information to answer the customer now?", "criteria": { "true": "every fact the answer needs is already in the history", "false": "a lookup is still missing", }, } ) made_progress: Noul = field( metadata={ "question": "Did the most recent observation add information the agent did not already have?", "criteria": {"true": "the last step produced something new", "false": "the loop is spinning"}, } ) hostile: Noul = field(metadata={"question": "Is this request hostile, manipulative or out of scope?"}) # {{/docs-fragment step}} # {{docs-fragment tools}} @env.task(cache="auto") async def trace_delivery(ticket: str) -> dict: """A stand-in for the real delivery backend.""" return {"order_id": "AC-1042", "status": "in_transit", "eta": "tomorrow EOD"} @env.task(cache="auto") async def lookup_account(ticket: str) -> dict: """A stand-in for the real account service.""" return {"account_ref": "acct-1001", "status": "active", "locked": False} TOOLS = {NextAction.TRACE_DELIVERY: trace_delivery, NextAction.LOOKUP_ACCOUNT: lookup_account} # {{/docs-fragment tools}} # {{docs-fragment loop}} @env.task async def agent(ticket: str, max_steps: int = 4) -> str: history: list[dict] = [{"role": "user", "content": ticket}] trace: list[dict] = [] for step in range(max_steps): s = await ask(Step, {"history": history}) action = s.action.value trace.append( { "step": step, "action": action.value, "confidence": s.confidence.value.name, "p_action": round(s.action.confidence, 3), "has_enough": round(s.has_enough.value, 3), } ) # Abstain as soon as the typed decision stops being trustworthy. The # gate is the confidence, not the Choice: a confident wrong action is # rarer than a low-confidence right one. if s.hostile.at(0.7) or not s.confidence.at_least(Confidence.MEDIUM): return json.dumps({"outcome": "escalate", "trace": trace}, indent=2) # Stop when there is enough to answer, when the model says to stop, or # when the loop has stopped making progress. if action in (NextAction.FINAL_ANSWER, NextAction.ESCALATE): break if s.has_enough.at(0.6) or (step > 0 and not s.made_progress.at(0.4)): break observation = await TOOLS[action](ticket) history.append({"role": "assistant", "content": f"called {action.value}"}) history.append({"role": "tool", "content": json.dumps(observation)}) trace[-1]["observation"] = observation return json.dumps({"outcome": "answered", "history": history, "trace": trace}, indent=2) # {{/docs-fragment loop}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(agent, ticket="Where is order AC-1042? It was due Tuesday.") print(run.name, run.url) run.wait() CODE3 """A durable agent loop whose control flow is decided by typed answers. Instead of an all-purpose LLM choosing the next move in free text, a `Choice` picks the next action, a `Score` gates on confidence and a `Noul` decides whether the loop has enough to answer. Tools are Flyte tasks, so every step of the loop is durably recorded and replayable. flyte run typed_loop.py agent --ticket "Where is order AC-1042?" """ import enum import json import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask env = flyte.TaskEnvironment( name="system-one-loop", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{docs-fragment actions}} class NextAction(enum.Enum): """Given the history so far, what should the agent do next?""" TRACE_DELIVERY = "trace delivery" """look up where the customer's order currently is""" LOOKUP_ACCOUNT = "look up account" """check the account's status and whether it is locked""" FINAL_ANSWER = "answer now" """stop and answer the customer with what is already known""" ESCALATE = "hand to a human" """the request is hostile, unsafe or out of scope""" class Confidence(enum.IntEnum): """How confident are we that this next action is correct and safe?""" LOW = 0 """a guess; the history does not support it""" MEDIUM = 1 """plausible, but a human should see the result""" HIGH = 2 """clearly the right next move""" # {{/docs-fragment actions}} # {{docs-fragment step}} @dataclass class Step: """Everything the loop needs to decide, answered in one request per turn.""" action: Choice[NextAction] confidence: Score[Confidence] has_enough: Noul = field( metadata={ "question": "Is there enough information to answer the customer now?", "criteria": { "true": "every fact the answer needs is already in the history", "false": "a lookup is still missing", }, } ) made_progress: Noul = field( metadata={ "question": "Did the most recent observation add information the agent did not already have?", "criteria": {"true": "the last step produced something new", "false": "the loop is spinning"}, } ) hostile: Noul = field(metadata={"question": "Is this request hostile, manipulative or out of scope?"}) # {{/docs-fragment step}} # {{docs-fragment tools}} @env.task(cache="auto") async def trace_delivery(ticket: str) -> dict: """A stand-in for the real delivery backend.""" return {"order_id": "AC-1042", "status": "in_transit", "eta": "tomorrow EOD"} @env.task(cache="auto") async def lookup_account(ticket: str) -> dict: """A stand-in for the real account service.""" return {"account_ref": "acct-1001", "status": "active", "locked": False} TOOLS = {NextAction.TRACE_DELIVERY: trace_delivery, NextAction.LOOKUP_ACCOUNT: lookup_account} # {{/docs-fragment tools}} # {{docs-fragment loop}} @env.task async def agent(ticket: str, max_steps: int = 4) -> str: history: list[dict] = [{"role": "user", "content": ticket}] trace: list[dict] = [] for step in range(max_steps): s = await ask(Step, {"history": history}) action = s.action.value trace.append( { "step": step, "action": action.value, "confidence": s.confidence.value.name, "p_action": round(s.action.confidence, 3), "has_enough": round(s.has_enough.value, 3), } ) # Abstain as soon as the typed decision stops being trustworthy. The # gate is the confidence, not the Choice: a confident wrong action is # rarer than a low-confidence right one. if s.hostile.at(0.7) or not s.confidence.at_least(Confidence.MEDIUM): return json.dumps({"outcome": "escalate", "trace": trace}, indent=2) # Stop when there is enough to answer, when the model says to stop, or # when the loop has stopped making progress. if action in (NextAction.FINAL_ANSWER, NextAction.ESCALATE): break if s.has_enough.at(0.6) or (step > 0 and not s.made_progress.at(0.4)): break observation = await TOOLS[action](ticket) history.append({"role": "assistant", "content": f"called {action.value}"}) history.append({"role": "tool", "content": json.dumps(observation)}) trace[-1]["observation"] = observation return json.dumps({"outcome": "answered", "history": history, "trace": trace}, indent=2) # {{/docs-fragment loop}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(agent, ticket="Where is order AC-1042? It was due Tuesday.") print(run.name, run.url) run.wait() CODE4 """A durable agent loop whose control flow is decided by typed answers. Instead of an all-purpose LLM choosing the next move in free text, a `Choice` picks the next action, a `Score` gates on confidence and a `Noul` decides whether the loop has enough to answer. Tools are Flyte tasks, so every step of the loop is durably recorded and replayable. flyte run typed_loop.py agent --ticket "Where is order AC-1042?" """ import enum import json import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask env = flyte.TaskEnvironment( name="system-one-loop", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{docs-fragment actions}} class NextAction(enum.Enum): """Given the history so far, what should the agent do next?""" TRACE_DELIVERY = "trace delivery" """look up where the customer's order currently is""" LOOKUP_ACCOUNT = "look up account" """check the account's status and whether it is locked""" FINAL_ANSWER = "answer now" """stop and answer the customer with what is already known""" ESCALATE = "hand to a human" """the request is hostile, unsafe or out of scope""" class Confidence(enum.IntEnum): """How confident are we that this next action is correct and safe?""" LOW = 0 """a guess; the history does not support it""" MEDIUM = 1 """plausible, but a human should see the result""" HIGH = 2 """clearly the right next move""" # {{/docs-fragment actions}} # {{docs-fragment step}} @dataclass class Step: """Everything the loop needs to decide, answered in one request per turn.""" action: Choice[NextAction] confidence: Score[Confidence] has_enough: Noul = field( metadata={ "question": "Is there enough information to answer the customer now?", "criteria": { "true": "every fact the answer needs is already in the history", "false": "a lookup is still missing", }, } ) made_progress: Noul = field( metadata={ "question": "Did the most recent observation add information the agent did not already have?", "criteria": {"true": "the last step produced something new", "false": "the loop is spinning"}, } ) hostile: Noul = field(metadata={"question": "Is this request hostile, manipulative or out of scope?"}) # {{/docs-fragment step}} # {{docs-fragment tools}} @env.task(cache="auto") async def trace_delivery(ticket: str) -> dict: """A stand-in for the real delivery backend.""" return {"order_id": "AC-1042", "status": "in_transit", "eta": "tomorrow EOD"} @env.task(cache="auto") async def lookup_account(ticket: str) -> dict: """A stand-in for the real account service.""" return {"account_ref": "acct-1001", "status": "active", "locked": False} TOOLS = {NextAction.TRACE_DELIVERY: trace_delivery, NextAction.LOOKUP_ACCOUNT: lookup_account} # {{/docs-fragment tools}} # {{docs-fragment loop}} @env.task async def agent(ticket: str, max_steps: int = 4) -> str: history: list[dict] = [{"role": "user", "content": ticket}] trace: list[dict] = [] for step in range(max_steps): s = await ask(Step, {"history": history}) action = s.action.value trace.append( { "step": step, "action": action.value, "confidence": s.confidence.value.name, "p_action": round(s.action.confidence, 3), "has_enough": round(s.has_enough.value, 3), } ) # Abstain as soon as the typed decision stops being trustworthy. The # gate is the confidence, not the Choice: a confident wrong action is # rarer than a low-confidence right one. if s.hostile.at(0.7) or not s.confidence.at_least(Confidence.MEDIUM): return json.dumps({"outcome": "escalate", "trace": trace}, indent=2) # Stop when there is enough to answer, when the model says to stop, or # when the loop has stopped making progress. if action in (NextAction.FINAL_ANSWER, NextAction.ESCALATE): break if s.has_enough.at(0.6) or (step > 0 and not s.made_progress.at(0.4)): break observation = await TOOLS[action](ticket) history.append({"role": "assistant", "content": f"called {action.value}"}) history.append({"role": "tool", "content": json.dumps(observation)}) trace[-1]["observation"] = observation return json.dumps({"outcome": "answered", "history": history, "trace": trace}, indent=2) # {{/docs-fragment loop}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(agent, ticket="Where is order AC-1042? It was due Tuesday.") print(run.name, run.url) run.wait() CODE5 """A durable agent loop whose control flow is decided by typed answers. Instead of an all-purpose LLM choosing the next move in free text, a `Choice` picks the next action, a `Score` gates on confidence and a `Noul` decides whether the loop has enough to answer. Tools are Flyte tasks, so every step of the loop is durably recorded and replayable. flyte run typed_loop.py agent --ticket "Where is order AC-1042?" """ import enum import json import pathlib from dataclasses import dataclass, field import flyte from flyteplugins.typesafe_ai import Choice, Noul, Score, ask env = flyte.TaskEnvironment( name="system-one-loop", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "flyteplugins-typesafe-ai", ), secrets=[flyte.Secret(key="TYPESAFE_API_KEY", as_env_var="TYPESAFE_API_KEY")], resources=flyte.Resources(cpu=1, memory="1Gi"), ) # {{docs-fragment actions}} class NextAction(enum.Enum): """Given the history so far, what should the agent do next?""" TRACE_DELIVERY = "trace delivery" """look up where the customer's order currently is""" LOOKUP_ACCOUNT = "look up account" """check the account's status and whether it is locked""" FINAL_ANSWER = "answer now" """stop and answer the customer with what is already known""" ESCALATE = "hand to a human" """the request is hostile, unsafe or out of scope""" class Confidence(enum.IntEnum): """How confident are we that this next action is correct and safe?""" LOW = 0 """a guess; the history does not support it""" MEDIUM = 1 """plausible, but a human should see the result""" HIGH = 2 """clearly the right next move""" # {{/docs-fragment actions}} # {{docs-fragment step}} @dataclass class Step: """Everything the loop needs to decide, answered in one request per turn.""" action: Choice[NextAction] confidence: Score[Confidence] has_enough: Noul = field( metadata={ "question": "Is there enough information to answer the customer now?", "criteria": { "true": "every fact the answer needs is already in the history", "false": "a lookup is still missing", }, } ) made_progress: Noul = field( metadata={ "question": "Did the most recent observation add information the agent did not already have?", "criteria": {"true": "the last step produced something new", "false": "the loop is spinning"}, } ) hostile: Noul = field(metadata={"question": "Is this request hostile, manipulative or out of scope?"}) # {{/docs-fragment step}} # {{docs-fragment tools}} @env.task(cache="auto") async def trace_delivery(ticket: str) -> dict: """A stand-in for the real delivery backend.""" return {"order_id": "AC-1042", "status": "in_transit", "eta": "tomorrow EOD"} @env.task(cache="auto") async def lookup_account(ticket: str) -> dict: """A stand-in for the real account service.""" return {"account_ref": "acct-1001", "status": "active", "locked": False} TOOLS = {NextAction.TRACE_DELIVERY: trace_delivery, NextAction.LOOKUP_ACCOUNT: lookup_account} # {{/docs-fragment tools}} # {{docs-fragment loop}} @env.task async def agent(ticket: str, max_steps: int = 4) -> str: history: list[dict] = [{"role": "user", "content": ticket}] trace: list[dict] = [] for step in range(max_steps): s = await ask(Step, {"history": history}) action = s.action.value trace.append( { "step": step, "action": action.value, "confidence": s.confidence.value.name, "p_action": round(s.action.confidence, 3), "has_enough": round(s.has_enough.value, 3), } ) # Abstain as soon as the typed decision stops being trustworthy. The # gate is the confidence, not the Choice: a confident wrong action is # rarer than a low-confidence right one. if s.hostile.at(0.7) or not s.confidence.at_least(Confidence.MEDIUM): return json.dumps({"outcome": "escalate", "trace": trace}, indent=2) # Stop when there is enough to answer, when the model says to stop, or # when the loop has stopped making progress. if action in (NextAction.FINAL_ANSWER, NextAction.ESCALATE): break if s.has_enough.at(0.6) or (step > 0 and not s.made_progress.at(0.4)): break observation = await TOOLS[action](ticket) history.append({"role": "assistant", "content": f"called {action.value}"}) history.append({"role": "tool", "content": json.dumps(observation)}) trace[-1]["observation"] = observation return json.dumps({"outcome": "answered", "history": history, "trace": trace}, indent=2) # {{/docs-fragment loop}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.run(agent, ticket="Where is order AC-1042? It was due Tuesday.") print(run.name, run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/system-one/typed_loop.py* Two things to notice. The gate is the **confidence**, not the `Choice` โ€” a confident wrong action is rarer than a low-confidence right one. And `made_progress` is what stops a loop that has started spinning, which is otherwise the failure mode you only discover from the bill. ## Coerced values cross task boundaries `Choice`, `Score` and `Noul` are plain dataclasses, so Flyte carries them with nothing registered โ€” including on their own, not just inside a battery: CODE6 The caller gets a real `Choice` back, with the picked member, its confidence, and the whole distribution. That means the coercion step can be its own cached, retryable task rather than a function call buried inside a larger one. ## Related - [Decision models](./_index): the category, the use cases, and when not to reach for one. - [TypeSafe AI integration](../../../integrations/typesafe-ai/_index): installation, the full API, and how answer types are serialized. - [Typed decisions for agentic pipelines](../../../tutorials/agents/system-one-agents/_index): three pipelines and a measured A/B against a one-shot generative baseline. - [Build an agent](../../agents/build-agent/_index): the loop this slots into. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents === Durable, self-healing agents built from tasks and apps, with sandboxing and MCP. # Agents An agent is a program that decides what to do next by calling a model in a loop. On Flyte, each step of that loop is a task, which is what makes the agent durable: every model call, tool call, and intermediate result is recorded, so a run that fails partway through can be inspected and resumed rather than restarted. This matters more for agents than for batch jobs. An agent's control flow is decided at runtime by the model, so you cannot know in advance which path a run took. Recording each step is what makes the run explainable afterward. ```python @env.task def step(state: State) -> State: ... # one model call plus its tool calls ``` Nothing here is a separate agent framework. An agent is tasks for the reasoning steps, an app when it needs to be reachable over HTTP, and a sandbox when it executes code the model wrote. ### **Agents > Build an agent** Implement ReAct, Plan-and-Execute, and other agent patterns with full observability. ### **Agents > Build an MCP** Serve Model Context Protocol servers for AI assistants to interact with, hosted on Union.ai. ### **Agents > Sandboxing** Safely execute LLM-generated code with workflow sandboxes or ephemeral containers. ## Related ### **Agent frameworks** Run agents from OpenAI, Claude, LangGraph, CrewAI, and more as durable Flyte tasks. ### **Tasks** The unit each reasoning step is built from. ### **Inference > Decision models** Answer many typed questions in one call, with calibrated confidence, and decide what happens next in code. ## Subpages - **Agents > Build an agent** - Implement ReAct, Plan-and-Execute, and other agent patterns with full observability. - **Agents > Build an MCP** - Serve Model Context Protocol servers for AI assistants to interact with, hosted on Union.ai. - **Agents > Sandboxing** - Safely execute LLM-generated code with workflow sandboxes or ephemeral containers. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-agent === Implement ReAct, Plan-and-Execute, and other agent patterns with full observability. # Build an agent This section covers how to build, deploy, and run agentic AI applications on Union.ai. Building an agent on Union.ai breaks down into two **orthogonal** choices: 1. **How you build the agent loop**: plain Python, the built-in `flyte.ai.agents.Agent` harness, or a third-party framework (LangGraph, PydanticAI, OpenAI Agents SDK). 2. **How you deploy and run it**: as a task you invoke on demand, as a scheduled task driven by a `flyte.Trigger`, or as a long-running app (e.g. a webhook or chat UI). Any agent from axis (1) can be deployed via any pattern in axis (2). The two are independent, so you can start with a pure-Python loop run on demand and later move it behind a schedule or a webhook without rewriting the agent. ## How Union.ai maps to the agentic world - **`TaskEnvironment`**: The sandboxed execution environment for your agent steps. It configures the container image, hardware resources (CPU, GPU), and secrets (API keys). Think of it as defining "where this code runs." - **`@env.task`**: Turns any Python function into a remotely-executed step. Each task runs in its own container with the resources you specified. This is the equivalent of a node in LangGraph or n8n. - **Tasks calling tasks**: A task can `await` other tasks, and each called task gets its own container automatically. No separate workflow decorator needed. The calling task IS your workflow, this is how you build multi-step agentic pipelines. - **`@flyte.trace`**: Marks helper functions inside a task for fine-grained observability and caching. Each traced call appears as a span in the Union.ai dashboard, with its inputs and outputs captured and checkpointed. Use this on your LLM calls, tool executions, and routing decisions to get full visibility into every turn of the agent loop. > [!TIP] > See the **Get started > Quickstart** for a hands-on walkthrough. ## Ways to build an agent | Approach | When to use it | Guide | |----------|----------------|-------| | **Pure Python** | You want full control over the loop and the lightest possible dependency footprint | **Agents > Build an agent > Pure Python agents** | | **The `Agent` harness** | You want a batteries-included tool-use loop with tools, MCP servers, memory, and HITL built in | **Agents > Build an agent > Flyte-native agents** | | **Third-party frameworks** | You already have agents in LangGraph, CrewAI, OpenAI Agents SDK, Pydantic AI, and more | [Agent frameworks](../../../integrations/agents/_index) | | **An unsupported framework** | Your framework has no first-party plugin | **Agents > Build an agent > Bring your own framework** | The `Agent` harness has a few dedicated guides of its own: - **Agents > Build an agent > Flyte-native agents > Extending the agent class**: customize the loop by overriding `run`. - **Agents > Build an agent > Agent memory**: persist conversation history and artifacts across runs with `MemoryStore`. - **Agents > Build an agent > Agent chat UI**: give any agent a hosted chat interface. ## Deploying an agent Once you've built an agent, **Agents > Build an agent > Deploy an agent as a service** covers running it as a task, on a schedule via `flyte.Trigger`, and behind an `AppEnvironment` webhook. ## Related - [**Grafana Agent Observability**](../../../integrations/grafana-agent-observability/_index): export generations, tool calls, token usage, and cost, grouped by run. - [**OpenTelemetry**](../../../integrations/opentelemetry/_index): export tasks and traced steps as spans, with durable runs arriving as one trace. - [**Sandboxing**](../sandboxing/_index): safely execute LLM-generated code. - [**Build an MCP server**](../build-mcp/_index): serve Model Context Protocol servers for AI assistants to interact with Union.ai. {{< subpage-cards >}} ## Subpages - **Agents > Build an agent > Pure Python agents** - Write the agent loop yourself in plain Python, with any LLM library you like. - **Agents > Build an agent > Flyte-native agents** - Build an agent with flyte.ai.agents.Agent instead of hand-rolling the tool-call loop. - **Agents > Build an agent > Bring your own framework** - Adapt any agent framework to Flyte, where Flyte is the runtime and your framework owns the loop. - **Agents > Build an agent > Agent memory** - Give an agent continuity across runs with MemoryStore, instead of starting each run blank. - **Agents > Build an agent > Agent chat UI** - Serve a chat interface for your agent as a hosted app. - **Agents > Build an agent > Deploy an agent as a service** - Put a built agent behind a URL so other systems can call it. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-agent/python-agents === Write the agent loop yourself in plain Python, with any LLM library you like. # Pure Python agents The lightest way to build an agent on Union.ai is to write the loop yourself in plain Python. Union.ai is framework-agnostic: use any Python LLM library (OpenAI SDK, Anthropic SDK, LiteLLM, etc.) inside your tasks. The platform provides the production infrastructure layer: sandboxed execution, parallel fan-out, durable checkpointing, and observability for every step of the agent loop. This approach gives you full control over the loop and the smallest possible dependency footprint. If you'd rather not hand-roll the tool-call loop, see **Agents > Build an agent > Flyte-native agents**, which provides a batteries-included loop with tools, MCP servers, memory, and HITL. If you already have agents written in a third-party framework, see [Agent frameworks](../../../integrations/agents/_index) for the ten supported plugins, or **Agents > Build an agent > Bring your own framework** for the framework-agnostic pattern. Two decorators are all you need: | Decorator | What it does | Think of it as... | |-----------|-------------|-------------------| | **`@env.task`** | Runs a function in its own container on Union.ai with dedicated resources, dependencies, and secrets | A sandboxed agent step with its own execution environment | | **`@flyte.trace`** | Marks a helper function for observability, where each call appears as a span in the Union.ai dashboard with captured I/O | An observability hook on your LLM calls, tool executions, and routing decisions | ## ReAct pattern: Reason, Act, Observe (no framework needed) The [ReAct pattern](https://arxiv.org/abs/2210.03629) is the most common agent architecture: the LLM reasons about what to do, calls a tool, observes the result, and repeats until done. This example is implemented directly with flyte: ``` Thought โ†’ Action โ†’ Observation โ†’ repeat until done ``` ``` import json from openai import AsyncOpenAI from pydantic import BaseModel import flyte env = flyte.TaskEnvironment( name="agent_env", image=flyte.Image.from_debian_base(python_version=(3, 13)).with_pip_packages("openai"), resources=flyte.Resources(cpu=2, memory="2Gi"), secrets=[flyte.Secret(key="OPENAI_API_KEY")], ) TOOLS = {"add": lambda a, b: a + b, "multiply": lambda a, b: a * b} @flyte.trace # each call = a span in the dashboard async def reason(goal: str, history: str) -> dict: """LLM picks a tool or returns a final answer.""" r = await AsyncOpenAI().chat.completions.create( model="gpt-5.6-luna", response_format={"type": "json_object"}, messages=[ { "role": "system", "content": f"Tools: {list(TOOLS)}. Respond JSON: " '{"thought":..,"tool":..,"args":{}} or {"thought":..,"done":true,"answer":..}', }, {"role": "user", "content": f"Goal: {goal}\n\n{history}\nWhat next?"}, ], ) return json.loads(r.choices[0].message.content) @flyte.trace async def act(tool: str, args: dict) -> str: """Execute the chosen tool.""" return str(TOOLS[tool](**args)) class AgentResult(BaseModel): answer: str steps: int @env.task # runs in its own container async def react_agent(goal: str, max_steps: int = 10) -> AgentResult: history = "" for step in range(1, max_steps + 1): # the agent loop decision = await reason(goal, history) # Thought if decision.get("done"): return AgentResult(answer=str(decision["answer"]), steps=step) result = await act(decision["tool"], decision["args"]) # Action # Observation history += f"Step {step}: {decision['thought']} -> {decision['tool']}({decision['args']}) = {result}\n" return AgentResult(answer="Max steps reached", steps=max_steps) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-agent/building-agents/react_agent.py* ```bash flyte run agent.py react_agent --goal "What is (12 + 8) * 3?" # => AgentResult(answer='60', steps=3) ``` **What's happening under the hood:** - `react_agent` runs in a container with only `openai` installed and 2 CPU / 2GB RAM - Each `reason()` and `act()` call is traced, so you see every LLM call, every tool invocation, and every intermediate result in the Union.ai dashboard - The agent's inputs and final output are durably persisted, letting you inspect any past run end-to-end - Swap in your own tools (web search, database queries, API calls) by adding to the `TOOLS` dict > [!TIP] > See the **Project patterns > Advanced project: LLM reporting agent > Agentic refinement**, **Tasks > Build tasks > Traces**, and [more patterns (planner, debate, etc.)](https://github.com/unionai/workshops/tree/main/tutorials/multi-agent-workflows). ## Plan-and-Execute with parallel fan-out The [Plan-and-Execute pattern](https://blog.langchain.com/plan-and-execute-agents/) splits a complex query into sub-tasks, fans them out in parallel, then synthesizes the results. With Union.ai the fan-out is just `asyncio.gather()`, and each sub-task gets its own container, giving you true parallelism on separate hardware. ```python # workflow.py import os, json, asyncio, flyte from openai import AsyncOpenAI env = flyte.TaskEnvironment( name="research_env", image=flyte.Image.from_debian_base(python_version=(3, 13)).with_pip_packages("openai"), resources=flyte.Resources(cpu=2, memory="2Gi"), secrets=[flyte.Secret(key="OPENAI_API_KEY")], ) @flyte.trace async def llm(prompt: str) -> str: r = await AsyncOpenAI().chat.completions.create( model="gpt-5.6-luna", messages=[{"role": "user", "content": prompt}], ) return r.choices[0].message.content @env.task async def plan(query: str, n: int = 3) -> list[str]: """Split the query into sub-topics.""" raw = await llm( f'Break this into exactly {n} sub-topics. Return ONLY a JSON array of strings.\n\n{query}' ) return json.loads(raw)[:n] @env.task async def research(topic: str) -> str: """Research one sub-topic (each call = its own container).""" return await llm(f"Write a short, factual report on: {topic}") @env.task async def synthesize(query: str, reports: list[str]) -> str: """Combine the sub-reports into a final answer.""" sections = "\n\n".join(reports) return await llm(f"Synthesize a final answer to '{query}' from:\n\n{sections}") @env.task async def research_workflow(query: str, num_topics: int = 3) -> str: topics = await plan(query, num_topics) reports = list(await asyncio.gather(*[research(t) for t in topics])) # parallel fan-out return await synthesize(query, reports) ``` ```bash flyte run workflow.py research_workflow --query "Impact of storms on travel insurance payouts" ``` **What's happening under the hood:** ``` research_workflow (orchestrator) โ”œโ”€โ”€ plan โ†’ LLM breaks query into N sub-topics [container 1] โ”œโ”€โ”€ research(t1) โ†’ researches one sub-topic [container 2] โ” โ”œโ”€โ”€ research(t2) โ†’ researches one sub-topic [container 3] โ”œ parallel โ”œโ”€โ”€ research(t3) โ†’ researches one sub-topic [container 4] โ”˜ โ””โ”€โ”€ synthesize โ†’ LLM combines reports into final answer [container 5] ``` - **Fan-out:** `asyncio.gather()` launches all research tasks in parallel, each in its own container - **Observability:** `@flyte.trace` on each LLM call means every prompt and response is visible as a span in the Union.ai dashboard - **Durable checkpointing:** Each task's output is persisted. If `synthesize` fails, re-running skips the completed `plan` and `research` steps (with caching enabled) > [!TIP] > The same fan-out works with any framework inside the `research` task. See [Agent frameworks](../../../integrations/agents/_index) for versions that run a LangGraph, CrewAI or OpenAI Agents SDK researcher inside each parallel container, with the tool calls durable on their own. ## More agentic patterns Union.ai is framework-agnostic, so these patterns work with any LLM library. Each maps to well-known agent architectures: | Pattern | What it does | When to use it | Link | |---------|-------------|----------------|------| | **ReAct** | Reason โ†’ Act โ†’ Observe loop with tool calling | Single-agent tasks with tools (API calls, search, code execution) | [multi-agent-workflows/react](https://github.com/unionai/workshops/tree/main/tutorials/multi-agent-workflows) | | **Plan-and-Execute** | LLM creates a plan, independent steps fan out in parallel, results are synthesized | Complex queries that decompose into parallel sub-tasks | [multi-agent-workflows/planner](https://github.com/unionai/workshops/tree/main/tutorials/multi-agent-workflows) | | **Evaluator-Optimizer (Reflection)** | Generate โ†’ Critique โ†’ Refine loop until quality threshold met | Content generation, code generation, any task with clear quality criteria | **Project patterns > Advanced project: LLM reporting agent > Agentic refinement** | | **Orchestrator-Workers (Manager)** | Supervisor agent delegates to specialist worker agents, reviews quality, requests revisions | Multi-agent systems where sub-tasks require different expertise | [multi-agent-workflows/manager](https://github.com/unionai/workshops/tree/main/tutorials/multi-agent-workflows) | | **Debate** | Multiple agents solve independently, then debate to consensus | High-stakes decisions where diverse reasoning improves accuracy | [multi-agent-workflows/debate](https://github.com/unionai/workshops/tree/main/tutorials/multi-agent-workflows) | | **Sequential (Prompt Chaining)** | Static pipeline of LLM calls, no dynamic routing | Predictable multi-step transformations (extract โ†’ validate โ†’ format) | [multi-agent-workflows/sequential](https://github.com/unionai/workshops/tree/main/tutorials/multi-agent-workflows) | ## How Union.ai's primitives map to the agent stack If you're coming from LangGraph, CrewAI, OpenAI Agents SDK, or similar frameworks, here's how the concepts you already know translate: **Your agent loop** is a Python `for`/`while` loop inside an `@env.task`. Each iteration calls `@flyte.trace`-decorated functions for reasoning and tool execution. Union.ai doesn't impose a loop structure; you write it in plain Python, which means any pattern (ReAct, reflection, plan-and-execute) works naturally. **Tool calling** is just calling Python functions. Define your tools as regular functions, decorate them with `@flyte.trace` for observability, and call them from within the agent loop. Use any tool-calling mechanism your LLM SDK provides (OpenAI function calling, Anthropic tool use, LangChain `bind_tools()`). MCP servers can be accessed from within tasks using the MCP Python SDK. **Parallel fan-out** (LangGraph's `Send()`, n8n's Split in Batches) is `asyncio.gather()`. Each awaited task gets its own container, giving you true parallelism on separate hardware, not just concurrent coroutines. **State and checkpointing** (LangGraph's Checkpointers, Threads) is automatic. Every task's inputs and outputs are durably persisted. `@flyte.trace` adds sub-step checkpoints within a task. Re-running with caching enabled skips completed steps, Union.ai's equivalent of replaying from a checkpoint. **Routing and conditional logic** (LangGraph's `add_conditional_edges`, n8n's If/Switch nodes) is Python `if/else`. No special API needed. **Environment isolation** (different dependencies per step) is `TaskEnvironment`. Your LLM step can use `langchain==0.3`; your data step can use `pandas` + GPU. Each gets its own container image. **Guardrails and validation** are Python code between steps: `if/else` checks, Pydantic validation, structured output parsing, or libraries like NeMo Guardrails. Raise an exception to fail a step and trigger retries. **Observability:** The Union.ai dashboard shows the full execution tree with per-step inputs, outputs, logs, resource usage, and timing. `@flyte.trace` adds spans within a task for fine-grained visibility into individual LLM calls and tool invocations. For LLM-specific metrics (token usage, cost per call), integrate with Langfuse or LangSmith from within your tasks. ## Next steps - **Agents > Build an agent > Flyte-native agents**: skip the boilerplate with a built-in tool-use loop. - **Agents > Build an agent > Deploy an agent as a service**: run this agent on a schedule or behind a webhook. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-agent/flyte-agents === Build an agent with flyte.ai.agents.Agent instead of hand-rolling the tool-call loop. # Flyte-native agents `flyte.ai.agents.Agent` is a flyte-native, batteries-included agent harness. Instead of hand-rolling the tool-call loop (as in **Agents > Build an agent > Pure Python agents**), you declare a set of tools and instructions, and the harness drives a robust LLM โ†” tool loop for you. The harness deeply integrates with Union.ai: - **Tools** can be plain Python callables, `@flyte.trace` helpers, `@env.task` durable tasks, `LazyEntity` remote-task references, or pre-built `AgentTool` instances. - **MCP servers** (Slack, GitHub, Linear, filesystem, โ€ฆ) are first-class: pass a `MCPServerSpec` and their tools are loaded into the catalog automatically. - **Memory** persists across runs via `flyte.io.Dir`. See **Agents > Build an agent > Agent memory**. - **HITL** support pauses the loop and asks a human for approval before sensitive tools execute. ## How it works `Agent(...)` collapses heterogeneous tool sources into a single tool registry plus an auto-generated system prompt. `agent.run(message)` then drives an LLM โ†” tool-call loop: 1. Send the conversation and tool catalog to the LLM. 2. If the assistant returns tool calls, execute each one (sequentially or concurrently), append the results back into the message history, and loop. 3. Stop when the assistant returns a plain-text reply (no tool calls) or when `max_turns` is reached. ```mermaid flowchart TB inputs["tools (fn / task / MCP),
skills, memory, and instructions"] inputs --> agent[["Agent
(tool registry, skills, system prompt)"]] subgraph loop["agent.run(message) ยท agent.run.aio(message) in async code"] direction TB llm["call_llm"] --loop max_turns times--> branch{"tool_calls?"} branch -- yes --> exec["execute tools
(optional HITL approval)"] exec --> llm branch -- no --> done["final reply"] end user(["user message"]) --> llm agent --> llm done --> result(["AgentResult
+ updated memory"]) ``` The call returns an `AgentResult` with the final `summary`, an `error` string (empty on success), and the number of `attempts` (turns) taken. ### Sync vs async `agent.run` is synchronous by default. Inside `async def` code (Flyte tasks, FastAPI handlers, etc.) use the `.aio(...)` companion instead. | Context | Call | |---------|------| | Scripts, notebooks, sync code | `result = agent.run(message)` | | `async def` tasks / handlers | `result = await agent.run.aio(message)` | ## A minimal agent Declare a few tools as plain async functions, build an `Agent`, and call `run`. The harness reads each tool's signature and docstring to build the JSON schema and description the LLM sees, so well-documented tools work best. ``` from flyte.ai.agents import Agent async def add(x: float, y: float) -> float: """Add two numbers and return their sum.""" return x + y async def multiply(x: float, y: float) -> float: """Multiply two numbers and return their product.""" return x * y async def get_weather(city: str) -> dict[str, str | float]: """Return a weather snapshot for `city`. In a real agent, replace this stub with a call to a weather API (and promote it to a ``@env.task`` for durable, retryable execution). """ fake = { "new york": {"temperature_f": 68.4, "conditions": "partly cloudy"}, "san francisco": {"temperature_f": 61.0, "conditions": "foggy"}, "tokyo": {"temperature_f": 74.2, "conditions": "sunny"}, } return fake.get(city.lower(), {"temperature_f": 70.0, "conditions": "clear"}) agent = Agent( name="basic-helper", instructions=( "You are a friendly assistant. Use the available tools to look up " "weather and compute math. Reply with a single sentence summary." ), model="claude-haiku-4-5", tools=[add, multiply, get_weather], max_turns=6, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-agent/agent-harness/basic_agent.py* Call it synchronously, or with `await agent.run.aio(message)` inside async code: CODE1 ## Tools The `tools=` argument accepts a sequence (or a `{name: tool}` mapping) of any mix of: | Tool source | What it is | When to use it | |-------------|------------|----------------| | Plain callable | A sync or async Python function | Lightweight, in-process helpers | | `@flyte.trace` helper | A traced function | In-process helpers you want as spans in the dashboard | | `@env.task` template | A durable Flyte task | Heavy compute / IO that should run on-cluster, be retryable, and observable | | `LazyEntity` | A reference to a remote deployed task | Calling already-deployed tasks by name | | `AgentTool` | A pre-built tool descriptor | Renaming, custom schema, or HITL gating | Pass a mapping to expose a tool under a different name to the LLM: CODE2 When a tool is an `@env.task`, the harness invokes it with `task.aio(...)`, so each tool call executes durably on the cluster and shows up in the Union.ai dashboard. ### Customizing a tool with `tool(...)` Use the `tool` decorator/wrapper to rename a tool, override its description, or gate it behind human approval, without writing an `AgentTool` by hand: CODE3 When the LLM tries to call a tool marked `requires_approval=True`, the harness invokes the agent's `approval_callback` and waits for a boolean decision before executing. The default callback raises a human-input request via the `flyteplugins-hitl` plugin and blocks until a human approves or denies. If denied, the agent receives a synthetic tool message explaining the rejection so it can recover gracefully. Pass `call_handler` to intercept *how* a tool is invoked. The handler is an async callback `(call_llm, tool_fn, **kwargs) -> result` that runs in place of the default execution. Await `tool_fn` to run the default behavior, or reach into `tool_fn.target` (the underlying task / callable) and `call_llm` (the agent's LLM callback) to do something custom. For example, ask the LLM how to size compute, then run the task with overridden resources and retry on OOM: CODE4 ## MCP integration The harness can connect to one or more [Model Context Protocol (MCP)](https://modelcontextprotocol.io) servers and surface their tools transparently. On the first `run` call, the harness connects to each server, lists its tools, and registers them in the catalog. Declare servers with `MCPServerSpec`: either an HTTP(S) `url` (for streamable-http / SSE transports) or a `command` (for stdio servers): CODE5 Useful `MCPServerSpec` knobs: - `tool_prefix`: prepend a prefix to every tool name from this server to avoid collisions. - `tool_filter`: an allowlist of tool names to expose to the LLM (`None` exposes all). - `headers`: HTTP headers (e.g. `Authorization`) for authenticated servers. MCP support requires the `mcp` package: `pip install 'flyte[mcp]'`. To serve your own MCP servers on Union.ai, see [Build an MCP](../build-mcp/_index). ## Skills Pass extra context to append to the system prompt via `skills=`. Each entry is either a literal string or a `pathlib.Path` to a local text file: CODE6 ## Observability Every step of the loop emits a typed `AgentEvent` (`agent_start`, `turn_start`, `tool_start`, `tool_end`, `approval_request`, โ€ฆ). Subscribe by setting the `agent_progress_cb` context variable to forward events to logs, NDJSON streams, websockets, or Union.ai reports. The built-in chat UI uses this hook to stream progress; see [Add a chat UI](agent-chat-ui.md). ## Extending the agent class The default loop is robust, but sometimes you need custom behavior around it: input guardrails, output post-processing, a different control flow, or extra bookkeeping. The cleanest way to do this is to subclass `Agent` and override its `run` method. `Agent` is a [dataclass](https://docs.python.org/3/library/dataclasses.html), and `run` is the single public entry point that drives the loop. There are two common strategies: 1. **Wrap the built-in loop**: add logic before and after `super().run(...)`. Best when you mostly want the default behavior plus pre/post steps. 2. **Replace the loop entirely**: implement `run` (and `tool_descriptions`) yourself. Best when you need a fundamentally different control flow but still want to plug into the rest of the ecosystem (e.g. the chat UI). ### `run` is sync-by-default `Agent.run` is wrapped with `@syncify`, which means callers can use it synchronously (`agent.run(...)`) or await the async companion (`await agent.run.aio(...)`). When you override `run`, decorate your async implementation with `@syncify` to keep the same dual interface, and call the parent loop via `await super().run.aio(...)`. ### Strategy 1: wrap the built-in loop Subclass `Agent` as a dataclass so you can add your own fields, then override `run` to add an input guardrail and post-process the answer: CODE7 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-agent/extending-the-agent/guarded_agent.py* Instantiate and call it just like a regular `Agent`: CODE8 Because `GuardedAgent` still subclasses `Agent`, every other feature (tools, MCP servers, memory, HITL) keeps working unchanged. ### Strategy 2: implement `run` from scratch If you want a completely custom loop, implement the `AgentProtocol`: a class exposing `run(message, memory) -> AgentResult` and `tool_descriptions() -> list[dict]`. Any object satisfying this protocol can be used anywhere the harness is accepted, including the [chat UI](agent-chat-ui.md). `memory` may be a `list[dict]` of prior messages (a chat history) or a `MemoryStore`. CODE9 > [!NOTE] > `AgentResult` carries `summary`, `error`, `attempts`, and (for code-generating agents) `code` and `charts`. Populate the fields relevant to your loop; downstream consumers like the chat UI read `summary` and `error`. ### Choosing between subclassing and composition Subclassing is the right tool when you need to change *how the loop runs*. If you only need to change *what happens around a run* (for example, looping the agent until a condition is met, or combining several agents) prefer plain composition: call `agent.run.aio(...)` from inside your own `@env.task`. This keeps the harness untouched and your orchestration logic explicit and observable in the dashboard. ## Next steps - **Agents > Build an agent > Agent memory**: persist transcript and artifacts across runs. - **Agents > Build an agent > Agent chat UI**: wrap the agent in a hosted chat interface. - **Agents > Build an agent > Deploy an agent as a service**: run on a schedule or behind a webhook. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-agent/bring-your-own-framework === Adapt any agent framework to Flyte, where Flyte is the runtime and your framework owns the loop. # Bring your own framework The [supported plugins](../../../integrations/agents/_index) are worked examples of one underlying idea: **Union.ai is the runtime, your framework is the loop.** If your agent library is written in Python, it runs on Union.ai with no special plugin. This page is a framework-agnostic template for the frameworks that don't have one. Drop in any library ([AutoGen](https://microsoft.github.io/autogen/), [smolagents](https://github.com/huggingface/smolagents), [Atomic Agents](https://github.com/BrainBlend-AI/atomic-agents), a raw provider SDK, or your own homegrown loop) wherever the comments say so. > [!NOTE] Check for a plugin first > If your framework is one of the ten with a first-party adapter, use that instead. The plugins give you per-tool containerization, model-turn replay and cross-run memory that this template does not. See [Agent frameworks](../../../integrations/agents/_index). ## How much control does the framework give you? Frameworks differ in how much of the agent loop they own, which shapes how you integrate them: | Level of control | What it means | Integration pattern | |------------------|---------------|---------------------| | **You own the loop** | The framework gives you primitives (graph nodes, tools) and you wire the control flow | Decorate nodes with `@flyte.trace` and run the compiled graph inside a task | | **The framework owns the loop, you own the tools** | The framework runs the tool-calling loop; you provide tools as plain functions | Have tools delegate to durable `@env.task`s | | **The framework owns everything** | The framework builds and runs the agent from configuration | Wrap the whole run in a task and trace the seam below the loop | Whichever model your framework uses, the integration is the same in spirit: the framework decides *what* the agent does next, and Union.ai decides *where and how durably* each step runs. ## The core pattern Put your framework's agent invocation inside an `@env.task`. The task gives you a container, durable inputs/outputs, retries, and a span in the dashboard. Everything inside the task is ordinary Python, so the framework behaves exactly as it does locally. ```python import flyte # 1. Declare the runtime: image (with YOUR framework's deps), resources, secrets. env = flyte.TaskEnvironment( name="my-agent", image=flyte.Image.from_debian_base(python_version=(3, 13)).with_pip_packages( # --> your agent framework + its provider packages go here, e.g.: # "crewai", "smolagents", "autogen-agentchat", ... ), resources=flyte.Resources(cpu=1, memory="1Gi"), secrets=[flyte.Secret(key="ANTHROPIC_API_KEY")], # --> your model provider key(s) ) @env.task(report=True) async def run_agent(prompt: str) -> str: # 2. Build/configure your framework's agent exactly as you would locally. # --> your framework setup goes here # agent = MyFramework.Agent(model=..., tools=[...], instructions=...) # 3. Run it. Use the framework's own (sync or async) entry point. # --> invoke your framework here # result = await agent.run(prompt) # 4. Return a serializable value (str, pydantic model, dataclass, ...). # return result.output ... if __name__ == "__main__": flyte.init_from_config() run = flyte.run(run_agent, prompt="...") # --> your prompt / inputs print(run.url) ``` That is the whole integration. The remaining sections are optional enhancements that make the framework more durable and observable. ## Make tools durable Most frameworks let a tool be any Python callable. To make a tool durable, retryable, and independently observable, have the framework's tool delegate to an `@env.task`. The framework still "owns" the tool; the heavy lifting runs on-cluster. ```python # A durable task that does the real work (IO, compute, external calls). @env.task async def fetch_data(source: str) -> dict: # --> your real tool implementation (API call, DB query, scrape, ...) ... # Register it with your framework using whatever tool API it exposes. # The body just awaits the durable task. # # @my_framework.tool # --> your framework's tool decorator/registration # async def get_data(source: str) -> dict: # """Tool description the LLM sees.""" # return await fetch_data(source) # runs as a Flyte task, durable + traced ``` > [!TIP] > Reach for an `@env.task` when a tool does real work you want retried, cached, or run on its own hardware (GPU, more memory). For lightweight in-process helpers, a plain `@flyte.trace` function (below) is enough. ## Trace the framework's internals If your framework exposes hooks, callbacks, or lets you wrap its node/step functions, decorate those with `@flyte.trace` to turn each LLM call, tool call, and routing decision into a span, with inputs and outputs captured and checkpointed. ```python @flyte.trace async def call_model(messages: list[dict]) -> str: # --> wrap the framework's model call (or pass this as the framework's LLM hook) ... @flyte.trace async def route(state) -> str: # --> wrap a routing / decision function so the branch is visible in the dashboard ... ``` For frameworks that don't expose hooks, wrap the whole run in `flyte.group(...)` to keep its trace tidy: ```python @env.task(report=True) async def run_agent(prompt: str) -> str: with flyte.group("my-framework-run"): # groups everything below under one span # --> your framework invocation ... ``` ## Fan out across containers Run many independent agents in parallel, each in its own container, with `asyncio.gather()`. This works for any framework because each call is just an awaited task. ```python import asyncio @env.task async def run_one(task_input: str) -> str: # --> one self-contained agent run for a single input ... @env.task async def run_many(inputs: list[str]) -> list[str]: # Each run_one call lands in its own container. results = await asyncio.gather(*[run_one(i) for i in inputs]) return list(results) ``` ## Checklist To bring any Python agent framework onto Union.ai: 1. **Wrap the run**: call the framework's entry point inside an `@env.task`. 2. **Declare deps**: add the framework + provider packages to the task's `image`. 3. **Supply secrets**: mount model-provider API keys via `flyte.Secret`. 4. **(Optional) Durable tools**: have tools delegate to `@env.task`s. 5. **(Optional) Observe**: decorate hooks/steps with `@flyte.trace`, or wrap in `flyte.group(...)`. 6. **(Optional) Scale**: fan out with `asyncio.gather()` for parallel, per-container runs. ## Next steps - [Agent frameworks](../../../integrations/agents/_index): the ten frameworks with a first-party plugin, if yours is one of them. - **Agents > Build an agent > Flyte-native agents**: a built-in, batteries-included loop if you'd rather not bring a framework. - **Agents > Build an agent > Pure Python agents**: hand-roll the loop with no framework at all. - **Agents > Build an agent > Deploy an agent as a service**: run your agent on a schedule or behind a webhook. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-agent/agent-memory === Give an agent continuity across runs with MemoryStore, instead of starting each run blank. # Agent memory By default, an **Agents > Build an agent > Flyte-native agents** is stateless: each `run` starts from a blank conversation. `MemoryStore` gives an agent continuity across runs by persisting both the conversation transcript and arbitrary path-addressed artifacts to a `flyte.io.Dir`. This is what lets a scheduled or webhook-driven agent remember what it did last time. Use cases: - An "inbox triage" agent that recalls which threads it has already responded to. - A research agent that builds up a scratchpad over many days. - Any sleep/wake pattern where the agent wakes on a schedule and resumes prior context. ## What a `MemoryStore` holds A `MemoryStore` combines two complementary stores backed by a working directory: - **`messages`**: the live LLM conversation transcript, managed by the agent. Mutate it only via `append()` / `extend()`. - **Path-addressed files**: arbitrary named blobs under the working root. Read and write them with `read_text` / `write_text` / `read_json` / `write_json` / `list_paths`. The on-disk layout under the root looks like: ``` /messages.json # transcript /.{txt,json,โ€ฆ} # path-addressed entries /meta/.json # per-entry metadata (sha, actor, ts) /audit/log.jsonl # opt-in audit trail /versions//_.txt # opt-in version history ``` ## Sync vs async The path-addressed I/O methods (`read_text`, `read_json`, `write_text`, `write_json`, `get_meta`, `current_sha`) and the lifecycle methods (`create`, `get_or_create`, `save`) are sync-by-default with an `.aio(...)` companion. Inside `async def` tasks, use the `.aio` form. ## Keyed stores: the easy path For durable agent memory, use a **keyed store**. `MemoryStore.get_or_create(key=...)` loads an existing store if present, otherwise creates a new one, saving to a deterministic blob-store namespace under the active Union.ai raw-data root: ``` {storage_root}/agents/memory-store/v0/{org}/{project}/{domain}/{key} ``` First, define the agent. Here it's a small research assistant with a single, **stateless** `web_search` tool. Its continuity comes from memory, not from the tool: ``` @env.task async def web_search(query: str, max_results: int = 3) -> list[dict[str, str]]: """Search the web for `query` and return the top matching results. A stateless tool โ€” it knows nothing about the agent's memory. But because the results it returns are recorded in the conversation transcript, the agent can recall or build on them in a later run without searching again. This stub returns canned results so the example runs offline. In a real agent, replace it with a call to a search API (Tavily, Brave, SerpAPI, โ€ฆ); keeping it an `@env.task` makes each search durable, retryable, and observable in the dashboard. """ return [ { "title": f"{query.title()} โ€” overview ({i + 1})", "url": f"https://example.com/?q={query.replace(' ', '+')}&r={i + 1}", "snippet": f"Key point #{i + 1} about {query}.", } for i in range(max_results) ] agent = Agent( name="memory-assistant", instructions=( "You are a personal research assistant with long-term memory. You " "remember what the user is working on and the facts they share, because " "your prior conversation transcript is always available. Use web_search " "to look things up, and reuse earlier findings from the conversation " "instead of searching again when you already have the answer." ), model="claude-haiku-4-5", tools=[web_search], max_turns=12, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-agent/agent-memory/agent_with_memory.py* Reuse the same `key` across runs to keep continuity. The chat task below picks up where the previous run left off (see the [full example](https://github.com/unionai/unionai-examples/tree/main/v2/user-guide/build-agent/agent-memory/agent_with_memory.py) for the `TaskEnvironment` setup): CODE2 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-agent/agent-memory/agent_with_memory.py* The agent has no note-taking tools. Continuity comes entirely from the persisted transcript, and it remembers two kinds of things for free: the **facts the user shares** and the **results its tools return**. The first run records both in `messages.json`; a later run with the same `memory_key` reloads and prepends them, so the agent recalls earlier context, and reuses prior `web_search` findings instead of searching again. That is the core value of `MemoryStore`: no extra plumbing required. ## Working with a MemoryStore independently Beyond the transcript, you can persist structured artifacts under arbitrary paths in the same store. This is optional (most agents get all the continuity they need from the transcript above) but it's useful when you want durable, queryable state (a scratchpad, a dedupe ledger, intermediate results). A flyte task can commit its own artifact by loading the keyed store, read-modify-writing a path-addressed file, and calling `save()`. Every write is recorded in a metadata sidecar (sha256, actor, timestamp) and, by default, appended to an audit log: CODE3 > [!NOTE] Coordinating tool writes with the transcript > Artifacts live on independent paths (e.g. `notes/notes.json`) from the transcript (`messages.json`), so they never collide. But when a tool writes to the same keyed store that the orchestrator also saves, the orchestrator's working copy goes stale mid-run. Reload the store with `get_or_create` after `agent.run`, carry over the updated transcript (`reloaded.messages = result.memory.messages`), and save once. Otherwise the orchestrator's final save re-uploads a stale copy and clobbers the tool's artifact. ## Optimistic concurrency When several tasks or agents share one keyed store (e.g. parallel tool calls, or a sleep/wake pattern), guard against lost updates by passing `expected_sha=`. The write succeeds only if the current content still matches; otherwise it raises `ConcurrencyError`: CODE4 ## Optional capabilities `MemoryStore` (and `create` / `get_or_create`) accept a few flags: | Option | Default | What it does | |--------|---------|--------------| | `audit` | `True` | Append every successful write to `audit/log.jsonl`. Inspect with `audit_tail(n)`. | | `keep_versions` | `False` | Snapshot every write under `versions/` for full history (โ‰ˆ 2ร— storage per write). | | `read_only_prefixes` | `()` | Reject direct writes into the given prefixes (e.g. `("memory/",)`), so the agent must stage proposals elsewhere and a trusted pipeline promotes them. | The internal `audit/`, `meta/`, and `versions/` prefixes and `messages.json` are reserved: writes to them are rejected, and they're excluded from `list_paths`. ## Passing memory to the agent Memory is not attached to the agent: it is passed in per call and returned on the result. `agent.run(message, memory=store)` prepends the store's prior transcript, runs the loop, and appends the new turn back onto the store. Persisting is explicit: `run` never writes on its own, so call `memory.save()` (or `await memory.save.aio()`) yourself afterward. CODE5 You can also pass a plain `list[dict]` of prior messages as `memory` for a stateless, single-shot history (nothing is persisted in that case). ## Lower-level usage Every `MemoryStore` is **keyed**: there is no unkeyed/ephemeral store. You normally obtain one via `MemoryStore.create(key=...)` or `MemoryStore.get_or_create(key=...)`, but direct construction is supported for advanced use and serialization (`MemoryStore` is a Flyte I/O type, so it can be passed as a task input/output). `save()` takes no arguments: it always uploads the working root to the deterministic keyed `remote_path`. When `root` is omitted, a temporary working directory is created and cleaned up automatically. ## Next steps - [The Flyte Agent harness](flyte-agents.md): how the agent loop uses `memory`. - **Agents > Build an agent > Deploy an agent as a service**: schedule a memory-backed agent so it resumes context on each wakeup. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-agent/agent-chat-ui === Serve a chat interface for your agent as a hosted app. # Agent chat UI A useful way to interact with an agent is through a chat interface. Because Union.ai can [host apps](../../apps/build-apps/_index) behind a URL, you can serve a chat UI for your agent with no separate infrastructure. There are two approaches: 1. **`AgentChatAppEnvironment`**: the fastest path. Any agent that implements the `AgentProtocol` (including the built-in `Agent`, in tool-use or `code_mode`) gets a hosted chat shell, tool sidebar, and streaming for free. 2. **A custom FastAPI app**: full control over the UI. Wrap the agent in a `FastAPIAppEnvironment` and serve your own HTML/CSS/JS. Both reuse the same agent object, so you can start with the built-in shell and graduate to a custom UI later. ## Option 1: the built-in chat UI `flyte.ai.chat.AgentChatAppEnvironment` wraps an agent in a hosted chat app. Since `Agent` implements the `AgentProtocol`, it plugs straight in: ``` import flyte from flyte.ai.agents import Agent from flyte.ai.chat import AgentChatAppEnvironment, CustomTheme task_env = flyte.TaskEnvironment( name="chat-agent-tools", image=flyte.Image.from_debian_base().with_pip_packages("litellm", "httpx"), resources=flyte.Resources(cpu=1, memory="512Mi"), secrets=[flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY")], ) @task_env.task async def search_docs(query: str, max_results: int = 3) -> list[dict[str, str]]: """Search internal documentation (stub) and return matching snippets.""" corpus = [ {"title": "Tasks", "body": "Define a task by decorating an async function with @env.task."}, {"title": "Triggers", "body": "Schedule a task by attaching a flyte.Trigger with a flyte.Cron automation."}, {"title": "Secrets", "body": "Mount cluster-managed secrets into a task with flyte.Secret(...)."}, ] needle = query.lower() matches = [d for d in corpus if needle in d["body"].lower() or needle in d["title"].lower()] return matches[:max_results] agent = Agent( name="docs-helper", instructions=( "You are a friendly internal docs assistant. Use search_docs to find " "relevant snippets. Always cite the doc title in your final answer." ), model="claude-haiku-4-5", tools=[search_docs], max_turns=8, ) @task_env.task(report=True) async def chat_entrypoint(message: str, memory: list[dict]) -> dict: """Parent task that owns the agent loop and the nested tool tasks.""" result = await agent.run.aio(message, memory=memory) return { "summary": result.summary, "error": result.error, "attempts": result.attempts, "charts": [], "code": "", } env = AgentChatAppEnvironment( name="docs-agent-chat-ui", agent=agent, task_entrypoint=chat_entrypoint, title="Internal docs assistant", subtitle="Backed by a flyte.ai.agents.Agent + durable Flyte task tools.", theme=CustomTheme(accent_color="#6F2AEF", accent_hover_color="#8B52F2"), prompt_nudges=[ {"label": "Basics", "prompt": "Can you show me a hello world example?"}, {"label": "Triggers", "prompt": "How do I schedule a task?"}, ], depends_on=[task_env], image=flyte.Image.from_debian_base().with_pip_packages("litellm", "fastapi", "uvicorn"), resources=flyte.Resources(cpu=2, memory="2Gi"), secrets=flyte.Secret("internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), passthrough_auth=True, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-agent/agent-chat-ui/agent_chat_ui.py* The `task_entrypoint` is a parent task that owns the agent loop, so the nested durable tool tasks run correctly under it. The chat shell streams progress by subscribing to the agent's `agent_progress_cb` events. ## Option 2: a custom FastAPI chat app When you want to control the look and feel, wrap any `AgentProtocol`-compatible agent in a `FastAPIAppEnvironment` and serve your own UI. A natural fit is an `Agent` in **code mode** (`code_mode=True`): each turn the LLM writes Python that runs in a [sandbox](../sandboxing/_index) with the tools exposed as functions, returning code + a summary (and any charts you choose to surface), all behind a conversational web interface. The architecture is small: ``` Browser (Chat UI) โ”œโ”€โ”€ GET / -> embedded HTML/CSS/JS chat interface โ”œโ”€โ”€ GET /api/tools -> JSON list of available tool descriptions โ””โ”€โ”€ POST /api/chat -> { message, memory } -> { code, charts, summary, error } โ””โ”€โ”€ Agent.run(message, memory) ``` The app itself is just a FastAPI server. The endpoints call the agent's `run.aio` and `tool_descriptions` methods: ```python import pathlib from fastapi import FastAPI from fastapi.responses import HTMLResponse from pydantic import BaseModel import flyte from flyte.ai.agents import Agent from flyte.app.extras import FastAPIAppEnvironment app = FastAPI(title="Chat Data Analytics Agent") env = FastAPIAppEnvironment( name="chat-analytics-agent", app=app, image=flyte.Image.from_debian_base().with_pip_packages( "fastapi", "uvicorn", "httpx", "pydantic-monty", "litellm", ), secrets=flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), scaling=flyte.app.Scaling(replicas=1), ) agent = Agent( name="analytics", instructions="You are a data analyst. Use the tools to fetch, aggregate, and chart data.", tools=ALL_TOOLS, code_mode=True, max_turns=15, ) class ChatRequest(BaseModel): message: str memory: list[dict] = [] class ChatResponse(BaseModel): code: str = "" charts: list[str] = [] summary: str = "" error: str = "" @app.get("/api/tools") async def get_tools() -> list[dict]: """Return JSON descriptions of available tool functions (for the sidebar).""" return agent.tool_descriptions() @app.post("/api/chat") async def chat(req: ChatRequest) -> ChatResponse: """Generate code, run it in the sandbox, and return results.""" result = await agent.run.aio(req.message, memory=req.memory) return ChatResponse(code=result.code, charts=result.charts, summary=result.summary, error=result.error) @app.get("/", response_class=HTMLResponse) async def index() -> HTMLResponse: """Serve the embedded chat UI.""" return HTMLResponse(content=CHAT_HTML) if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) app_handle = flyte.serve(env) print(f"Deployed Chat Analytics Agent: {app_handle.url}") ``` `CHAT_HTML` is the embedded front-end (a single HTML string with the chat markup, styles, and a small fetch-based client that POSTs to `/api/chat` and renders the returned charts and summary). `ALL_TOOLS` is the agent's tool registry. Keeping both in their own modules means adding a tool is the only change required; the agent auto-generates its system prompt from each tool's signature and docstring. Run it locally during development, then deploy with one command: ```bash # Local development python chat_app.py # Deploy to Union.ai flyte deploy chat_app.py env ``` Union.ai assigns a URL, handles TLS, and auto-scales the app. > [!TIP] > Drop `code_mode=True` to serve a standard tool-use **Agents > Build an agent > Flyte-native agents** (or plug in any object implementing the `AgentProtocol`) behind the same UI. The endpoints only depend on `run.aio` and `tool_descriptions`. ## Next steps - **Agents > Build an agent > Flyte-native agents**: the agent powering the chat UI. - [Sandboxing](../sandboxing/_index): how an `Agent` in code mode safely executes generated code. - **Agents > Build an agent > Deploy an agent as a service**: other ways to run an agent (task, schedule, webhook). === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-agent/deploy-agent-as-service === Put a built agent behind a URL so other systems can call it. # Deploy an agent as a service Once you've built an agent (with **Agents > Build an agent > Pure Python agents**, the **Agents > Build an agent > Flyte-native agents**, or a [third-party framework](../../../integrations/agents/_index)), *how* you run it is an independent choice. The same agent object can be deployed in several ways: | Pattern | When to use it | What invokes the agent | |---------|----------------|------------------------| | **As a task** | On-demand runs from the CLI, a notebook, or another service | `flyte.run(...)` | | **As a scheduled task** | Recurring autonomous wakeups (triage, monitoring, reports) | A `flyte.Trigger` (cron or fixed-rate) | | **Behind a webhook** | React to external events (GitHub, paging tools, CI) | An HTTP `POST` to an `AppEnvironment` | All three wrap the agent loop in a regular Flyte task, so every run is durable, retryable, and observable in the Union.ai dashboard. The examples below use the `Agent` harness, but the pattern is identical for any agent: just call your agent's entry point inside the task. ## As a task The simplest deployment: put the agent loop in an `@env.task` and invoke it on demand. This works for any agent. ```python import flyte from flyte.ai.agents import Agent env = flyte.TaskEnvironment( name="concierge-agent", image=flyte.Image.from_debian_base().with_pip_packages("litellm"), secrets=[flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY")], ) agent = Agent( name="customer-concierge", instructions="You are a customer-service concierge.", tools=[...], ) @env.task(report=True) async def concierge(request: str) -> str: """Run the agent for a single request.""" result = await agent.run.aio(request) return result.summary or result.error ``` Run it on demand: ```bash flyte run agent.py concierge --request "Refund order #12345 to the customer." ``` Or from Python with `flyte.run(concierge, request="...")`. To register a stable, deployed version of the task, use `flyte deploy agent.py env`. ## As a scheduled task (via `Trigger`) To run an agent autonomously on a schedule, attach a `flyte.Trigger` to the task. The "wakeup" is a regular Flyte task: the agent loop runs inside it, so every tool call is durable, observable, and retryable. Pair this with **Agents > Build an agent > Agent memory** so the agent resumes prior context on each wakeup. ``` agent = Agent( name="github-triage", instructions=( "You are a GitHub issue triager. For each wakeup: list open issues for " "the configured repo, classify each one, group them by severity, and " "post a concise digest to the team channel. Always end by calling post_digest." ), model="claude-haiku-4-5", tools=[list_open_issues, classify_issue, post_digest], max_turns=20, ) @env.task( triggers=flyte.Trigger( "daily-triage", flyte.Cron("0 9 * * *"), # every day at 09:00 inputs={"trigger_time": flyte.TriggerTime, "repo": "flyteorg/flyte", "channel": "#flyte-triage"}, ), report=True, ) async def triage_repo(trigger_time: datetime, repo: str, channel: str) -> str: """Scheduled wakeup that runs the triage agent end-to-end.""" message = f"It is {trigger_time.isoformat()}. Triage the open issues in {repo} and post a digest to {channel}." with flyte.group("triage-loop"): result = await agent.run.aio(message) return result.summary or f"[triage failed] {result.error}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-agent/deploy/scheduled_triage_agent.py* The agent's tools (`list_open_issues`, `classify_issue`, `post_digest`) are durable `@env.task`s; see the [full example](https://github.com/unionai/unionai-examples/tree/main/v2/user-guide/build-agent/deploy/scheduled_triage_agent.py) for their definitions. Deploying the task registers the trigger; from then on Union.ai wakes the agent on schedule. Use `flyte.Cron(...)` for calendar schedules or `flyte.FixedRate(...)` for fixed intervals. The `flyte.TriggerTime` input is filled with the scheduled fire time. See [Triggers](../../triggers/_index) for the full schedule reference. ## Behind a webhook (`AppEnvironment`) To kick off an agent run in response to an external event, deploy a small FastAPI app via an `AppEnvironment` that exposes an HTTP endpoint. The endpoint launches the agent task with `flyte.run.aio(...)`, so the long-running agent loop executes durably in the background while the webhook returns immediately with a run URL. ``` @tool_env.task(report=True) async def review_pr(repo: str, pr_number: int, event: str) -> str: """Durable task that runs the agent for a single webhook event.""" message = f"GitHub webhook fired for {repo}#{pr_number} (event={event}). Review the PR." result = await agent.run.aio(message) return result.summary or result.error def _build_app(): from fastapi import FastAPI api = FastAPI(title="flyte-agent-webhook") @api.post("/trigger") async def trigger(payload: dict) -> dict[str, str]: repo = payload.get("repository") pr_number = int(payload.get("pull_request", {}).get("number", 0)) event = payload.get("action") run = await flyte.run.aio(review_pr, repo=repo, pr_number=pr_number, event=event) return {"run_url": run.url, "name": run.name} return api webhook_env = flyte.app.AppEnvironment( name="flyte-agent-webhook", image=flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn", "litellm"), resources=flyte.Resources(cpu=1, memory="512Mi"), requires_auth=True, depends_on=[tool_env], ) @webhook_env.server async def serve(): import uvicorn config = uvicorn.Config(_build_app(), host="0.0.0.0", port=webhook_env.get_port().port) await uvicorn.Server(config).serve() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-agent/deploy/webhook_agent.py* The agent and its tools (`fetch_pr`, `post_comment`) are defined in the [full example](https://github.com/unionai/unionai-examples/tree/main/v2/user-guide/build-agent/deploy/webhook_agent.py). Once deployed, point your external system at the `/trigger` URL: ```bash curl -X POST -H "Content-Type: application/json" \ -d '{"repository": "flyteorg/flyte", "pull_request": {"number": 123}, "action": "opened"}' \ https://.apps./trigger ``` > [!NOTE] > When the webhook app submits runs on behalf of incoming requests, it needs valid Union.ai credentials. Use passthrough auth (a `FastAPIPassthroughAuthMiddleware` and `flyte.init_passthrough`) so the run is submitted with the caller's identity. See **Apps > Native app integrations > FastAPI app**. ## Chat and other app patterns - **Chat UI:** To let users converse with the agent in a browser, serve it behind a chat interface. See **Agents > Build an agent > Agent chat UI**. - **FastAPI endpoint:** For API-first agents, expose your agent behind a REST endpoint with `FastAPIAppEnvironment` so other services or agents can call it programmatically. - **Model serving:** **Inference > Self-hosted endpoints > vLLM** on GPUs behind an OpenAI-compatible API with `VLLMAppEnvironment` or `SGLangAppEnvironment`. > [!TIP] > See [Build Apps](../../apps/build-apps/_index) and [Configure Apps](../../apps/configure-apps/_index) for more details on hosting services on Union.ai. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-mcp === Serve Model Context Protocol servers for AI assistants to interact with, hosted on Union.ai. # Build an MCP Union.ai supports serving [Model Context Protocol (MCP)](https://modelcontextprotocol.io) servers over HTTP. There are two main MCP environment types: | Environment | Purpose | |-------------|---------| | **`MCPAppEnvironment`** | Serve any FastMCP instance with custom tools | | **`FlyteMCPAppEnvironment`** | Flyte-specific server that exposes Flyte operations as tools | See the sub-pages for detailed guides: - **Agents > Build an MCP > User-defined MCP server**: Build and deploy your own FastMCP instances - **Agents > Build an MCP > Flyte MCP server**: Use Flyte-specific tools to interact with your cluster ## HTTP layout All MCP app environments expose the same HTTP endpoints: - `GET /health`: Liveness/readiness check (`{"status": "healthy"}`) - `POST {mcp_mount_path}/mcp` or `{mcp_mount_path}/sse`: MCP protocol endpoint (default: `/mcp` for generic, `/flyte-mcp` for Flyte) ## Quickstart The fastest way to try Flyte MCP is locally (no deployment needed): ```bash uvx --from "flyte[mcp]>=2.5.18" flyte-mcp --transport stdio ``` `--transport stdio` is required when a client launches the server as a subprocess. The CLI defaults to `streamable-http`, which starts an HTTP listener instead. For client setup, tool selection, allowlists, and remote deployment, see **Agents > Build an MCP > Flyte MCP server**. {{< subpage-cards >}} ## Subpages - **Agents > Build an MCP > User-defined MCP server** - Deploy any FastMCP instance as a long-running app serving its tools over HTTP. - **Agents > Build an MCP > Flyte MCP server** - Expose Flyte operations as MCP tools so an AI assistant can drive your workloads. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-mcp/mcp_server === Deploy any FastMCP instance as a long-running app serving its tools over HTTP. # User-defined MCP server `MCPAppEnvironment` deploys any [FastMCP](https://modelcontextprotocol.io) instance as a long-running Union.ai app, serving its tools over HTTP. Use it when you want to expose your *own* custom tools to AI assistants and LLM clients, rather than the built-in Flyte operations covered in **Agents > Build an MCP > Flyte MCP server**. ## When to use it Reach for `MCPAppEnvironment` when: - You have domain-specific logic (database lookups, internal APIs, business rules, retrieval over your own corpus) that you want to package as MCP tools. - You want an LLM client like Claude Code, Claude Desktop, or OpenCode to call those tools over a stable, authenticated HTTP endpoint. - You want the tool server to run on Union.ai infrastructure, with the same image, secrets, resources, and autoscaling story as any other app. If instead you want assistants to *operate your Union.ai cluster* (run tasks, inspect runs, build images, search docs), use **Agents > Build an MCP > Flyte MCP server**. It ships those tools for you. The two can also run side by side as separate apps. ## How it works You build a `FastMCP` instance and register tools on it with the `@mcp.tool()` decorator. `MCPAppEnvironment` wraps that instance in a Starlette + Uvicorn server and deploys it as an app. Every tool you defined on the instance is exposed automatically; there is no extra registration step. ## Basic example ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "mcp", # "starlette", # "uvicorn", # ] # /// """A basic MCP server app that serves a custom FastMCP instance. This example shows how to deploy any FastMCP server as a Flyte app using ``MCPAppEnvironment``. The server exposes tools via the Model Context Protocol (MCP) over HTTP. """ import flyte from flyte.ai.mcp import MCPAppEnvironment from mcp.server.fastmcp import FastMCP # {{docs-fragment basic-mcp}} mcp = FastMCP(name="demo-generic-mcp") @mcp.tool() def ping() -> str: """Health-style echo for demos.""" return "pong" @mcp.tool() def add(a: int, b: int) -> int: """Add two numbers together.""" return a + b env = MCPAppEnvironment( name="generic-mcp-demo", mcp=mcp, transport="streamable-http", mcp_mount_path="/mcp", resources=flyte.Resources(cpu=1, memory="512Mi"), ) if __name__ == "__main__": flyte.init_from_config() handle = flyte.serve(env) handle.activate(wait=True) print(f"App is ready at {handle.endpoint}") # {{/docs-fragment basic-mcp}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-mcp/basic_mcp_app.py* Deploying with `flyte.serve(env)` activates the app and prints its public endpoint. See [Serve and deploy apps](../../apps/serve-and-deploy-apps/_index) for how deployment, activation, and scaling work in general. ## HTTP layout The MCP ASGI app is mounted at `mcp_mount_path` (default `/mcp`). The resulting endpoints are: CODE0 The session path is `{mcp_mount_path}/mcp` for `streamable-http` and `{mcp_mount_path}/sse` for `sse`. To get a cleaner URL such as `/mcp`, set `mcp_mount_path="/"`. ## Choosing a transport | Transport | Session endpoint | When to use | |-----------|------------------|-------------| | `streamable-http` (default) | `{mcp_mount_path}/mcp` | The right choice for almost all remote deployments. Works with Claude Code, Claude Desktop, and OpenCode. | | `sse` | `{mcp_mount_path}/sse` | Only when a client specifically requires a Server-Sent Events stream. Being phased out across the MCP ecosystem. | CODE1 ## Connecting a client User-defined MCP servers are always deployed as remote HTTP apps; there is no local CLI equivalent. Once `flyte.serve(env)` prints your endpoint, register it with your client. The session URL depends on your `mcp_mount_path` (default `/mcp`) and transport (default `streamable-http`), so the full endpoint is `https:///mcp/mcp`. ### Claude Code CODE2 ### OpenCode CODE3 Replace `` with the hostname from `handle.endpoint`. If you deployed with a custom `mcp_mount_path`, adjust the path accordingly. ## Configuration tips - **Resources**: Tool servers are typically I/O-bound and lightweight. `flyte.Resources(cpu=1, memory="512Mi")` is a good starting point; raise it only if a tool does heavy in-process work. - **Secrets**: If your tools call external APIs, pass credentials with `secrets=...` rather than baking them into the image. See [secret-based authentication](../../apps/build-apps/secret-based-authentication.md). - **Custom dependencies**: Add the libraries your tools need to the app `image`. Remember to include `mcp`, `starlette`, and `uvicorn` (these come from `pip install 'flyte[mcp]'`). - **Extra files**: If your tools import local helper modules, use the `include` parameter so they ship with the app. See [including additional files](../../apps/configure-apps/including-additional-files.md). ## Best practices 1. **Write clear docstrings**: The docstring on each `@mcp.tool()` function is what the LLM sees when deciding whether and how to call it. Treat it as the tool's API contract: describe the purpose, arguments, and return value. 2. **Use precise type hints**: FastMCP derives the tool's input schema from your function signature, so accurate types lead to better-formed tool calls. 3. **Keep tools focused**: Prefer several small, single-purpose tools over one tool with many modes. LLMs select narrowly-scoped tools more reliably. 4. **Require auth in production**: Keep `requires_auth=True` (the default) so only authenticated clients can reach your tools. 5. **Right-size resources**: Start small (1 CPU, 512Mi) and scale up only if profiling shows you need to. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/build-mcp/flyte_mcp_server === Expose Flyte operations as MCP tools so an AI assistant can drive your workloads. # Flyte MCP server `FlyteMCPAppEnvironment` exposes Union.ai operations as standardized [MCP](https://modelcontextprotocol.io) tools, so AI assistants and LLM clients can drive your cluster programmatically: running tasks, monitoring runs, reading logs, inspecting actions, managing apps and triggers, and searching the SDK and docs. Unlike **Agents > Build an MCP > User-defined MCP server**, where you supply your own tools, this environment ships a curated set of Flyte tools out of the box. You decide which of them to expose and what they're allowed to touch. > [!TIP] There is a prebuilt plugin > [`flyte-agent-plugins`](https://github.com/flyteorg/flyte-agent-plugins) ships these same > control-plane tools as a `flyte-cluster` MCP server, plus a hosted `flyte-docs` search > server. See **Flyte agent plugins** for > harness-specific installation and configuration. > > Build your own `FlyteMCPAppEnvironment` below when you need to scope the tools, > allowlist resources, or deploy a shared server. ## When to use it Use a Flyte MCP server when you want an assistant to *act on your cluster on your behalf*. Common scenarios: - **Agentic development loops**: Let Claude Code or OpenCode run a task, wait for it, read its outputs, and iterate, without you copy-pasting commands. - **Conversational operations**: Ask an assistant to list recent runs, check a run's status, or abort a stuck run. - **Docs- and example-aware coding**: Enable the `search` tools so an assistant can ground its answers in the Flyte SDK examples and Union documentation. - **Self-service automation**: Give a trusted internal agent a tightly-scoped server (a few allowlisted tasks, no destructive tools) to perform a narrow job. If you only need to expose custom, non-Flyte tools, use **Agents > Build an MCP > User-defined MCP server** instead. ## How to run it There are two ways to run a Flyte MCP server, suited to different stages: | Mode | When to use | |------|-------------| | **Local (stdio)** | One user on one machine. The client launches the server as a subprocess, using your local Flyte config and your existing login. Nothing is deployed, and no data leaves your machine. | | **Remote (HTTP)** | A whole team, or a client that cannot launch a subprocess (a browser-based assistant, for example). The server runs as a deployed app with a stable, authenticated URL. | Prefer stdio unless you need one of the two things only HTTP gives you: a single shared server that nobody has to install, or a URL for a client that has no local process. ### Running locally with `uvx` The `flyte[mcp]` extra ships a `flyte-mcp` CLI entrypoint. Run it with [`uvx`](https://docs.astral.sh/uv/guides/tools/) (no global install required): ```bash uvx --from "flyte[mcp]>=2.5.18" flyte-mcp --transport stdio ``` `uvx` downloads `flyte[mcp]` into an isolated environment, runs `flyte-mcp`, and exits cleanly when you're done. The server finds its Flyte config with the same search order as the `flyte` CLI, so whichever project and cluster that config points at is what the tools operate on. Two parts of that command matter: - **`--transport stdio` is required.** The CLI defaults to `streamable-http`, which starts an HTTP listener instead of speaking JSON-RPC on stdin and stdout. A client that launches the process expecting stdio will not connect without this flag. - **`>=2.5.18` is the minimum version.** It is the first release that constrains its `mcp` dependency below 2.0. Earlier versions resolve `mcp` 2.0.0, which removed the module the server imports, and the server exits at startup reporting `mcp is not installed`. > [!TIP] > Pin to an exact version instead of a floor: `uvx --from "flyte[mcp]==2.5.18" flyte-mcp --transport stdio` The server starts even when the search order finds no Flyte config. In that case the tools fail when the assistant calls them, rather than the server failing to start. From `flyte` 2.12.2, a `--config` or `FLYTE_MCP_CONFIG` path that doesn't exist does stop the server at startup. #### Pin the server to a tenant Requires `flyte` 2.12.2 or later. The config search prefers `./config.yaml`, `./.flyte/config.yaml`, and the git root's `.flyte/config.yaml` over `FLYTECTL_CONFIG`. An MCP client often launches the server from your project directory, so a config checked into that repo wins, and the tools act on that repo's tenant. To choose the tenant explicitly, pass `--config`, and optionally `--endpoint` to override the config file's endpoint: ```bash uvx --from "flyte[mcp]>=2.12.2" flyte-mcp --transport stdio --config ~/.flyte/config.yaml ``` | Option | Environment variable | Effect | |--------|----------------------|--------| | `--config` | `FLYTE_MCP_CONFIG` | Flyte config file to initialize from, instead of the search order. | | `--endpoint` | `FLYTE_MCP_ENDPOINT` | Endpoint to connect to. Overrides the endpoint in the config file. | Combining either option with `--no-init-from-config` is a usage error. At startup the server prints the config file and endpoint it resolved, and where each came from, to stderr: ```text flyte-mcp: config /home/me/.flyte/config.yaml (from --config), endpoint dns:///my-tenant.example.com (from config file) ``` If the search order found the config in the working directory or its git repo, the server also prints a warning naming that file. The `whoami` tool reports the config file as `config_file`, so the assistant can check which tenant it is acting on. > [!NOTE] Skip the search corpus > The three `search_*` tools grep a local copy of the Flyte SDK examples, the docs examples, and `llms.txt`. Enabling them makes the CLI clone roughly 120 MB into `~/.flyte/mcp` on first launch. Pass `--tool-groups` without `search` to skip it: > ```bash > uvx --from "flyte[mcp]>=2.5.18" flyte-mcp --transport stdio \ > --tool-groups task,run,action,logs,app,trigger,project,secret,condition,identity > ``` Once running, register it with your client as a **stdio** transport: the client manages the process lifetime. See the **Agents > Build an MCP > Flyte MCP server > Connecting a client** section below. ### Deploying remotely Deploy a `FlyteMCPAppEnvironment` as a long-running app to get a stable, shared HTTP endpoint: ```python flyte.init_from_config() handle = flyte.serve(mcp_env) handle.activate(wait=True) print(f"MCP endpoint: {handle.endpoint}/flyte-mcp/mcp") ``` The app is deployed into **your own tenant**, so the server sits in the same trust domain as the data it reads: run metadata, logs, and task inputs and outputs stay inside your account. Set `requires_auth=True` and the endpoint sits behind your organization's SSO, so each call runs as the person driving the agent, with their own permissions. See [Serve and deploy apps](../../apps/serve-and-deploy-apps/_index) for how deployment, activation, and scaling work in general. ## Basic example A server with **all** tools enabled. The environment definition is the same for both modes โ€” only the last step differs, since `flyte.serve` deploys it as an app: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "mcp", # "starlette", # "uvicorn", # ] # /// """A Flyte MCP server app that exposes Flyte operations as MCP tools. This example deploys an MCP (Model Context Protocol) server that allows AI assistants and LLM-based clients to interact with the Flyte control plane using the standardized MCP protocol. The server exposes tools for running tasks, monitoring runs, managing apps and triggers, and searching Flyte SDK/docs examples. Requirements: pip install 'flyte[mcp]' Usage: Deploy all tools $ python v2/user-guide/build-mcp/flyte_mcp_app.py Or serve locally for development (recommended: `uvx`) $ uvx --from "flyte[mcp]" flyte-mcp """ import flyte from flyte.ai.mcp import FlyteMCPAppEnvironment # {{docs-fragment flyte-mcp-all-tools}} # Deploy an MCP server with all tools enabled mcp_env = FlyteMCPAppEnvironment( name="flyte-mcp-server", resources=flyte.Resources(cpu=1, memory="512Mi"), transport="streamable-http", instructions=( "This MCP server provides tools to interact with the Flyte control plane. " "Use the available tools to run tasks, monitor runs, manage apps and triggers, " "and search SDK/docs examples." ), ) if __name__ == "__main__": flyte.init_from_config() app_handle = flyte.serve(mcp_env) app_handle.activate(wait=True) print(f"App is ready at {app_handle.endpoint}") # {{/docs-fragment flyte-mcp-all-tools}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-mcp/flyte_mcp_app.py* The default mount path is `/flyte-mcp`, so with the default `streamable-http` transport the MCP endpoint is `/flyte-mcp/mcp`. > [!TIP] Set `instructions` > The `instructions` string is sent to the LLM as guidance on what the server is for and how to use its tools. A clear, specific instruction string measurably improves how reliably the assistant picks the right tool. ## Scoping the server A server with every tool enabled and no restrictions is convenient for trusted local use, but for anything shared you should narrow it down. There are three layers of control, from coarse to fine. ### 1. Tool groups Tools are organized into groups. Pass `tool_groups` to enable only the groups you need: CODE5 | Group | Tools | Typical use | |-------|-------|-------------| | `all` | All tools (default when both `tool_groups` and `tools` are omitted) | Trusted local development | | `core` | No tools (only HTTP routes) | Health-check-only / building up explicitly | | `task` | `run_task`, `get_task`, `list_tasks` | Launching and inspecting tasks | | `run` | `get_run`, `get_run_io`, `abort_run`, `list_runs`, `wait_for_run`, `rerun_run` | Monitoring and controlling runs | | `action` | `list_actions`, `get_action`, `abort_action` | Debugging a run step by step: phases, attempts, failure details, timing | | `logs` | `get_logs` | Reading task logs | | `app` | `get_app`, `list_apps`, `activate_app`, `deactivate_app` | Managing deployed apps | | `trigger` | `list_triggers`, `get_trigger`, `activate_trigger`, `deactivate_trigger` | Managing triggers | | `project` | `list_projects`, `get_project` | Discovering projects and domains | | `secret` | `list_secrets`, `create_secret`, `delete_secret` | Managing secrets (names only โ€” values are never returned) | | `condition` | `list_conditions`, `signal_condition` | Answering human-in-the-loop gates | | `identity` | `whoami` | Confirming which identity and org the server is acting as, and (for a server started with `flyte-mcp` 2.12.2 or later) which config file it was started from | | `search` | `search_flyte_sdk_examples`, `search_flyte_docs_examples`, `search_full_docs` | Grounding answers in SDK/docs | ### 2. Individual tools For the tightest control, pass `tools` with an explicit list of tool names instead of `tool_groups` (pass one or the other, not both): CODE6 This is the way to build, for example, a strictly read-only server. ### 3. Allowlists Even with a tool enabled, you can restrict *which resources* it may target. Allowlists are the safest way to expose `run_task` or app/trigger management to an agent: CODE7 When an allowlist is set, calls targeting anything outside it are rejected. Omitting an allowlist leaves that resource type unrestricted. ## Enabling the search tools The `search` tools need a corpus to scan, so you must point them at filesystem paths that exist *inside the app image*: - `sdk_examples_path`: Flyte SDK examples (powers `search_flyte_sdk_examples`) - `docs_examples_path`: Union examples (powers `search_flyte_docs_examples`) - `full_docs_path`: the docs `llms.txt` index (powers `search_full_docs`) The default image already clones the flyte-sdk and unionai-examples repos and downloads `llms.txt` into `/root` for you. If you supply a custom `image`, bake the corpora in yourself and pass matching paths: CODE8 ## Putting it together: a filtered server This example combines an explicit tool list, an allowlist, search paths, and instructions to build a scoped server. It lists its tools instead of using `tool_groups=["task", "run", "search"]` so that it can leave out `abort_run`: the `run` group includes it, and no allowlist covers it, so it would let an agent abort any run its identity has access to, in any project and domain it names. The `task_allowlist` then restricts every task tool and `rerun_run`: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.0.0", # "mcp", # "starlette", # "uvicorn", # ] # /// """A Flyte MCP server with filtered tools and search. This example shows how to deploy a more restricted MCP server that exposes an explicit list of task, run, and search tools, with a task allowlist to restrict which tasks can be accessed and configurable search paths for documentation. It lists its tools instead of using tool groups so that it can leave out `abort_run`, which the `run` group includes and no allowlist covers. """ import flyte from flyte.ai.mcp import FlyteMCPAppEnvironment # Create an image with the required dependencies and search corpora baked in image = ( flyte.Image.from_debian_base() .with_apt_packages("ca-certificates", "git", "curl") .with_pip_packages("mcp", "starlette", "uvicorn") ) # {{docs-fragment flyte-mcp-filtered}} mcp_env = FlyteMCPAppEnvironment( name="restricted-mcp", image=image, resources=flyte.Resources(cpu=1, memory="512Mi"), transport="streamable-http", # An explicit list instead of tool_groups=["task", "run", "search"], so that # abort_run (in the "run" group, not covered by any allowlist) is left out. tools=[ "run_task", "get_task", "list_tasks", "get_run", "get_run_io", "list_runs", "wait_for_run", "rerun_run", "search_flyte_sdk_examples", "search_flyte_docs_examples", "search_full_docs", ], task_allowlist=["my-project/my-task", "another-task"], # Search paths (see docstring): you need to clone/fetch these during image build. sdk_examples_path="/root/flyte-sdk/examples", docs_examples_path="/root/unionai-examples/v2", full_docs_path="/root/llms.txt", instructions=( "This MCP server provides tools to run and monitor specific Flyte tasks, " "and search Flyte SDK/docs examples. " "Only allowlisted tasks can be accessed." ), ) if __name__ == "__main__": flyte.init_from_config() app_handle = flyte.serve(mcp_env) app_handle.activate(wait=True) print(f"App is ready at {app_handle.endpoint}") # {{/docs-fragment flyte-mcp-filtered}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-mcp/flyte_mcp_app_filtered.py* ## Connecting a client ### Claude Code: local (stdio) Registers the `flyte-mcp` process as a locally managed stdio server. Claude Code starts and stops the `uvx` process automatically: CODE9 `--transport stdio` appears twice on purpose. The first tells Claude Code how to talk to the server; the second tells the server which transport to serve. Without the second, the server starts an HTTP listener and the connection fails. ### Claude Code: remote (HTTP) For a deployed server with a public URL: CODE10 ### OpenCode: local OpenCode spawns the `uvx` command for you: CODE11 ### OpenCode: remote CODE12 ## Best practices 1. **Start broad locally, scope down for sharing**: Run with `all` tools via `uvx` while exploring, then enable only the groups or tools you need before deploying a shared server. 2. **Always allowlist mutating tools**: If `run_task` or app/trigger management is enabled on a shared server, set the corresponding allowlist so an agent can't touch arbitrary resources. No allowlist applies to `abort_run`, `abort_action`, `create_secret`, `delete_secret`, or `signal_condition`, and each belongs to a group (`run`, `action`, `secret`, `condition`). To keep one from the server's agent, pass an explicit `tools=[...]` list that leaves it out, instead of `tool_groups`. 3. **Prefer `tools` over `tool_groups` for read-only servers**: An explicit allowlist of read tools is the clearest way to guarantee an agent can't change anything. 4. **Write specific `instructions`**: Describe what the server does and any constraints (e.g. "only allowlisted tasks can be run"). This guides tool selection and reduces wasted calls. 5. **Keep auth on**: Leave `requires_auth=True` so only authenticated clients can reach a deployed server. ## MCP tools reference | Tool | Group | Description | |------|-------|-------------| | `run_task` | `task` | Run a task | | `get_task` | `task` | Get task details | | `list_tasks` | `task` | List tasks | | `get_run` | `run` | Get a run | | `get_run_io` | `run` | Get run inputs and outputs | | `abort_run` | `run` | Abort a run | | `list_runs` | `run` | List runs | | `wait_for_run` | `run` | Wait for a run to finish | | `rerun_run` | `run` | Re-run a prior run | | `list_actions` | `action` | List the actions of a run | | `get_action` | `action` | Get action details and timing | | `abort_action` | `action` | Abort a single action | | `get_logs` | `logs` | Read action logs | | `get_app` | `app` | Get an app | | `list_apps` | `app` | List apps | | `activate_app` | `app` | Activate an app | | `deactivate_app` | `app` | Deactivate an app | | `list_triggers` | `trigger` | List triggers | | `get_trigger` | `trigger` | Get a trigger | | `activate_trigger` | `trigger` | Activate a trigger | | `deactivate_trigger` | `trigger` | Deactivate a trigger | | `list_projects` | `project` | List projects | | `get_project` | `project` | Get a project | | `list_secrets` | `secret` | List secret names | | `create_secret` | `secret` | Create a secret | | `delete_secret` | `secret` | Delete a secret | | `list_conditions` | `condition` | List the conditions of a run | | `signal_condition` | `condition` | Signal a waiting condition | | `whoami` | `identity` | Show the caller's identity | | `search_flyte_sdk_examples` | `search` | Search Flyte SDK examples | | `search_flyte_docs_examples` | `search` | Search Flyte docs examples | | `search_full_docs` | `search` | Search the full Flyte docs | === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/sandboxing === Safely execute LLM-generated code with workflow sandboxes or ephemeral containers. # Sandboxing A **sandbox** is an isolated, secure environment where code can run without affecting the host system. Sandboxes restrict what the executing code can do (limiting filesystem access, blocking network calls, and preventing arbitrary system operations) so that even malicious or buggy code cannot cause harm. The exact restrictions depend on the sandboxing approach: some sandboxes eliminate dangerous operations entirely, while others provide full capabilities within an isolated, disposable container. ## Why sandboxing matters for AI LLM-generated code is inherently untrusted. The model may produce code that is correct and useful, but it can also produce code that is dangerous, and it does so without intent or awareness. | Risk | Example | |------|---------| | Data destruction | `DELETE FROM orders WHERE 1=1`: wipes an entire table | | Credential exfiltration | Reads environment variables and sends API keys to an external endpoint | | Infinite loops | `while True: pass` consumes CPU indefinitely | | Resource abuse | Spawns thousands of threads or allocates unbounded memory | | Filesystem damage | `rm -rf /` or overwrites critical configuration files | | Network abuse | Makes unauthorized API calls, sends spam, or joins a botnet | Running LLM-generated code without a sandbox means trusting the model to never make these mistakes. Sandboxing eliminates this trust requirement by making dangerous operations structurally impossible. ## Types of sandboxes There are three broad approaches to sandboxing LLM-generated code, each with different tradeoffs: | Type | How it works | Tradeoffs | Examples | |------|-------------|-----------|----------| | **One-shot execution** | Code runs to completion in a disposable container, then the container is discarded. Stdout, stderr, and outputs are captured. | Simple, no state reuse. Good for single-turn tasks. | Container tasks, serverless functions | | **Interactive sessions** | A persistent VM or container where you send commands incrementally and observe results between steps. Sessions last for the lifetime of the VM. | Flexible and multi-turn, but heavier to provision and manage. | E2B, Daytona, fly.io | | **Programmatic tool calling** | The LLM generates orchestration code that calls a predefined set of tools. The orchestration code runs in a sandbox while the tools run in full containers. | Durable, observable, and secure. Tools are known ahead of time. | Flyte workflow sandboxing | ## What Flyte offers Flyte provides two complementary sandboxing approaches: ### Workflow sandbox (Monty) A **sandboxed orchestrator** built on [Monty](https://github.com/pydantic/monty), a Rust-based sandboxed Python interpreter. The sandbox starts in microseconds, runs pure Python control flow, and dispatches heavy work to full container tasks through the Flyte controller. This enables the **programmatic tool calling** pattern (also known as code mode): LLMs generate Python orchestration code that invokes registered tools, and Flyte executes it safely with full durability, observability, and type checking. ### Code sandbox (container) A **stateless code sandbox** that runs arbitrary Python scripts or shell commands inside an ephemeral Docker container. The container is built on demand from declared dependencies, executed once, and discarded. This is the right choice when you need full Python capabilities: third-party packages, file I/O, shell commands, or any computation that goes beyond pure control flow. ### When to use which | | Workflow sandbox | Code sandbox | |---|---|---| | **Runtime** | Monty (Rust-based Python interpreter) | Ephemeral Docker container | | **Startup** | Microseconds | Seconds (image build + container spin-up) | | **Capabilities** | Pure Python control flow and a subset of the standard library: no third-party packages, no I/O, no network | Full Python environment: any package, any library, full I/O | | **Use case** | LLM-generated orchestration logic that calls registered tools | Arbitrary computation: data processing, test execution, ETL, shell pipelines | | **State** | Runs within a worker container process | Stateless: fresh container per invocation | | **Security model** | Dangerous operations are structurally impossible | Isolated container | - Use the **workflow sandbox** when you need to run untrusted control flow (loops, conditionals, routing) that dispatches work to known tasks. It starts in microseconds and provides the strongest isolation guarantees. - Use the **code sandbox** when you need full Python capabilities: third-party packages, file I/O, shell commands, or any computation that goes beyond pure control flow. ### Learn more - **Agents > Sandboxing > Workflow sandboxing in Flyte**: How the Monty-based sandboxed orchestrator works, with examples - **Agents > Sandboxing > Programmatic tool calling for agents**: The concept behind programmatic tool calling and how to build agents that use it - **Agents > Sandboxing > Code sandboxing**: Running arbitrary code and commands in ephemeral containers with `flyte.sandbox.create()` {{< subpage-cards >}} ## Subpages - **Agents > Sandboxing > Workflow sandboxing in Flyte** - Run pure Python control flow in a sandboxed orchestrator while heavy work goes to container tasks. - **Agents > Sandboxing > Programmatic tool calling for agents** - Let the model emit one block of code that calls your tools, rather than a sequence of JSON tool calls. - **Agents > Sandboxing > Code sandboxing** - Run arbitrary Python or shell inside an ephemeral, stateless container with flyte.sandbox.create. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/sandboxing/workflow-sandboxing-flyte === Run pure Python control flow in a sandboxed orchestrator while heavy work goes to container tasks. # Workflow sandboxing in Flyte Flyte provides a sandboxed orchestrator that lets you run pure Python control flow in a secure sandbox while dispatching heavy work to full container tasks. This enables patterns where LLMs generate orchestration code dynamically, and Flyte executes it safely with full durability and observability. ## Why workflow sandboxing? Three properties of Flyte make it a natural fit for sandboxed code execution: 1. **Infrastructure on demand**: Flyte spins up containers with specific permissions, secrets, and resources for each task. 2. **LLMs are great at Python**: Models trained on billions of lines of code can reliably generate Python orchestration logic. 3. **Microsecond startup**: The sandbox is powered by [Monty](https://github.com/pydantic/monty) (Pydantic's Rust-based Python interpreter), which starts in microseconds without the overhead of VMs or containers. The result: LLMs generate the orchestration code (control flow, conditionals, loops), and Flyte tasks handle the heavy lifting (data access, computation, external APIs) in full containers. > [!NOTE] Orchestrators without a container > The orchestrators on this page run inside a worker container. In Union.ai, an > **Tasks > Build tasks > Orchestrator tasks** runs the same kind of > sandboxed code with no container of its own, for drivers that only call tasks. ## How it works Your generated code runs inside one or more **Monty sandboxes**: lightweight Python interpreters embedded within a **worker container**. Each sandbox can execute pure Python (variables, loops, conditionals, function calls) but has no access to the filesystem, network, or OS, and can import only a subset of the standard library. A **bridge layer** acts as a hypervisor between the worker container and the sandboxes, handling opaque IO and routing callable tasks. When your code calls an external task, the bridge dispatches it, either as a method in the outer Python process or as a durable remote call through the Flyte controller (via the Queue Service): ```mermaid flowchart TB subgraph worker["Worker Container"] subgraph bridge["Bridge / Hypervisor"] IO["Opaque IO: File, Dir, DataFrame"] subgraph sandbox1["Monty Sandbox 1"] A1["Your code: loops, variables, conditionals"] B1["result = add(x, y)"] end subgraph sandbox2["Monty Sandbox 2"] A2["More sandboxed code"] end end end A1 --> B1 B1 -- "callable task" --> bridge bridge -- "result" --> B1 IO -. "routed to tasks" .-> bridge bridge -- "external call" --> QS["Queue Service"] QS -- "completion" --> bridge ``` Each sandbox sees external tasks as opaque function calls. When your code hits one, Monty **pauses**, and the bridge layer dispatches the task, either directly in the outer Python process or as a remote durable call through the Flyte controller system (Queue Service). Once the call completes, Monty **resumes** with the result. Your code never knows the difference: it just looks like a regular function call that returns a value. Multiple Monty sandboxes can run within the same worker container, each isolated like a lightweight VM. **Opaque IO types** like `File`, `Dir`, and `DataFrame` are managed by the bridge layer and pass through the sandbox without inspection. Your code can route them between tasks but cannot read or modify their contents. ## Example: sandboxed orchestrator Use `@env.sandbox.orchestrator` to define a sandboxed task that calls regular worker tasks. The orchestrator contains only pure Python control flow; all heavy computation runs in worker containers. ```python import flyte env = flyte.TaskEnvironment(name="sandboxed-demo") # Worker tasks โ€” run in their own containers @env.task def add(x: int, y: int) -> int: return x + y @env.task def multiply(x: int, y: int) -> int: return x * y @env.task def fib(n: int) -> int: """Compute the nth Fibonacci number iteratively.""" a, b = 0, 1 for _ in range(n): a, b = b, a + b return a # Sandboxed orchestrator โ€” pure Python control flow @env.sandbox.orchestrator def pipeline(n: int) -> dict[str, int]: fib_result = fib(n) linear_result = add(multiply(n, 2), 5) total = add(fib_result, linear_result) return { "fib": fib_result, "linear": linear_result, "total": total, } ``` When `pipeline` runs, Monty executes the control flow in the sandbox. Each call to `fib`, `multiply`, and `add` pauses the sandbox, runs the worker task in a container, and resumes with the result. Both `def` and `async def` orchestrators are supported. In an `@env.sandbox.orchestrator`, call tasks without `await`: a task call returns its result directly, and awaiting it raises `TypeError`. ## Example: dynamic code execution For cases where the code itself is generated at runtime (from templates, user input, or LLM output), use `orchestrator_from_str()` and `orchestrate_local()`. ### Reusable task from a code string `orchestrator_from_str()` creates a reusable task template from a Python code string. The value of the **last expression** becomes the return value. ```python import flyte import flyte.sandbox env = flyte.TaskEnvironment(name="code-string-demo") @env.task def add(x: int, y: int) -> int: return x + y @env.task def multiply(x: int, y: int) -> int: return x * y # Create a reusable task from a code string compute_pipeline = flyte.sandbox.orchestrator_from_str( """ partial = add(x, y) multiply(partial, scale) """, inputs={"x": int, "y": int, "scale": int}, output=int, tasks=[add, multiply], name="compute-pipeline", ) # flyte.run(compute_pipeline, x=2, y=3, scale=4) โ†’ 20 ``` ### One-shot local execution `orchestrate_local()` executes a code string and returns the result directly: no task template, no controller. Use it for quick one-off computations. ```python result = await flyte.sandbox.orchestrate_local( "add(x, y) * 2", inputs={"x": 1, "y": 2}, tasks=[add], ) # result โ†’ 6 ``` ### Parameterized code generation Because the code is a string, you can generate it programmatically: ```python def make_reducer(operation: str) -> flyte.sandbox.CodeTaskTemplate: """Create a sandboxed task that reduces a list using the given operation.""" if operation == "sum": body = """ acc = 0 for v in values: acc = acc + v acc """ elif operation == "product": body = """ acc = 1 for v in values: acc = acc * v acc """ else: raise ValueError(f"Unknown operation: {operation}") return flyte.sandbox.orchestrator_from_str( body, inputs={"values": list}, output=int, name=f"reduce-{operation}", ) sum_task = make_reducer("sum") product_task = make_reducer("product") ``` ## Building agents with programmatic tool calling The sandboxed orchestrator and `orchestrate_local()` are the foundation for building agents that use **programmatic tool calling**: systems where an LLM generates Python orchestration code, and the sandbox executes it with registered tools. Because `orchestrate_local()` accepts a plain code string and a list of tool functions, you can wire it into an LLM generate-execute-retry loop: the model writes code, the sandbox runs it, and on failure the error feeds back to the model for correction. See **Agents > Sandboxing > Programmatic tool calling for agents** for the full concept, agent implementation patterns, and end-to-end examples. ## Syntax restrictions Monty runs a subset of Python. The tables below apply to `flyte` 2.10.6 or later, which runs the sandbox on Monty 1.0. ### Allowed | Feature | Notes | |---------|-------| | Variables and assignment | `x = 1`, `d["key"] = v`, `l[0] = v` | | Augmented assignment | `x += 1` | | Walrus operator | `(y := 3)` | | Arithmetic and comparisons | `x + y`, `x > y` | | String operations | Concatenation, f-strings, `str.format()` | | `if`/`elif`/`else` | Conditional logic | | `for` loops | Iteration over lists, ranges, dicts | | `while` loops | Condition-based loops | | Function definitions (`def`, `lambda`) | Local helper functions | | `async def` and `await` | Async helper functions; call tasks without `await` | | `class` definitions | Local helper classes | | `with` statements | | | `try`/`except` and `raise` | | | `assert` statements | | | `global`/`nonlocal` | | | List/dict/tuple/set literals | `[1, 2, 3]`, `{"key": "value"}`, `{1, 2}` | | Comprehensions and generator expressions | `[x * 2 for x in items]`, `sum(i for i in range(3))` | | `import` | A subset of the standard library, such as `math`, `json`, `re`, `datetime` and `collections`; no third-party packages | | External task calls | Calling registered `@env.task` workers | ### Not allowed | Feature | Workaround | |---------|------------| | `yield`/`yield from` (generator functions) | Build and return a list | | `del` statements | Not supported | | `match` statements | Use `if`/`elif` | | `await` on a task call | Call the task without `await` | | Reading the clock (`time.time()`, `datetime.now()`) | Pass dates in as inputs; date arithmetic works | | Unseeded randomness (`random.random()`) | Use a seeded `random.Random(seed)` | | Standard-library modules outside the subset, such as `statistics`, `string`, `hashlib`, `enum` and `subprocess` | Not supported | ### Type restrictions - **Primitive types**: `int`, `float`, `str`, `bool`, `bytes`, `None` - **Collection types**: `list`, `dict`, `tuple` (including generic forms like `list[int]`, `dict[str, float]`) - **Opaque IO handles**: `File`, `Dir`, `DataFrame`; pass-through only, cannot be inspected in the sandbox - **Union types**: `Optional[T]` and `Union` of allowed types - **Not allowed as inputs or outputs**: Custom classes, dataclasses, Pydantic models, or any user-defined types. A class defined inside the sandbox can still be used there. ## Security model The sandboxed orchestrator provides security through restriction, not trust: - **No filesystem access**: Cannot read, write, or list files - **No network access**: Cannot make HTTP requests, open sockets, or resolve DNS - **No OS access**: Cannot spawn processes, read environment variables, or access system resources - **Limited imports**: Only a subset of the standard library can be imported; no third-party packages - **Opaque IO**: `File`, `Dir`, and `DataFrame` values pass through the sandbox without inspection; the sandbox can route them between tasks but cannot read their contents - **Type-checked boundaries**: Inputs and outputs are validated against declared types at the sandbox boundary - **Deterministic execution**: The same inputs always produce the same outputs (excluding external task results) The sandbox runs untrusted code safely because dangerous operations are not just discouraged: they are structurally impossible in the Monty runtime. === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/sandboxing/code-mode === Let the model emit one block of code that calls your tools, rather than a sequence of JSON tool calls. # Programmatic tool calling for agents **Programmatic tool calling** (also known as **code mode**) is a pattern where LLMs write executable code instead of making individual tool calls. Rather than the model emitting a sequence of JSON tool-call objects and the system routing each one, the model generates a single block of code that calls multiple tools, transforms data, and applies logic, all executed in a sandbox. The key insight: LLMs are trained on billions of lines of code, but only a small amount of synthetic tool-call data. Code generation is a more natural and reliable output modality for models than structured tool-call schemas. ## Programmatic tool calling vs sequential tool calling In sequential tool calling, every intermediate result passes through the model's context window. The model calls one tool, reads the result, decides what to do next, calls another tool, and so on. Each round-trip costs tokens and latency. With programmatic tool calling, the model generates a complete program upfront. The sandbox executes it, and only the final result returns to the model. | Aspect | Sequential tool calling | Programmatic tool calling | |--------|-------------|-----------| | **Output format** | JSON tool-call objects, one at a time | A single block of executable code | | **Data flow** | Every intermediate result passes through the model | Intermediate results stay in the sandbox | | **Context overhead** | Grows with each tool call (all results in context) | Fixed: only tool signatures in context | | **Multi-step logic** | Model re-invoked at every step | Sandbox executes loops, conditionals, transforms | | **Scaling with tools** | Context grows linearly with number of tool definitions | Tools discovered progressively or loaded on demand | ## Why programmatic tool calling is powerful ### Token efficiency Sequential tool calling loads all tool definitions into the context window upfront and passes every intermediate result through the model. Programmatic tool calling reduces this dramatically: - **98%+ context reduction** reported by Anthropic when using code execution with MCP servers: from 150,000 tokens down to 2,000 tokens for the same task. - **99.9% reduction** reported by Cloudflare for large APIs: approximately 1,000 tokens with programmatic tool calling versus 1.17 million tokens when exposing each API endpoint as a separate tool. ### Performance By eliminating round-trips through the model for intermediate steps, programmatic tool calling achieves significant speed improvements. The sandbox evaluates conditionals, loops, and data transformations locally: no "time to first token" delay for each step. ### Natural programming patterns Code naturally expresses patterns that are awkward or impossible in tool-call sequences: - **Loops**: Process a list of items without the model deciding "call this tool again" for each one - **Conditionals**: Branch on intermediate results without another model invocation - **Data transformation**: Filter, map, and aggregate data before passing it to the next tool - **Variable reuse**: Store intermediate results and reference them later ### Progressive tool discovery Instead of loading hundreds of tool definitions into the context window, programmatic tool calling supports progressive discovery. The model can search for relevant tools, load only what it needs, and compose them in code. ### Data privacy Intermediate results stay in the sandbox execution environment. They never re-enter the model's context window, which means sensitive data (PII, credentials, financial records) can be processed without the model seeing it. ## Example: sequential vs programmatic tool calling Consider a task: "Analyze sales data, filter for Q4, calculate statistics, and create a chart." ### Sequential tool calling approach The model makes serial tool calls, with each result passing through the context window: ``` Step 1: Model โ†’ tool_call: fetch_data("sales_2024") Result: [150KB of sales data] โ†’ back into model context Step 2: Model โ†’ tool_call: filter_data(data, "month", ">=", "Oct") Result: [40KB of filtered data] โ†’ back into model context Step 3: Model โ†’ tool_call: calculate_statistics(filtered, "revenue") Result: {"mean": 112000, ...} โ†’ back into model context Step 4: Model โ†’ tool_call: create_chart("bar", "Q4 Revenue", ...) Result: "..." โ†’ back into model context ``` Four round-trips through the model. The 150KB dataset enters the context window and stays there. ### Programmatic tool calling approach The model generates a single code block: ```python data = fetch_data("sales_2024") q4_months = ["Oct", "Nov", "Dec"] q4_data = [row for row in data if row["month"] in q4_months] stats = calculate_statistics(q4_data, "revenue") months = [] revenues = [] for row in q4_data: if row["month"] not in months: months.append(row["month"]) for month in months: total = 0 for row in q4_data: if row["month"] == month: total = total + row["revenue"] revenues.append(total) chart = create_chart("bar", "Q4 Revenue by Month", months, revenues) {"charts": [chart], "summary": "Q4 stats: " + str(stats)} ``` One model invocation. The data never re-enters the model's context window. The sandbox handles the filtering, aggregation, and chart creation locally. ## Example: defining tools Tools are plain Python functions with type annotations and docstrings. The agent auto-generates its system prompt from these signatures, so adding a tool requires no other changes. ```python async def fetch_data(dataset: str) -> list: """Fetch tabular data by dataset name. Available datasets: - "sales_2024": columns month, region, revenue, units - "employees": columns name, department, salary, years_exp, performance_rating - "website_traffic": columns date, page, visitors, bounce_rate, avg_duration - "inventory": columns product, category, stock, price, supplier """ ... async def create_chart(chart_type: str, title: str, labels: list, values: list) -> str: """Generate a self-contained Chart.js HTML snippet. Args: chart_type: One of "bar", "line", "pie", "doughnut". title: Chart title displayed above the canvas. labels: X-axis labels (or slice labels for pie/doughnut). values: Either a flat list of numbers, or a list of {"label": str, "data": list[number]} dicts for multi-series. """ ... async def calculate_statistics(data: list, column: str) -> dict: """Calculate descriptive statistics for a numeric column. Returns dict with keys: count, mean, median, min, max, std_dev. """ ... async def filter_data(data: list, column: str, operator: str, value: object) -> list: """Filter rows where column matches the condition. Operator: one of "==", "!=", ">", ">=", "<", "<=". """ ... ALL_TOOLS = { "fetch_data": fetch_data, "create_chart": create_chart, "calculate_statistics": calculate_statistics, "filter_data": filter_data, } ``` The `ALL_TOOLS` dict is the single source of truth. The agent introspects it to build the system prompt, and the sandbox uses it to resolve function calls. ## Example: programmatic tool-calling agent The `CodeModeAgent` implements the generate-execute-retry loop: ```python import flyte.sandbox from _tools import ALL_TOOLS class CodeModeAgent: def __init__(self, tools, *, model="claude-sonnet-4-6", max_retries=2): self._tools = tools self._model = model self._max_retries = max_retries # System prompt auto-generated from tool signatures + docstrings self.system_prompt = self._build_system_prompt() async def run(self, message: str, history: list[dict]) -> AgentResult: messages = [*history, {"role": "user", "content": message}] # Step 1: LLM generates Python code code = await generate_code(self._model, self.system_prompt, messages) # Step 2: Execute in Monty sandbox with registered tools for attempt in range(1 + self._max_retries): try: result = await flyte.sandbox.orchestrate_local( code, inputs={"_unused": 0}, tasks=list(self._tools.values()), ) return AgentResult(code=code, charts=result.get("charts", []), summary=result.get("summary", "")) except Exception as exc: if attempt < self._max_retries: # Step 3: Feed error back to LLM for retry code = await generate_code( self._model, self.system_prompt, [*messages, {"role": "assistant", "content": f"```python\n{code}\n```"}, {"role": "user", "content": f"Error: {exc}\nFix the code."}], ) continue return AgentResult(code=code, error=str(exc)) ``` The pattern: 1. **Generate**: The LLM receives tool signatures and the user's request, and outputs Python code. 2. **Execute**: The code runs in the Monty sandbox. Tool calls pause the sandbox, dispatch to real implementations, and resume with results. 3. **Retry**: If execution fails, the error message is fed back to the LLM, which generates a corrected version. This repeats up to `max_retries` times. ## Example: chat app Wrap the agent in a FastAPI endpoint to create a conversational analytics assistant: ```python from _agent import CodeModeAgent from _tools import ALL_TOOLS from fastapi import FastAPI import flyte from flyte.app.extras import FastAPIAppEnvironment app = FastAPI(title="Chat Data Analytics Agent") env = FastAPIAppEnvironment( name="chat-analytics-agent", app=app, image=flyte.Image.from_debian_base().with_pip_packages( "fastapi", "uvicorn", "httpx", "pydantic-monty", ), secrets=flyte.Secret(key="anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ) agent = CodeModeAgent(tools=ALL_TOOLS, max_retries=2) @app.post("/api/chat") async def chat(req: ChatRequest) -> ChatResponse: result = await agent.run(req.message, req.history) return ChatResponse( code=result.code, charts=result.charts, summary=result.summary, error=result.error, ) ``` Users send natural language requests (`"Show me monthly revenue trends for 2024"`), the agent generates analysis code, the sandbox executes it with the registered tools, and the response includes charts and a text summary. ## Example: durable agent For production workloads, wrap the tools as `@env.task` so the sandbox dispatches them as durable Flyte tasks through the controller. This gives you execution history, retries, caching, and full observability. ```python from _agent import CodeModeAgent from _tools import ALL_TOOLS import flyte import flyte.report env = flyte.TaskEnvironment( name="llm-code-mode", secrets=[flyte.Secret(key="anthropic-api-key", as_env_var="ANTHROPIC_API_KEY")], image=flyte.Image.from_debian_base().with_pip_packages( "httpx", "pydantic-monty", "unionai-reuse", ), ) # Wrap each tool as a durable task @env.task async def fetch_data(dataset: str) -> list: return await _tools.fetch_data(dataset) @env.task async def create_chart(chart_type: str, title: str, labels: list, values: list) -> str: return await _tools.create_chart(chart_type, title, labels, values) # ... wrap remaining tools similarly ... # Agent uses plain functions for prompt generation, # @env.task versions for durable sandbox execution durable_tools = {t.func.__name__: t for t in [fetch_data, create_chart, ...]} agent = CodeModeAgent(tools=ALL_TOOLS, execution_tools=durable_tools) @env.task(report=True) async def analyze(request: str) -> str: """Run the code-mode agent and render an HTML report.""" result = await agent.run(request, []) report_html = build_report(request, result) await flyte.report.replace.aio(report_html) await flyte.report.flush.aio() return result.summary ``` The key difference from the chat app: each tool call goes through the Flyte controller as a durable task. If `fetch_data` fails, Flyte retries it automatically. Every tool invocation is recorded and visible in the execution timeline. Run it with: ```bash flyte run durable_agent.py analyze \ --request "Show me monthly revenue trends for 2024, broken down by region" ``` ## References - [Code execution with MCP](https://www.anthropic.com/engineering/code-execution-with-mcp): Anthropic engineering blog on the code execution pattern - [Code Mode](https://blog.cloudflare.com/code-mode/): Cloudflare's introduction to code mode for LLM tool calling - [Code Mode MCP](https://blog.cloudflare.com/code-mode-mcp/): Cloudflare's server-side code mode implementation - [Code Mode Protocol](https://github.com/universal-tool-calling-protocol/code-mode): Open specification for the code mode pattern === PAGE: https://www.union.ai/docs/v2/union/user-guide/agents/sandboxing/code-sandboxing === Run arbitrary Python or shell inside an ephemeral, stateless container with flyte.sandbox.create. # Code sandboxing `flyte.sandbox.create()` runs arbitrary Python code or shell commands inside an ephemeral, stateless Docker container. The container is built on demand from declared dependencies, executed once, and discarded. Each invocation starts from a clean slate: no filesystem state, environment variables, or side effects carry over between runs. ## Execution modes `flyte.sandbox.create()` supports three mutually exclusive execution modes. ### Auto-IO mode The default mode. Write only the business logic. Flyte generates the I/O boilerplate automatically. How it works: 1. Flyte generates an `argparse` preamble that parses declared inputs from CLI arguments. 2. Declared inputs become local variables in scope. 3. After your code runs, Flyte writes declared scalar outputs to `/var/outputs/` automatically. ```python{hl_lines=[2, 4, 6, 11]} import flyte import flyte.sandbox sandbox = flyte.sandbox.create( name="double", code="result = x * 2", inputs={"x": int}, outputs={"result": int}, ) result = await sandbox.run.aio(x=21) # returns 42 ``` No imports, no argument parsing, no file writing. The variable `x` is available directly, and the variable `result` is captured automatically because it matches a declared output name. A more involved example with third-party packages: ```python{hl_lines=["4-9", 12, 20, 24]} import datetime _stats_code = """\ import numpy as np nums = np.array([float(v) for v in values.split(",")]) mean = float(np.mean(nums)) std = float(np.std(nums)) window_end = dt + delta """ stats_sandbox = flyte.sandbox.create( name="numpy-stats", code=_stats_code, inputs={ "values": str, "dt": datetime.datetime, "delta": datetime.timedelta, }, outputs={"mean": float, "std": float, "window_end": datetime.datetime}, packages=["numpy"], ) mean, std, window_end = await stats_sandbox.run.aio( values="1,2,3,4,5", dt=datetime.datetime(2024, 1, 1), delta=datetime.timedelta(days=1), ) ``` When there are multiple outputs, `.run()` returns them as a tuple in declaration order. ### Verbatim mode Set `auto_io=False` to run a complete Python script with full control over I/O. Flyte runs the script exactly as written: no injected preamble, no automatic output collection. Your script must: - Read inputs from `/var/inputs/` (files are bind-mounted at these paths) - Write outputs to `/var/outputs/` ```python{hl_lines=["4-9", 12, 17]} from flyte.io import File _etl_script = """\ import json, pathlib payload = json.loads(pathlib.Path("/var/inputs/payload").read_text()) total = sum(payload["values"]) pathlib.Path("/var/outputs/total").write_text(str(total)) """ etl_sandbox = flyte.sandbox.create( name="etl-script", code=_etl_script, inputs={"payload": File}, outputs={"total": int}, auto_io=False, ) total = await etl_sandbox.run.aio(payload=payload_file) ``` Use verbatim mode when you need precise control over how inputs are read and outputs are written, or when your script has its own argument parsing. ### Command mode Run any shell command, binary, or pipeline. Provide `command` instead of `code`. ```python{hl_lines=[5]} from flyte.io import File linecount_sandbox = flyte.sandbox.create( name="line-counter", command=[ "/bin/bash", "-c", "grep -c . /var/inputs/data_file > /var/outputs/line_count || echo 0 > /var/outputs/line_count", ], inputs={"data_file": File}, outputs={"line_count": str}, ) count = await linecount_sandbox.run.aio(data_file=data_file) ``` Command mode is useful for running test suites, compiled binaries, shell pipelines, or any non-Python workload. Use `arguments` to pass positional arguments to the command. File inputs are bind-mounted at `/var/inputs/` and can be referenced in the arguments list: ```python{hl_lines=[4, 5]} sandbox = flyte.sandbox.create( name="test-runner", command=["/bin/bash", "-c", pytest_cmd], arguments=["/var/inputs/solution.py", "/var/inputs/tests.py"], inputs={"solution.py": File, "tests.py": File}, outputs={"exit_code": str}, ) ``` ## Executing a sandbox Call `.run()` on the sandbox object to build the image and execute. **Async execution** ```python result = await sandbox.run.aio(x=21) ``` **Sync execution** ```python result = sandbox.run(x=21) ``` Both forms build the container image (if not already built), start the container, execute the code or command, collect outputs, and discard the container. `flyte.sandbox.create()` defines the sandbox configuration and can be called at module level or inside a task. The actual container execution happens when you call `.run()`, which must run inside a Flyte task (either locally or remotely on the cluster). ### Error handling If the sandbox code fails (non-zero exit code, Python exception, or timeout), `.run()` raises an exception with the error details. If `retries` is set, Flyte automatically retries the execution before surfacing the error. If the image build fails due to an invalid package, an `InvalidPackageError` is raised with the package name and the underlying error message. ## Supported types Inputs and outputs must use one of the following types: | Category | Types | | ---------------- | ----------------------------------------- | | **Primitive** | `int`, `float`, `str`, `bool` | | **Date/time** | `datetime.datetime`, `datetime.timedelta` | | **File handles** | `flyte.io.File` | ### How types are handled **In auto-IO mode:** - **Primitive and date/time inputs** are injected as local variables with the correct Python type. Flyte generates an `argparse` preamble behind the scenes. Your code just uses the variable names directly. - **`File` inputs** are bind-mounted into the container. The input variable contains the file path as a string (e.g., `"/var/inputs/payload"`), so you can read it with `pathlib.Path(payload).read_text()`. - **Primitive and date/time outputs** are written to `/var/outputs/` automatically. Just assign the value to a variable matching the declared output name. - **`File` outputs** are the exception: your code must write the file to `/var/outputs/` manually. **In verbatim mode:** - All inputs (including primitives) are available at `/var/inputs/`. Your script reads them directly from the filesystem. - All outputs must be written to `/var/outputs/` by your script. **In command mode:** - `File` inputs are bind-mounted at `/var/inputs/`. - All outputs must be written to `/var/outputs/` by your command. ## Configuring the container image ### Python packages Install PyPI packages with `packages`: ```python{hl_lines=[6]} sandbox = flyte.sandbox.create( name="data-analysis", code="...", inputs={"data": str}, outputs={"result": str}, packages=["numpy", "pandas>=2.0", "scikit-learn"], ) ``` ### System packages Install system-level (apt) packages with `system_packages`: ```python{hl_lines=[7]} sandbox = flyte.sandbox.create( name="image-processor", code="...", inputs={"image": File}, outputs={"result": File}, packages=["Pillow"], system_packages=["libgl1-mesa-glx", "libglib2.0-0"], ) ``` > [!NOTE] > `gcc`, `g++`, and `make` are included automatically in every sandbox image. ### Additional Dockerfile commands For advanced image customization, use `additional_commands` to inject arbitrary `RUN` commands into the Dockerfile: ```python{hl_lines=[6]} sandbox = flyte.sandbox.create( name="custom-env", code="...", inputs={"x": int}, outputs={"y": int}, additional_commands=["curl -sSL https://example.com/setup.sh | bash"], ) ``` ### Pre-built images Skip the image build entirely by providing a pre-built image URI: ```python{hl_lines=[6]} sandbox = flyte.sandbox.create( name="prebuilt", code="result = x + 1", inputs={"x": int}, outputs={"result": int}, image="ghcr.io/my-org/my-sandbox-image:latest", ) ``` ### Image configuration Control the registry and Python version with `ImageConfig`: ```python{hl_lines=["8-12"]} from flyte.sandbox import ImageConfig sandbox = flyte.sandbox.create( name="custom-registry", code="...", inputs={"x": int}, outputs={"y": int}, image_config=ImageConfig( registry="ghcr.io/my-org", registry_secret="ghcr-credentials", python_version=(3, 12), ), ) ``` ## Runtime configuration ### Resources Set CPU and memory limits for the container: ```python{hl_lines=[6]} sandbox = flyte.sandbox.create( name="heavy-compute", code="...", inputs={"data": str}, outputs={"result": str}, resources=flyte.Resources(cpu=4, memory="8Gi"), ) ``` The default is 1 CPU and 1Gi memory. ### Retries Automatically retry failed executions: ```python{hl_lines=[6]} sandbox = flyte.sandbox.create( name="flaky-task", code="...", inputs={"x": int}, outputs={"y": int}, retries=3, ) ``` ### Timeout Set a maximum execution time in seconds: ```python{hl_lines=[6]} sandbox = flyte.sandbox.create( name="bounded-task", code="...", inputs={"x": int}, outputs={"y": int}, timeout=300, # 5 minutes ) ``` ### Environment variables Inject environment variables into the container: ```python{hl_lines=[6]} sandbox = flyte.sandbox.create( name="configured-task", code="...", inputs={"x": int}, outputs={"y": int}, env_vars={"LOG_LEVEL": "DEBUG", "FEATURE_FLAG": "true"}, ) ``` ### Secrets Mount Flyte secrets into the container: ```python{hl_lines=[6]} sandbox = flyte.sandbox.create( name="authenticated-task", code="...", inputs={"query": str}, outputs={"result": str}, secrets=[flyte.Secret(key="api-key", as_env_var="API_KEY")], ) ``` ### Caching Control output caching behavior: ```python{hl_lines=["6-8"]} sandbox = flyte.sandbox.create( name="cached-task", code="...", inputs={"x": int}, outputs={"y": int}, cache="auto", # default โ€” Flyte decides based on inputs # cache="override" # force re-execution and update cache # cache="disable" # no caching ) ``` ## Deploying a sandbox as a task Use `.as_task()` to convert a sandbox into a deployable `ContainerTask`. The returned task has the generated script pre-filled as a default input, so retriggers from the UI only require user-declared inputs. This pattern is useful when you want to define a sandbox dynamically (for example, with LLM-generated code) and then deploy it as a standalone task that others can trigger from the UI. ```python{hl_lines=[4, 11, "33-38"]} import flyte import flyte.sandbox from flyte.io import File from flyte.sandbox import sandbox_environment # sandbox_environment provides the base runtime image for code sandboxes. # Include it in depends_on so Flyte builds the sandbox runtime before your task runs. env = flyte.TaskEnvironment( name="sandbox-demo", image=flyte.Image.from_debian_base(name="sandbox-demo"), depends_on=[sandbox_environment], ) @env.task async def deploy_sandbox_task() -> str: # Initialize the Flyte client for in-cluster operations (image building, deployment) flyte.init_in_cluster() sandbox = flyte.sandbox.create( name="deployable-sandbox", # In auto-IO mode, File inputs become path strings โ€” read with pathlib code="""\ import json, pathlib data = json.loads(pathlib.Path(payload).read_text()) total = sum(data["values"]) """, inputs={"payload": File}, outputs={"total": int}, resources=flyte.Resources(cpu=1, memory="512Mi"), ) # Build the image and get a ContainerTask with the script pre-filled task = await sandbox.as_task.aio() # Create a TaskEnvironment from the task and deploy it deploy_env = flyte.TaskEnvironment.from_task("deployable-sandbox", task) versions = flyte.deploy(deploy_env) return versions[0].summary_repr() ``` ## End-to-end example The following example defines sandboxes in all three modes, creates helper tasks, and runs everything in a single pipeline: ``` import datetime from pathlib import Path import flyte import flyte.sandbox from flyte.io import File from flyte.sandbox import sandbox_environment # {{docs-fragment create}} # sandbox_environment provides the base runtime for code sandboxes. # Include it in depends_on so the sandbox runtime is available when tasks execute. env = flyte.TaskEnvironment( name="sandbox-demo", image=flyte.Image.from_debian_base(name="sandbox-demo"), depends_on=[sandbox_environment], ) # Auto-IO mode: pure computation. The code string runs in an isolated sandbox; # only the declared inputs go in and only the declared outputs come back. sum_sandbox = flyte.sandbox.create( name="sum-to-n", code="total = sum(range(n + 1)) if conditional else 0", inputs={"n": int, "conditional": bool}, outputs={"total": int}, ) # {{/docs-fragment create}} # Auto-IO mode with packages _stats_code = """\ import numpy as np nums = np.array([float(v) for v in values.split(",")]) mean = float(np.mean(nums)) std = float(np.std(nums)) window_end = dt + delta """ stats_sandbox = flyte.sandbox.create( name="numpy-stats", code=_stats_code, inputs={ "values": str, "dt": datetime.datetime, "delta": datetime.timedelta, }, outputs={"mean": float, "std": float, "window_end": datetime.datetime}, packages=["numpy"], ) # Verbatim mode: full script control _etl_script = """\ import json, pathlib payload = json.loads(pathlib.Path("/var/inputs/payload").read_text()) total = sum(payload["values"]) pathlib.Path("/var/outputs/total").write_text(str(total)) """ etl_sandbox = flyte.sandbox.create( name="etl-script", code=_etl_script, inputs={"payload": File}, outputs={"total": int}, auto_io=False, ) # Command mode: shell pipeline linecount_sandbox = flyte.sandbox.create( name="line-counter", command=[ "/bin/bash", "-c", "grep -c . /var/inputs/data_file > /var/outputs/line_count || echo 0 > /var/outputs/line_count", ], inputs={"data_file": File}, outputs={"line_count": str}, ) @env.task async def create_text_file() -> File: path = Path("/tmp/data.txt") path.write_text("line 1\n\nline 2\n") return await File.from_local(str(path)) @env.task async def payload_generator() -> File: path = Path("/tmp/payload.json") path.write_text('{"values": [1, 2, 3, 4, 5]}') return await File.from_local(str(path)) @env.task async def run_pipeline() -> dict: # Auto-IO: sum 1..10 = 55 total = await sum_sandbox.run.aio(n=10, conditional=True) # Auto-IO with numpy mean, std, window_end = await stats_sandbox.run.aio( values="1,2,3,4,5", dt=datetime.datetime(2024, 1, 1), delta=datetime.timedelta(days=1), ) # Verbatim ETL payload = await payload_generator() etl_total = await etl_sandbox.run.aio(payload=payload) # Command mode: line count data_file = await create_text_file() line_count = await linecount_sandbox.run.aio(data_file=data_file) return { "sum_1_to_10": total, "mean": round(mean, 4), "std": round(std, 4), "window_end": window_end.isoformat(), "etl_sum_1_to_10": etl_total, "line_count": line_count, } if __name__ == "__main__": flyte.init_from_config() r = flyte.run(run_pipeline) print(f"run url: {r.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/sandboxing/code_sandbox.py* ## API reference ### `flyte.sandbox.create()` | Parameter | Type | Description | | --------------------- | ----------------- | ---------------------------------------------------------- | | `name` | `str` | Sandbox name. Derives task and image names. | | `code` | `str` | Python source to run. Mutually exclusive with `command`. | | `inputs` | `dict[str, type]` | Input type declarations. | | `outputs` | `dict[str, type]` | Output type declarations. | | `command` | `list[str]` | Shell command to run. Mutually exclusive with `code`. | | `arguments` | `list[str]` | Arguments forwarded to `command`. | | `packages` | `list[str]` | Python packages to install via pip. | | `system_packages` | `list[str]` | System packages to install via apt. | | `additional_commands` | `list[str]` | Extra Dockerfile `RUN` commands. | | `resources` | `flyte.Resources` | CPU and memory limits. Default: 1 CPU, 1Gi memory. | | `image_config` | `ImageConfig` | Registry and Python version settings. | | `image_name` | `str` | Explicit image name (overrides auto-generated). | | `image` | `str` | Pre-built image URI (skips build). | | `auto_io` | `bool` | Auto-generate I/O wiring. Default: `True`. | | `retries` | `int` | Number of retries on failure. Default: `0`. | | `timeout` | `int` | Timeout in seconds. | | `env_vars` | `dict[str, str]` | Environment variables for the container. | | `secrets` | `list[Secret]` | Flyte secrets to mount. | | `cache` | `str` | `"auto"`, `"override"`, or `"disable"`. Default: `"auto"`. | ### Sandbox methods | Method | Description | | --------------------------------- | ----------------------------------------------------------------- | | `sandbox.run(**kwargs)` | Build the image and execute synchronously. Returns typed outputs. | | `await sandbox.run.aio(**kwargs)` | Async version of `run()`. | | `sandbox.as_task()` | Build the image and return a deployable `ContainerTask`. | | `await sandbox.as_task.aio()` | Async version of `as_task()`. | Both `run()` and `as_task()` accept an optional `image` parameter to provide a pre-built image URI, skipping the build step. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts === Register task outputs and uploads as named, versioned artifacts, trigger runs on new versions, mount them into apps, and trace lineage. # Artifacts An artifact is a named, versioned reference to an object in storage. Instead of remembering which bucket path holds last week's training set, you register the output under a name, and downstream tasks, triggers, and apps refer to it by that name. Your data path does not change. Files, directories, and dataframes are offloaded to object storage exactly as before. An artifact adds a name, a version, and a record of where it came from. Registering under the same name again creates a new version, and Union records which run produced each version and which tasks and apps consume it, so you can trace a deployed model back to the dataset it was trained on. Any `flyte.io.File`, `flyte.io.Dir`, or `flyte.io.DataFrame` can become an artifact. The most common way is to wrap a task's return value: ```python @env.task(produces_artifacts=True) async def train() -> File: weights = await File.from_local("model.pt") return artifacts.new(weights, artifacts.Metadata(name="trained-model")) ``` ### **Artifacts > Task outputs as artifacts** Wrap a task's return value with `flyte.artifacts.new()` to register it as a named, versioned artifact with metadata and a model or data card. ### **Artifacts > Publish your own artifacts** Upload existing datasets and model weights from anywhere with `Artifact.create` or `flyte create artifact`, recording where they came from. ### **Artifacts > Prefetch Hugging Face models** Pull model weights from the Hugging Face Hub into your own storage as a model artifact, versioned by commit, with the model card attached. ### **Triggers > Trigger on new artifact versions** Run a task automatically whenever a new version of an artifact lands, using `flyte.OnArtifact`. It fires no matter who published the version. ### **Artifacts > Use artifacts in apps** Mount model weights and datasets into serving apps with `flyte.app.ArtifactValue`, resolved and pinned at deploy time. ### **Artifacts > Automatic lineage tracking** Union records who produced each artifact version and which tasks, triggers, and apps depend on it, and shows the graph in the UI. ### **Artifacts > Partitioned artifacts** Give each artifact version a day, hour, region, or other key with `partitions`, so you can address one slice of a dataset and list the slices you have. ### **Artifacts > Find and retrieve artifacts** Look up artifacts by name, version, partition, range, source run, kind, or attributes, from Python or the CLI, and pass them to runs. ### **Artifacts > Publish outputs of tasks you don't own** Register another task's outputs as artifacts from the caller with `flyte.artifacts.produces`, without changing the task. ## Related ### **Tasks** The unit of work that produces and consumes artifacts. ### **Apps** Long-running services that serve the models and datasets artifacts hold. ### **Factories** Declare how artifacts are made from other artifacts, and build any of them for a partition or a range on demand. ## Subpages - **Artifacts > Task outputs as artifacts** - Wrap a task's return value with `flyte.artifacts.new()` to register it as a named, versioned artifact with metadata and a model or data card. - **Artifacts > Publish your own artifacts** - Upload existing datasets and model weights from anywhere with `Artifact.create` or `flyte create artifact`, recording where they came from. - **Artifacts > Prefetch Hugging Face models** - Pull model weights from the Hugging Face Hub into your own storage as a model artifact, versioned by commit, with the model card attached. - **Artifacts > Use artifacts in apps** - Mount model weights and datasets into serving apps with `flyte.app.ArtifactValue`, resolved and pinned at deploy time. - **Artifacts > Automatic lineage tracking** - Union records who produced each artifact version and which tasks, triggers, and apps depend on it, and shows the graph in the UI. - **Artifacts > Partitioned artifacts** - Give each artifact version a day, hour, region, or other key with `partitions`, so you can address one slice of a dataset and list the slices you have. - **Artifacts > Find and retrieve artifacts** - Look up artifacts by name, version, partition, range, source run, kind, or attributes, from Python or the CLI, and pass them to runs. - **Artifacts > Publish outputs of tasks you don't own** - Register another task's outputs as artifacts from the caller with `flyte.artifacts.produces`, without changing the task. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts/task-outputs === Wrap a task's return value with `flyte.artifacts.new()` to register it as a named, versioned artifact with metadata and a model or data card. # Task outputs as artifacts The most common way to create an artifact is to register a task output. Two things are required: the task must be declared with `produces_artifacts=True`, and the return value must be wrapped with `flyte.artifacts.new()`. ```python import flyte from flyte import artifacts from flyte.io import File env = flyte.TaskEnvironment(name="training") @env.task(produces_artifacts=True) async def train() -> File: weights = await File.from_local("model.pt") return artifacts.new( weights, artifacts.Metadata( name="trained-model", description="Classifier trained on the latest training set", attrs={"framework": "pytorch"}, ), ) ``` Every run of this task registers a new version of `trained-model`. Union records the producing run on the artifact, so you can always trace a version back to the execution that created it. > [!WARNING] Both parts are required > The wrapper is stripped from the output value either way. Without `produces_artifacts=True` the platform never extracts the metadata, so no artifact is registered, no trigger fires, and there is nothing for an app to bind to. Nothing warns you. If you can't change the task, the caller can declare its outputs as artifacts instead. See **Artifacts > Publish outputs of tasks you don't own**. ## What can be an artifact An artifact must be an offloaded value: a `flyte.io.File`, a `flyte.io.Dir`, or a `flyte.io.DataFrame`. Primitives, dataclasses, and Pydantic models cannot be artifacts. Wrap a raw dataframe with `DataFrame.from_df()` first. The wrapped value must also be a top-level task output. Nesting an artifact inside a list, a dictionary, or a model raises an error. In a multi-output task, only the wrapped slot becomes an artifact: ```python @env.task(produces_artifacts=True) async def train() -> tuple[File, float]: ... return artifacts.new(weights, metadata), accuracy ``` ## Metadata `flyte.artifacts.Metadata` carries the identity of the artifact. Only `name` is required. If you leave out `version`, the version comes from the producing run, so every execution registers a distinct version. You can also set a `description`, string-valued `attrs` for searching and filtering, a `kind` (`"model"`, `"data"`, or `"generic"`), and a card. For models there is a helper that fills in the standard fields and records the artifact's kind as `model`: ```python card = artifacts.Card.create_from(content=card_html, format="html", card_type="model") metadata = artifacts.Metadata.create_model_metadata( name="trained-model", description="A toy classifier", framework="PyTorch", architecture="ResNet50", task="Image Classification", serial_format="pt", card=card, ) ``` A card is a document attached to the artifact and rendered in the UI. `flyte.artifacts.Card.create_from()` accepts inline content or a local file, in formats including HTML, Markdown, JSON, YAML, CSV, and PNG. ## Consuming artifacts in tasks Downstream tasks take artifacts as ordinary typed inputs. Fetch a reference with `flyte.remote.Artifact.get()` and pass it to `flyte.run()`: ```python from flyte.remote import Artifact model = Artifact.get("trained-model") # latest version data = Artifact.get("training-set", version="v3") # pinned version run = flyte.run(evaluate, model=model, data=data) ``` The task body receives a plain `File`, `Dir`, or `DataFrame` and needs no artifact-specific code. ## Reading an artifact's value directly Outside a task โ€” in a notebook or a local script โ€” materialize the value with `to_python()`, passing the type the artifact holds: ```python import asyncio import flyte from flyte.io import Dir from flyte.remote import Artifact flyte.init_from_config() async def load() -> str: artifact = Artifact.get("trained-model") weights = await artifact.to_python(Dir) # File or DataFrame for other artifacts return await weights.download() local = asyncio.run(load()) ``` In a notebook, `await` the two calls directly instead of wrapping them in `asyncio.run()`. The download runs wherever you call it, so that environment needs credentials for the object store. This is a plain fetch and records no **Artifacts > Automatic lineage tracking** edge. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts/publish-artifacts === Upload existing datasets and model weights from anywhere with `Artifact.create` or `flyte create artifact`, recording where they came from. # Publish your own artifacts Not every dataset or model is produced by a task. You can publish an existing asset as an artifact from anywhere: a laptop, a notebook, a CI job, or an external pipeline. This is how you bootstrap a registry from assets you already have. ## Publish an artifact ### Programmatic `flyte.remote.Artifact.create()` uploads the value and registers a version in one call: ```python import flyte from flyte.io import File from flyte.remote import Artifact flyte.init_from_config() published = Artifact.create( File.from_local_sync("data/2026-08-18.csv"), name="incoming_dataset", description="Dataset dropped off by a partner", external_ref="s3://partner-bucket/drop/2026-08-18.csv", ) print(published.name, published.version) ``` The call is synchronous by default; use `Artifact.create.aio(...)` from async code. ### CLI `flyte create artifact` publishes a file directly: ```bash flyte create artifact incoming_dataset --from-file data/2026-08-18.csv \ --external-ref s3://partner-bucket/drop/2026-08-18.csv flyte create artifact my-model --from-file model.pt --kind model --attr framework=torch flyte create artifact my-model --from-file model.pt --card model_card.html --card-type model ``` `--attr` is repeatable, `--kind` is one of `model`, `data`, or `generic`, and the card format is inferred from the file extension. If you do not pass a version, one is generated for you. Set attrs, kind, and a card the same way as in task-produced **Artifacts > Task outputs as artifacts > Metadata**. The external ref records where the data came from. When `Artifact.create()` runs inside a task, the producing run is stamped on the artifact automatically; outside a task, the external ref is the provenance you can attach. ## Finding artifacts ### Programmatic ```python from flyte.remote import Artifact Artifact.list_names() # all artifact names, with latest version info Artifact.listall("my-model") # every version of my-model, newest first Artifact.get("my-model", version="1.0") # one version Artifact.list_names(search="model") # names containing "model" Artifact.listall(source_run="my_run") # versions produced by a run Artifact.listall(kind="model", attrs={"framework": "torch"}) ``` ### CLI ```bash flyte get artifact # all artifact names, with latest version info flyte get artifact my-model # every version of my-model, newest first flyte get artifact my-model 1.0 # details of one version flyte get artifact --search model # names containing "model" flyte get artifact --source-run my_run # versions produced by a run flyte get artifact --kind model --attr framework=torch ``` `Artifact.get(name)` returns the latest version by default, and `listall` and `list_names` return iterators. For partitions, ranges, and more filters, see **Artifacts > Find and retrieve artifacts**. Artifacts are scoped to a project and domain. All of these calls accept `project` and `domain` arguments, and default to the ones in your config. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts/prefetch-models === Pull model weights from the Hugging Face Hub into your own storage as a model artifact, versioned by commit, with the model card attached. # Prefetch Hugging Face models `flyte.prefetch.hf_model()` downloads a model from the Hugging Face Hub into your own object storage and registers the result as a model artifact. It is the third way an artifact is created, alongside **Artifacts > Task outputs as artifacts** and **Artifacts > Publish your own artifacts**. ### Programmatic ```python import flyte import flyte.prefetch flyte.init_from_config() run = flyte.prefetch.hf_model(repo="HuggingFaceTB/SmolLM2-135M-Instruct") run.wait() ``` ### CLI ```bash flyte prefetch hf-model HuggingFaceTB/SmolLM2-135M-Instruct --wait ``` For the full how-to, including sharding for multi-GPU inference, resources, tokens for gated repos, CLI usage, and serving the result from a vLLM or SGLang endpoint, see **Inference > Prefetching models**. This page covers what a prefetch means for the artifact registry. ## What gets registered On success the platform records a model artifact for the stored weights: * The artifact name defaults to the last segment of the repo id, with `.` replaced by `-`, or set it with `artifact_name`. The example above registers `SmolLM2-135M-Instruct`. * The version is the Hugging Face commit ID. * The searchable metadata carries the model facts (framework, architecture, task, modality, serialization format) plus the source repo and commit. * The repo's README, if it has one, is attached as the model card. The prefetch task is cached. Its cache key covers the task's inputs (the repo, `artifact_name`, the model metadata, `shard_config` and `raw_data_path`) and its configuration (`resources`, `hf_token_key` and `force`), but not the upstream commit, which the task looks up only when it runs. Re-running a prefetch with the same arguments reuses the cached result and doesn't pick up a newer upstream commit. To download the repo's latest commit, increment `force` (`--force 1`, `--force 2`, and so on, on the CLI). If the commit has moved, it registers as a new version you can **Triggers > Trigger on new artifact versions**. ## Finding a prefetched model Retrieve it by name, or find it by where it came from. The source repo and commit are recorded as searchable metadata: ### Programmatic ```python from flyte.remote import Artifact model = Artifact.get("SmolLM2-135M-Instruct") models = Artifact.listall(attrs={"source_repo": "HuggingFaceTB/SmolLM2-135M-Instruct"}) ``` ### CLI ```bash flyte get artifact SmolLM2-135M-Instruct flyte get artifact --attr source_repo=HuggingFaceTB/SmolLM2-135M-Instruct ``` Those `source_repo` and `source_commit` attributes are what make a prefetched model traceable back to its Hub repo and commit. To load the weights yourself rather than passing them to a task, see **Artifacts > Task outputs as artifacts > Reading an artifact's value directly**. Once prefetched, mount the model into a serving app with an artifact parameter. See **Artifacts > Use artifacts in apps**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts/artifacts-in-apps === Mount model weights and datasets into serving apps with `flyte.app.ArtifactValue`, resolved and pinned at deploy time. # Use artifacts in apps A serving app usually needs model weights or reference data on disk before it starts. Instead of baking them into the image or downloading them in startup code, declare an artifact as an app parameter and Union mounts it for you. `flyte.app.ArtifactValue` names the artifact, and the parameter's `mount` says where its contents appear in the container: ```python import flyte import flyte.app env = flyte.app.AppEnvironment( name="classifier-api", resources=flyte.Resources(cpu="2", memory="8Gi"), parameters=[ flyte.app.Parameter( name="model", value=flyte.app.ArtifactValue(name="trained-model", type="directory"), mount="/tmp/model", ) ], ) ``` The app code reads `/tmp/model` like any local directory. Only `flyte.io.File` and `flyte.io.Dir` artifacts can be app parameters; set `type` to `"file"` or `"directory"` to match. The prebuilt serving environments accept an `ArtifactValue` directly. For example, the vLLM and SGLang app environments take one as `model_path`, which pairs naturally with **Artifacts > Prefetch Hugging Face models**. ## Versions are pinned at deploy time The artifact is resolved when the app is deployed. If you leave out `version`, the latest version at deploy time is chosen and pinned, so a new version published later does not swap weights under a running app. Redeploy to move to the newer version, or pass an explicit `version=` to stay on a known one. Union records exactly which artifact version each app deployment resolved, so the artifact's **Artifacts > Automatic lineage tracking** shows every app serving it. ## Apps can publish artifacts too An app endpoint can call `flyte.remote.Artifact.create()` to register a new version from inside the app, for example to snapshot state it has built up. That version behaves like any other: it shows up in the registry and can fire **Triggers > Trigger on new artifact versions**. One difference from a task output: outside a task there is no producing run to stamp on the version, so pass `external_ref` if you want the new version to record where its data came from. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts/lineage === Union records who produced each artifact version and which tasks, triggers, and apps depend on it, and shows the graph in the UI. # Automatic lineage tracking Every artifact version carries its history with it. Union records who produced it and everything that depends on it, without any configuration on your part. The result is a graph you can walk in either direction: from a deployed model back to the run and dataset that produced it, or from a dataset forward to every model, trigger, and app that consumes it. ## What gets recorded On the producer side, each version records how it came to exist: * A task output records the run and task that produced it, with a link to that execution and its inputs and logs. * An upload through `flyte.remote.Artifact.create()` or `flyte create artifact` records who published it, and the `external_ref` if one was given, pointing at the original location of the data. * A Hugging Face prefetch records the source repo and commit. On the consumer side, Union records each place a version is bound to compute: * Apps whose deployment resolved the artifact as a parameter, down to the exact pinned version. * Triggers watching the artifact name, and the runs they started. ## The lineage view Each artifact in the UI has a **Lineage** tab that draws this graph. The source action that produced the artifact sits on the left, and the dependents fan out on the right: the triggers watching the artifact name, and the apps pinning the selected version. App and run nodes link to their own pages, so you can jump from the graph to a consuming app's deployment or the producing run's logs. Trigger rows expand in place to reveal the runs they started. The neighboring tabs break out the same relationships as lists: **Versions** shows the full version history, **Triggers** and **Apps** list what depends on the artifact, and **Artifact card** renders the attached model or data card. Before deleting or reworking a dataset, you can see every model trained on it and every app serving those models. When a served model misbehaves, you can walk back to the training run and the exact dataset version it consumed. You can query the same relationships in code: ### Programmatic ```python from flyte.remote import Artifact Artifact.listall(source_run="my_run") # what a run produced Artifact.listall(source_external_ref="s3://partner-bucket/drop/2026-08-18.csv") model = Artifact.get("trained-model") print(model.source, model.created_by, model.url) ``` ### CLI ```bash flyte get artifact --source-run my_run # what a run produced flyte get artifact --source-external-ref s3://partner-bucket/drop/2026-08-18.csv ``` `url` links to the artifact's page in the UI. ## What is not recorded Calling `Artifact.get()` in your own code and reading the data is a plain fetch, and does not create a consumer edge in the graph. Passing an artifact as a task input does not record a consumer edge yet either. Today the tracked dependencies are apps that declare the artifact as a parameter and the runs started by artifact triggers. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts/partitions === Give each artifact version a day, hour, region, or other key with `partitions`, so you can address one slice of a dataset and list the slices you have. # Partitioned artifacts > [!NOTE] > Requires flyte 2.10.0 or later. An ingest job writes raw events every day for each region. If every run publishes a new version of one `raw_events` artifact, the versions pile up in a flat list. Finding "the US data for August 2" means reading descriptions, and a backfill has no way to ask which days already exist. Partitions fix this. Each version records the day and region it holds, and those values are part of its identity: ```python import asyncio from datetime import date, timedelta import flyte import flyte.artifacts as artifacts from flyte.io import File env = flyte.TaskEnvironment(name="ingest") @env.task(produces_artifacts=True) async def ingest(day: date, region: str) -> File: file = await File.from_local(f"/data/{region}/{day}.parquet") return artifacts.new( file, artifacts.Metadata(name="raw_events", partitions={"date": day, "region": region}), ) @env.task async def main(days: int = 3) -> None: start = date(2026, 8, 1) await asyncio.gather( *(ingest(start + timedelta(days=d), r) for d in range(days) for r in ("us", "eu")) ) ``` One run of `main` fills six partitions. Now you can ask for exactly the slice you want: ```python from flyte.remote import Artifact us_aug_2 = Artifact.get("raw_events", date=date(2026, 8, 2), region="us") ``` See **Artifacts > Find and retrieve artifacts** for ranges, listing partition values, and more. To run a task each time a partition lands, see **Triggers > Trigger on partitions**. > [!WARNING] Partition keys are fixed per artifact name > The first partitioned version of `raw_events` fixes its keys to `date` and `region`. A later version published with different keys does not change them, and neither does adding partitions to an artifact that was declared without any. To use different keys, publish under a new artifact name. See **Artifacts > Partitioned artifacts > Partition keys are fixed**. ## Partition values `Metadata.partitions` maps a partition key to a value. The Python type of the value decides what kind of partition it is: | Value | Partition | |---|---| | `datetime.date` | Daily time partition | | `datetime.datetime` | Hourly time partition, floored to the hour in UTC. A naive `datetime` is treated as UTC | | `flyte.artifacts.TimePartition(value, "week")` or `"month"` | Weekly or monthly time partition. Use it for the coarser granularities, or to be explicit | | Anything else | String partition, stored as `str(value)`. `7` becomes `"7"` | A version can carry at most one time partition, plus any number of string partitions. A `None` value is rejected, since an unset partition is almost always a bug. ```python # Hourly artifacts.Metadata(name="raw_events_hourly", partitions={"hour": datetime(2026, 8, 1, 9, 30)}) # Monthly artifacts.Metadata( name="monthly_report", partitions={"date": artifacts.TimePartition(date(2026, 8, 1), "month")}, ) ``` ## Republishing a partition Publishing to a partition that already has a version adds a new version. It does not overwrite the old one. Reads by partition return the newest version, and older ones stay addressable by their version id. A rerun of a failed day is safe, and you can always see what the partition held before. ## Publishing from outside a task Publishing from a script or the CLI takes the same partition values. Use it to backfill partitions from data you already have: ### Programmatic ```python import flyte from flyte.io import File from flyte.remote import Artifact flyte.init_from_config() Artifact.create( File.from_local_sync("backfill/2026-07-31-us.parquet"), name="raw_events", partitions={"date": date(2026, 7, 31), "region": "us"}, ) ``` ### CLI ```bash flyte create artifact raw_events --from-file backfill/2026-07-31-us.parquet \ --partition date=2026-07-31 --partition region=us ``` An ISO date (`2026-07-31`) is a daily partition, an ISO hour (`2026-07-31T09`) an hourly one, and anything else a string partition. Weekly and monthly partitions need the Python API. `--partition` on `flyte create artifact` is newer than the rest of this page; if `flyte create artifact --help` doesn't list it, upgrade flyte. ## Partition keys are fixed An artifact name has one set of partition keys. They are fixed once, by whichever comes first: * The first version published **with** partitions. A version published without partitions never fixes the keys. * A declaration with `Artifact.declare`. See **Artifacts > Partitioned artifacts > Fixing the keys up front**. After that, no later version changes them. For `raw_events`, fixed to `date` and `region`: | You publish | Result | |---|---| | A version with an extra key, such as `channel` | The keys stay `date` and `region` | | A version without one of the keys, such as `date` alone | The keys stay `date` and `region` | | A version without partitions | The keys stay `date` and `region` | The same holds for an artifact declared with no partitions: a version published with partitions leaves it unpartitioned. There is one case where adding partitions does change an artifact: its earlier versions have no partitions, and it was never declared. Then the first partitioned version fixes the keys, and the earlier versions no longer match them. To prevent this, declare the artifact with no partitions. A version whose keys differ from the artifact's is not rejected. It is published after the task that made it has finished, so the registry stores it as published instead of failing the run. Compare its `partitions` with `Artifact.get_schema(name)` to find it. ### Changing an artifact's keys To use different keys, publish under a new artifact name. Publishing versions with the new keys does not change the old name, and declaring different keys fails. Deleting versions does not reliably reset the keys either. Declared keys stay after every version is deleted. Keys fixed by a first version are dropped only when the last version is deleted. ## Fixing the keys up front When several teams or jobs write the same artifact, declare the keys before anyone publishes, so the first writer can't fix the wrong ones by accident: ```python Artifact.declare("raw_events", {"date": date, "region": str}) Artifact.declare("raw_events_hourly", {"hour": datetime, "region": str}) Artifact.declare("monthly_report", {"date": "month"}) ``` A key maps to `date` (or `"day"`) for daily, `datetime` (or `"hour"`) for hourly, `"week"` or `"month"` for the coarser time partitions, and `str` for a string partition. Declaring again with the same keys is a no-op. Declaring different keys fails, because changing an artifact's keys means using a new name. An artifact that is read by version, not by partition, can be declared with no keys. Then a version published with partitions by mistake can't make it partitioned: ```python Artifact.declare("tracking_data", {}) ``` `Artifact.get_schema(name)` returns the keys an artifact has, and whether they were declared or fixed by the first version. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts/retrieving-artifacts === Look up artifacts by name, version, partition, range, source run, kind, or attributes, from Python or the CLI, and pass them to runs. # Find and retrieve artifacts Different consumers ask different questions of the registry. An evaluation job wants the latest model. A backfill wants the newest version of every August partition. A dashboard wants the list of regions that have data, and an auditor wants everything a given run produced. Each of these is one call on `flyte.remote.Artifact`, or one `flyte get artifact` command. The recipes below go from simple to specific. The Python calls need a client, so call `flyte.init_from_config()` first. All of them accept `project=` and `domain=` and default to your config. ```python from datetime import date, datetime import flyte from flyte.remote import Artifact flyte.init_from_config() ``` ## By name and version ### Programmatic ```python model = Artifact.get("trained-model") # latest version model = Artifact.get("trained-model", version="v3") # a pinned version ``` ### CLI ```bash flyte get artifact trained-model # every version, newest first flyte get artifact trained-model v3 # one version ``` ## One partition For a **Artifacts > Partitioned artifacts**, pass one value per partition key to get the latest version of that partition: ### Programmatic ```python events = Artifact.get("raw_events", date=date(2026, 8, 2), region="us") ``` ### CLI ```bash flyte get artifact raw_events --partition date=2026-08-02 --partition region=us ``` A `date` matches a daily partition, a `datetime` an hourly one, and a string that reads as an ISO date or timestamp is treated as a time value too. If a key name clashes with an argument of `get` (such as `name` or `version`), pass it in a `partitions={...}` mapping instead. ## A range of partitions `listall` takes a `(start, end)` tuple on the time key, inclusive at both ends, and a list on a string key to match any of its values. Add `latest_per_partition=True` to get one version per partition instead of every version: ### Programmatic ```python august = list( Artifact.listall( "raw_events", date=(date(2026, 8, 1), date(2026, 8, 31)), region=["us", "eu"], latest_per_partition=True, ) ) for a in august: print(a.partitions, a.version) ``` ### CLI ```bash flyte get artifact raw_events --partition date=2026-08-01..2026-08-31 --partition region=us,eu --latest-per-partition ``` This is the query a backfill plans with: compare the partitions that came back against the days you expect, and fill the gaps. ## The values a partition key has `partition_values` returns the distinct values of one key, sorted. Other keys narrow it: ```python Artifact.partition_values("raw_events", "region") # ["eu", "us"] Artifact.partition_values("raw_events", "date", region="us") # [date(2026, 8, 1), ...] ``` Time keys come back as `date` values, or `datetime` for hourly partitions. `Artifact.get_schema(name)` tells you which keys an artifact has. ## By where it came from, or what it is `listall` filters server-side on provenance and metadata. Combine as many as you need: ### Programmatic ```python Artifact.listall(source_run="my-run") # everything a run produced Artifact.listall(source_run="my-run", source_action="a0") # one action of that run Artifact.listall(source_external_ref="s3://partner-bucket/drop/2026-08-18.csv") Artifact.listall(kind="model", attrs={"framework": ["torch", "jax"]}) # any listed value matches Artifact.listall("trained-model", created_after=datetime(2026, 8, 1), limit=10) ``` ### CLI ```bash flyte get artifact --source-run my-run flyte get artifact --kind model --attr framework=torch ``` `listall` returns an iterator, newest first. ## Browsing names ### Programmatic ```python for group in Artifact.list_names(search="events"): print(group) ``` ### CLI ```bash flyte get artifact # every name, with its latest version and version count flyte get artifact --search events ``` ## Passing what you found to a run An `Artifact` binds to a task input of the matching type. The task receives a plain `File`, `Dir`, or `DataFrame`: ```python run = flyte.run(summarize, events=Artifact.get("raw_events", date=date(2026, 8, 2), region="eu")) ``` A task that takes a list accepts a list of artifacts. `listall` is an iterator, so materialize it first: ```python august = list(Artifact.listall("raw_events", date=(date(2026, 8, 1), date(2026, 8, 31)), latest_per_partition=True)) run = flyte.run(monthly_rollup, days=august) ``` To load the data in a notebook or script instead, see **Artifacts > Task outputs as artifacts > Reading an artifact's value directly**. ## Things to know * `get` returns exactly one version. It rejects a range or a list (use `listall`) and a version combined with partition values, since a version already names one artifact. * `latest_per_partition` needs an artifact name. * A read by partition raises an error when that partition has no version yet. === PAGE: https://www.union.ai/docs/v2/union/user-guide/artifacts/declared-artifacts === Register another task's outputs as artifacts from the caller with `flyte.artifacts.produces`, without changing the task. # Publish outputs of tasks you don't own > [!NOTE] > Requires flyte 2.10.0 or later. Another team maintains a shared `clean` task. It returns a plain `File` and knows nothing about artifacts. Your pipeline calls it once per day and region, and you want each output registered as a partition of `clean_events`. You can't wrap its return value with `flyte.artifacts.new()`, because the task isn't yours to edit. `flyte.artifacts.produces` lets the caller declare which outputs become artifacts: ```python import asyncio from datetime import date, timedelta import flyte import flyte.artifacts as artifacts from flyte.io import File env = flyte.TaskEnvironment(name="pipeline") # Owned by another team. It returns a plain File. @env.task async def clean(day: date, region: str) -> File: ... async def clean_one(day: date, region: str) -> File: with artifacts.produces( o0=artifacts.Metadata(name="clean_events", partitions={"date": day, "region": region}) ): return await clean.override(produces_artifacts=True)(day=day, region=region) @env.task async def main(days: int = 2) -> None: start = date(2026, 8, 1) await asyncio.gather( *(clean_one(start + timedelta(days=d), r) for d in range(days) for r in ("us", "eu")) ) ``` Each call publishes one `clean_events` version, partitioned by its own day and region. The result is the same as if `clean` had returned `artifacts.new(...)` itself: the version's source is the action that ran `clean`, and it shows up in **Artifacts > Automatic lineage tracking** and fires **Triggers > Trigger on new artifact versions** like any other. ## How it works * **Keyword names are output slots.** `o0` is the first output, `o1` the second, and so on. Outputs you don't name stay ordinary outputs. * **The call needs `produces_artifacts=True`.** That flag is what lets the platform publish a task's outputs. Turn it on for this call with `.override(produces_artifacts=True)`. Without it, nothing is published. * **Call one task per block.** The declaration applies to every task called inside the `with` block, so keep one call per block. Concurrent calls, as in `asyncio.gather` above, each keep their own declaration. It does not pass on to the actions that the called task spawns. * **Publishing happens on success.** If the called task fails, nothing is published. * **Outside a task, `produces` does nothing.** ## Publishing only some outputs A task that returns several values publishes only the slots you declare. Here `train` returns a model and a training log, and only the model is registered: ```python with artifacts.produces(o0=artifacts.Metadata(name="events_model", kind="model")): model, _log = await train.override(produces_artifacts=True)(features=features) ``` ## When the task also wraps its output If the called task already returns `artifacts.new(...)`, the caller's declaration wins for the name, version, partitions, and parents. The task's own description, card, and attrs fill in whatever the caller leaves empty. This lets you reuse a task that publishes under its own name, but file its output under yours. ## Remote task references The same works for a task you only have a reference to, such as one deployed by another team. Fetch it, turn on publishing, and declare its outputs: ```python ref = flyte.remote.Task.get("other_team.clean", auto_version="latest") callee = await ref.override.aio(produces_artifacts=True) with artifacts.produces(o0=artifacts.Metadata(name="clean_events", partitions={"date": day, "region": region})): await callee(day=day, region=region) ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/authenticating === Authenticate with Union.ai using OAuth2, API keys, and service accounts. # Authenticating with Union Union supports three authentication modes to suit different environments and use cases. This guide will help you choose the right authentication method and configure it correctly. ## Quick start For most users getting started with Union: ### Programmatic ```python import flyte # Initialize with PKCE authentication (default) flyte.init(endpoint="dns:///your-endpoint.hosted.unionai.cloud") ``` Or, if you have a configuration file: ```python import flyte flyte.init_from_config() ``` ### CLI 1. Create a configuration file: ```bash flyte create config --endpoint https://your-endpoint.unionai.cloud ``` Optionally, you can also add a default project and domain. ```bash flyte create config --endpoint http://your-endpoint.unionai.cloud --project flytesnacks --domain development ``` 2. Run any command to authenticate: ```bash flyte get project ``` This will automatically open your browser to complete authentication. > [!NOTE] > For details on creating and managing configuration files, see **Get started > Run modes > Run on a deployed cluster > Configuration file**. ## Authentication modes ### PKCE authentication (browser-based) {#pkce} **Default mode** - Uses OAuth2 PKCE flow with automatic browser authentication. #### When to use - Interactive development on your laptop or workstation - Jupyter notebooks running locally or on machines with browser access - Any environment where you can open a web browser #### How it works When you run any Flyte command, Union automatically: 1. Opens your default web browser 2. Prompts you to authenticate 3. Stores credentials securely in your system's keyring that auto-refresh every few hours > [!NOTE] > Tokens are stored securely in your system's native keyring (e.g., Keychain Access on macOS). On systems without keyring support, see the **Authenticating with Union > Token storage and keyring** section. #### Usage ### Programmatic ```python import flyte import flyte.remote as remote # Initialize with PKCE authentication (default) flyte.init(endpoint="dns:///your-endpoint.hosted.unionai.cloud") print([t for t in remote.Task.listall(project="flytesnacks", domain="development")]) ``` If your configuration file is accessible, you can also initialize with `init_from_config`: ```python import flyte flyte.init_from_config("/path/to/config.yaml") ``` Or omitting the path to pick up from the default locations: ```python flyte.init_from_config() ``` ### CLI This is the default authentication type when you create a configuration from the `flyte create config` command. The generated file has the effect of: ```yaml admin: endpoint: dns:///your-endpoint.hosted.unionai.cloud authType: Pkce insecure: false ``` Since the PKCE method is default, it's omitted from the generated file, as is disabling SSL. Simply run any command - authentication happens automatically: ```bash flyte get project flyte run app.py main flyte deploy app.py ``` ### Device flow authentication {#device-flow} **For headless or browser-restricted environments** - Uses OAuth2 device flow with code verification. > [!IMPORTANT] > Device flow is temporarily unavailable for newly provisioned Union organizations while we transition authentication providers. Organizations that already use device flow can continue to do so. For new organizations, use **Authenticating with Union > PKCE** when a browser is available or an **Authenticating with Union > API key** for non-interactive access. #### When to use - Remote servers without GUI/browser access - Hosted notebook environments (Google Colab, AWS SageMaker, Azure ML) - SSH sessions or terminal-only environments - Docker containers where browser redirect isn't possible #### How it works When you run a command, Union displays a URL and user code. You: 1. Open the URL on any browser (on any device) 2. Enter the displayed code 3. Complete authentication 4. Return to your terminal - the session is now authenticated Tokens are stored securely in your system's keyring. On systems without keyring support (common in headless Linux environments), see the **Authenticating with Union > Token storage and keyring** section. #### Usage ### Programmatic **In Python scripts:** ```python import flyte env = flyte.TaskEnvironment("my-project") @env.task def my_task(): return "Hello Union!" if __name__ == "__main__": # Initialize with device flow authentication flyte.init(endpoint="dns:///your-union-endpoint", auth_type="DeviceFlow") # Your workflow execution code here ``` **Example: Google Colab** ```python # In a Colab notebook import flyte # This will display a URL and code in the cell output flyte.init( endpoint="dns:///your-union-endpoint", auth_type="DeviceFlow" ) # Define and run your workflows env = flyte.TaskEnvironment("my-project") @env.task def process_data(data: str) -> str: return f"Processed: {data}" ``` ### CLI Create or update your config to use device flow: ```bash flyte create config --endpoint http://your-endpoint.unionai.cloud --auth-type headless ``` Your config file will contain: ```yaml admin: authType: DeviceFlow endpoint: dns:///your-endpoint.hosted.unionai.cloud ``` When you run a command, you'll see: ```bash flyte get app ``` Output: ```bash To Authenticate, navigate in a browser to the following URL: https://signin.hosted.unionai.cloud/activate?user_code=TKBJXFFW ``` Open that URL on any device with a browser, enter the code, and authentication completes. ### API key authentication (OAuth2 app credentials) {#api-key} **For automated and CI/CD environments** - Uses OAuth2 client credentials encoded as an API key. #### When to use - CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins) - Automated deployment scripts - Production workloads - Any non-interactive environment - Service-to-service authentication #### How it works Union encodes OAuth2 client credentials (client ID and client secret) into a single API key string. This key contains all information needed to connect to Union, including the endpoint. > [!NOTE] > **Security Note:** API keys are sensitive credentials. Treat them like passwords: > > - Store them in secret management systems (GitHub Secrets, AWS Secrets Manager, etc.) > - Never commit them to version control > - Rotate them regularly > - Use different keys for different environments #### Usage ### Programmatic The Flyte SDK provides two methods for initializing with API keys: 1. **Using `flyte.init_from_api_key()`** (recommended for API key authentication): ```python import flyte # Initialize with API key from FLYTE_API_KEY environment variable (default) flyte.init_from_api_key() # Or explicitly pass the API key flyte.init_from_api_key(api_key="your-encoded-api-key") # Use with remote APIs import flyte.remote as remote tasks = remote.Task.listall(project="flytesnacks", domain="development") ``` 2. **Using `flyte.init()` with api_key parameter**: ```python import flyte # Initialize with API key - endpoint is embedded in the key flyte.init(api_key="your-encoded-api-key") # Use with remote APIs import flyte.remote as remote tasks = remote.Task.listall(project="flytesnacks", domain="development") ``` Both methods work identically. The `init_from_api_key()` method is a convenience function specifically designed for API key authentication. If no `api_key` parameter is provided, it automatically reads from the `FLYTE_API_KEY` environment variable. > [!NOTE] > Use `flyte.init_from_api_key()` or `flyte.init(api_key=...)` for API key authentication, **not** `flyte.init_from_config()`. `init_from_config()` reads its auth settings from a `config.yaml` file, which has no API key field, so it cannot authenticate with an API key. > [!NOTE] > The API key is a base64-encoded string containing endpoint, client_id, client_secret, and org information. The SDK automatically decodes this and uses OAuth2 client credentials flow for authentication. **Example: Automated deployment script** ```python #!/usr/bin/env python3 import flyte env = flyte.TaskEnvironment("my-project") @env.task def automated_task(): return "Deployed from automation" if __name__ == "__main__": # Option 1: Use init_from_api_key (reads from FLYTE_API_KEY env var by default) flyte.init_from_api_key() # Option 2: Explicitly pass the API key # import os # api_key = os.getenv("FLYTE_API_KEY") # if not api_key: # raise ValueError("FLYTE_API_KEY environment variable not set") # flyte.init_from_api_key(api_key=api_key) # Deploy or run workflows # ... your deployment code here ``` **Example: Script using Flyte remote APIs** When you're not declaring tasks but only calling remote APIs, you can call `flyte.init()` at module level (similar to notebooks): ```python #!/usr/bin/env python3 import flyte import flyte.remote as remote # Initialize with API key flyte.init_from_api_key() # Use remote APIs tasks = remote.Task.listall(project="flytesnacks", domain="development") for task in tasks: print(f"Task: {task.name}") ``` ### CLI 1. Install the Union plugin: ```bash pip install flyteplugins-union ``` 2. Create the API key, and copy the `FLYTE_API_KEY` value it prints (it's shown only once): ```bash flyte create api-key --name my-ci-key ``` 3. Store this key securely (e.g., in GitHub Secrets, secret manager) **Managing API keys** Create a key: ```bash flyte create api-key --name my-ci-key ``` This creates OAuth application credentials and prints an `export FLYTE_API_KEY="..."` command to use the key. OAuth applications should not be confused with Union Apps, which are a different construct entirely. List existing keys: ```bash flyte get api-key ``` Delete a key: ```bash flyte delete api-key my-ci-key ``` #### Using API keys with Union apps API keys created with `flyte create api-key` can be used to authenticate requests to Union Apps hosted on your Union cluster. However, note that: > [!IMPORTANT] > API keys **cannot** be used directly against Union APIs (like the admin API) unless you're using the Flyte SDK or another language SDK/OAuth2 client. For direct API access, contact the Union team for guidance on proper authentication methods. **Using API keys with Union Apps:** When you create an API key using `flyte create api-key`, you can use it to invoke HTTP endpoints in your Union Apps by passing it in the `Authorization: Bearer` header: Create an API key: ```bash flyte create api-key --name my-app-key ``` Use the API key to call a Union App endpoint: ```bash curl -H "Authorization: Bearer " \ https:///profile ``` Replace `` with the `FLYTE_API_KEY` value that `flyte create api-key` printed, and `` with your app's endpoint hostname. **Example response:** ```json { "subject": "Some-subject-id", "name": "" } ``` The `/profile` endpoint (or similar identity endpoints in your app) returns information about the authenticated identity. When using an API key, this will be a bot identity, as the API key uses client app ID and secret for authentication. > [!TIP] > Different Union Apps may expose different endpoints. Common patterns include: > > - `/profile` or `/me` - Returns the authenticated user/bot identity > - `/health` - Health check endpoint > - Custom application endpoints specific to your workflow ## Comparison table | Feature | PKCE | Device Flow | API Key | |---------|------|-------------|---------| | **Environment** | Browser available | Headless/remote | Fully automated | | **Authentication** | Automatic browser | Manual code entry | Non-interactive | | **Token refresh** | Automatic | Automatic | Automatic | | **Best for** | Local development | Remote notebooks | CI/CD, production | | **Setup complexity** | Minimal | Minimal | Moderate (creating a key requires `flyteplugins-union`) | | **Security** | User credentials | User credentials | App credentials | ## Switching between authentication modes You can switch authentication modes by updating your config file: Switch to PKCE: ```bash flyte create config --endpoint dns:///your-endpoint.hosted.unionai.cloud ``` Switch to device flow: ```bash flyte create config --endpoint dns:///your-endpoint.hosted.unionai.cloud --auth-type headless ``` Or manually edit your `~/.flyte/config.yaml`: ```yaml admin: authType: Pkce # or DeviceFlow endpoint: dns:///your-union-endpoint ``` ## Token storage and keyring {#token-storage} Flyte stores authentication tokens securely using your system's native keyring. This provides secure credential storage and allows you to stay authenticated across CLI commands and interactive sessions without re-authenticating. ### How it works When you authenticate using PKCE or device flow, Flyte stores your OAuth tokens in: - **macOS**: Keychain Access - **Windows**: Windows Credential Manager - **Linux**: Secret Service API (GNOME Keyring, KWallet, etc.) These tokens are automatically refreshed as needed across multiple commands and sessions. ### Systems without keyring support Some environments, particularly headless Linux systems like remote desktops, Docker containers, or minimal server installations, may not have a keyring service available. **Symptoms:** - You are prompted to re-authenticate every time you run a Flyte command - You need to authenticate again each time you start a new interactive Python session - You see warnings about keyring access failures ### Solution: Install keyrings.alt For systems without native keyring support, install the `keyrings.alt` package: ```bash pip install keyrings.alt ``` This package provides an alternative keyring backend that stores credentials unencrypted in a plain-text file on disk, allowing token persistence across sessions. **Installation in different environments:** Standard installation: ```bash pip install keyrings.alt ``` With UV: ```bash uv pip install keyrings.alt ``` In a Docker container (add to your Dockerfile): ```dockerfile RUN pip install keyrings.alt ``` After installing `keyrings.alt`, Flyte will automatically use it to store tokens, eliminating the need for repeated authentication. > [!NOTE] > While `keyrings.alt` is less secure than native keyring systems, it's significantly better than re-authenticating for every command and is appropriate for headless development environments. ### Verifying keyring functionality To check if keyring is working correctly: ```python import keyring print(keyring.get_keyring()) ``` You should see output indicating which keyring backend is active: - Native keyring: `keyring.backends.Windows.WinVaultKeyring` (Windows), etc. - Alternative keyring: `keyrings.alt.file.PlaintextKeyring` or similar On macOS, Flyte doesn't use the `keyring` backend. It stores tokens in the default keychain through `/usr/bin/security`, so this check doesn't show where Flyte stores tokens. ## Troubleshooting ### Browser doesn't open for PKCE If the browser doesn't open automatically: 1. Copy the URL shown in your terminal 2. Open it manually in your browser 3. Complete the authentication flow Alternatively, switch to device flow if you're in a headless environment. ### Device flow code expires Device flow codes typically expire after a few minutes. If your code expires: 1. Run the command again to get a new code 2. Authenticate more quickly ### API key doesn't work Verify your API key is set correctly: ```bash echo $FLYTE_API_KEY ``` ## Best practices 1. **Local development**: Use PKCE authentication for the best experience 2. **Remote development**: Use device flow where supported; for newly provisioned organizations, use PKCE when a browser is available or an API key for headless environments 3. **Production/CI**: Always use API keys for automated environments 4. **API key security**: - Store in secret managers (GitHub Secrets, AWS Secrets Manager, Vault) - Never commit to version control - Rotate regularly - Use different keys per environment (dev, staging, prod) 5. **Config management**: Keep your `~/.flyte/config.yaml` in source control (without secrets) to maintain consistent settings across your team === PAGE: https://www.union.ai/docs/v2/union/user-guide/factories === Declare how artifacts are made from other artifacts, then ask for any artifact for a partition or a range and let Union build only what is missing or stale. # Factories > [!NOTE] Preview feature > Factories are in preview. We are actively working with customers to improve them, so if you want changes or improvements, talk to the Union team. > > Factories require `flyteplugins-union` 0.12.0 or later and flyte 2.10.0 or later: `pip install "flyteplugins-union>=0.12.0"`. Ending in an app and triggers require 0.15.0 or later. ## Why factories Three teams share one daily report. Ingest publishes `raw_events` every day for each region. The data team owns a `clean` task, the ML team owns `featurize`, which combines every region for a day, and the analytics team owns `report`, which reads the last three days of features. On September 1, a bug fix lands in `clean`, and someone asks for the August reports to be regenerated. Now you have to work out: * which days and regions of `raw_events` exist, * which `events` partitions need to be rebuilt with the fixed code, and which `features` and reports depend on them, * in what order to run 62 `clean` calls, 31 `featurize` calls, and 31 `report` calls, and * how to pick up where you left off when day 17 fails. **Triggers > Trigger on new artifact versions** don't help here. They push forward when a new version lands, but they can't answer "make the August reports exist." Usually someone ends up writing a one-off backfill script that knows the whole pipeline. A factory replaces that script with a declaration. You describe once how each artifact is made from the others. Then you ask for the artifact you want: ### Programmatic ```python run = analytics.materialize(daily_report, date="2026-08-01..2026-08-31") ``` ### CLI ```bash flyte factory materialize analytics daily_report --partition date=2026-08-01..2026-08-31 ``` Union works backwards from `daily_report`. It reuses every partition that is still fresh, builds the rest in dependency order and in parallel, and publishes each result as an artifact version. Run the same command again and nothing is rebuilt. If day 17 failed, only day 17 and what depends on it run. ## What a factory is A factory is a graph of [artifacts](../artifacts/_index). You ask it for data, and it works out which tasks to run. ```mermaid flowchart LR raw_events[("raw_events
date, region")] -- clean --> events[("events
date, region")] events -- "featurize (all regions)" --> features[("features
date")] features -- "report (last 3 days)" --> daily_report[("daily_report
date")] ``` It is made of three things: * **Sources.** Artifacts made outside the factory, such as `raw_events` above. The factory finds them in the registry. * **Builds.** One task call that makes one or more artifacts from other artifacts and constants. The tasks are ordinary deployed tasks. They take plain inputs and return plain outputs, and they don't know the factory exists. * **Materializations.** A request to make one artifact for a partition or a range. A materialization is a single run: every partition that needs building becomes a child action, and a partition whose inputs and code haven't changed is a cache hit. A factory can also end in a running app that serves what it built, and it can materialize itself when a source gets a new version or on a schedule. A factory is like a Makefile for data. A source is a file with no rule, a build is a rule, and materializing is `make `. "Is it up to date?" is answered by the task cache. ## How factories connect the platform Everything a factory produces is an ordinary, partitioned artifact version, published with the action that built it as its source. That makes the factory the piece that ties the rest of Union together: | Piece | Role | With a factory | |---|---|---| | [Tasks](../tasks/_index) | The work | Each build is a task you already have, owned by whichever team wrote it | | [Artifacts](../artifacts/_index) | Named, versioned, partitioned data | The nodes of the graph, and what you ask for | | [Triggers](../triggers/_index) | Push: react when new data lands | A factory **Factories > Trigger a factory** when a source changes or on a schedule, and downstream `OnArtifact` triggers fire on the versions it publishes | | [Apps](../apps/_index) | Serve models and data | A factory can **Factories > End in an app** and deploy it with the exact version it built | | **Artifacts > Automatic lineage tracking** | Where data came from | Every version points at the action that built it | Triggers push work forward when data arrives. Factories pull: they make sure the data you need exists for the partitions you ask for. A trigger on a factory combines the two: new data arrives, and the factory builds what depends on it. ## When to use one Use a factory when your data is partitioned, when it passes through tasks owned by different teams, or when you need to backfill or rebuild ranges. If one task calls a few others and you never ask for historical partitions, plain task calls are simpler. ### **Factories > Declare a factory** Describe how each artifact is made with sources and builds, map partitions between them, and name the outputs of multi-output tasks. ### **Factories > Materialize and backfill** Deploy a factory, then build one partition or a whole range, preview the plan, rebuild after a code change, and resume a failed backfill. ### **Factories > End in an app** Deploy an app with the exact model version a factory built, after checks and a person's approval, and roll it back by pinning a version. ### **Factories > Trigger a factory** Materialize automatically when a source gets a new version or on a schedule. ## Subpages - **Factories > Declare a factory** - Describe how each artifact is made with sources and builds, map partitions between them, and name the outputs of multi-output tasks. - **Factories > Materialize and backfill** - Deploy a factory, then build one partition or a whole range, preview the plan, rebuild after a code change, and resume a failed backfill. - **Factories > End in an app** - Deploy an app with the exact model version a factory built, after checks and a person's approval, and roll it back by pinning a version. - **Factories > Trigger a factory** - Materialize automatically when a source gets a new version or on a schedule. === PAGE: https://www.union.ai/docs/v2/union/user-guide/factories/declare-a-factory === Describe how each artifact is made with sources and builds, map partitions between them, and name the outputs of multi-output tasks. # Declare a factory > [!NOTE] Preview feature > Factories are in preview. If you want changes or improvements, talk to the Union team. This page builds the analytics factory from the [overview](./_index): `raw_events` is cleaned per day and region, combined across regions into `features`, and rolled into a report over a trailing three-day window. ## The tasks The tasks are ordinary. They take plain inputs, return plain outputs, and don't import the factory. Turn on caching, because the task cache is how a factory decides that a partition is still fresh: ```python from datetime import datetime import flyte from flyte.io import File env = flyte.TaskEnvironment(name="analytics_tasks") @env.task(cache="auto") async def clean(raw: File, date: datetime, region: str, min_quality: int = 30) -> File: ... @env.task(cache="auto") async def featurize(per_region: list[File], date: datetime) -> File: ... @env.task(cache="auto") async def report(week: list[File], date: datetime) -> File: ... ``` Deploy them as usual with `flyte deploy analytics.py env`. In practice they often live in other teams' repositories. ## The factory ```python from flyte.remote import Task from flyteplugins.union import factory clean_task = Task.get("analytics_tasks.clean", auto_version="latest") featurize_task = Task.get("analytics_tasks.featurize", auto_version="latest") report_task = Task.get("analytics_tasks.report", auto_version="latest") raw_events = factory.source("raw_events") events = factory.build("events").using(clean_task, raw=raw_events, min_quality=30) features = factory.build("features").using(featurize_task, per_region=events.all("region")) daily_report = factory.build("daily_report").using( report_task, week=features.window(date=factory.TimeRange(days=3)) ) analytics = factory.Factory("analytics", daily_report, description="Daily analytics report") ``` Nothing runs here. `source` and `build` only declare. * **`factory.source(name)`** is an artifact made outside the factory. Its type and partition keys come from the registry, so `raw_events` needs to have been **Artifacts > Partitioned artifacts** at least once, or declared with `Artifact.declare`. Pass `project=` and `domain=` to read a source from another project. * **`factory.build(name).using(task, **args)`** is one task call and the artifact it makes. `build(...)` says what is made, and `.using(...)` takes the task and its arguments, like `functools.partial`. * **Handles form the graph.** `.using(...)` returns a handle for the artifact it makes. Passing that handle into another build is what connects them. There is no separate step for adding edges. * **`factory.Factory(name, *targets)`** includes every build reachable by walking back from the artifacts you list. You can materialize any artifact in it, not only the ones listed. ### Tasks that ship with the factory `.using(...)` also takes a task object instead of a reference to a deployed task. `flyte factory deploy` then checks the arguments against the task's signature, deploys the task's environment, and pins the build to the version it deployed, so the factory and its tasks ship with one command: ```python from analytics_tasks import clean, featurize, report events = factory.build("events").using(clean, raw=raw_events, min_quality=30) ``` Keep such tasks in a module that doesn't import the factory. A task's pod imports the module the task is defined in, and the factory plugin isn't installed in the task's image. To check the definition without registering anything, validate it and print the graph as Mermaid: ### Programmatic ```python print(analytics.validate()) # structural problems, if any print(analytics.graph()) ``` ### CLI ```bash flyte factory deploy analytics.py --dry-run ``` ## Mapping partitions between artifacts A build's partitions follow from its inputs. Each argument that reads an artifact says which partitions of it a single call receives: | Written as | The task receives | Example | |---|---|---| | `events` | The same partition: one value | `events[2026-08-02, us]` for `events[2026-08-02, us]` | | `events.all("region")` | Every value of `region` for the same other keys: a `list` | All regions of `events` for 2026-08-02. The output loses `region` | | `features.window(date=factory.TimeRange(days=3))` | A trailing window ending at this partition: a `list` | `features` for 07-31, 08-01, and 08-02 | | `events.select(region="us")` | One pinned value, other keys matched: one value | Only the US `events` for each date. The output loses `region` | So `events` is partitioned by `date` and `region` like `raw_events`. `features` is partitioned by `date` alone, because it reads every region, and `daily_report` keeps `date`. ### Passing partition values to a task A task parameter named like a partition key receives that key's value for the partition being built. That's why `clean` gets `date` and `region` without either being written in `.using(...)`. A time partition arrives as a `datetime`. If the parameter has a different name, bind it with `factory.partition`: ```python factory.build("events").using(clean_task, raw=raw_events, day=factory.partition("date")) ``` ### A build that adds a partition When a build reads no artifacts, or its output has a key that no input carries, state its partitions: ```python raw_rows = factory.build("raw_rows", partitions={"date": factory.Daily}).using( pull_task, day=factory.partition("date"), source_url="https://example.com/rows" ) ``` Time keys use `factory.Hourly`, `factory.Daily`, `factory.Weekly`, or `factory.Monthly`. String keys use `str` or `int`. ## Tasks with several outputs The names given to `build` line up with the task's return tuple, left to right. Use `"_"` for an output that is not an artifact: ```python # split returns (File, File): both are artifacts, made by one call. clean_rows, rejects = factory.build("clean_rows", "rejects").using(split_task, raw=raw_rows) # train returns (log, model, metrics, debug): only the middle two are artifacts. model, metrics = factory.build("_", "model", "metrics", "_").using(train_task, rows=clean_rows) ``` The list must be as long as the return tuple, so deploy fails rather than guessing which output you meant. Asking for one output of a build builds all of them. The same task can back several builds with different constants, because builds are identified by what they make. ## Build options `factory.build(...)` also takes: * `kind`: the artifact kind, `"model"`, `"data"`, or `"generic"`, or a mapping of artifact name to kind for a multi-output build. * `runcontext`: settings for this build's task call. The supported keys are `queue`, `env_vars`, and `service_account`. * `description`: shown with the artifact. Next, **Factories > Materialize and backfill**. A factory can also **Factories > End in an app**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/factories/materialize === Deploy a factory, then build one partition or a whole range, preview the plan, rebuild after a code change, and resume a failed backfill. # Materialize and backfill > [!NOTE] Preview feature > Factories are in preview. If you want changes or improvements, talk to the Union team. Once a factory is **Factories > Declare a factory**, there is one verb for running it: **materialize**. You name an artifact and a partition or a range, and the factory builds whatever is needed to produce it. ## Deploy Deploy the tasks, then the factory: ### Programmatic ```python import flyte flyte.init_from_config() flyte.deploy(env) # the tasks analytics.deploy() # the factory ``` ### CLI ```bash flyte deploy analytics.py env flyte factory deploy analytics.py ``` If the factory is given **Factories > Declare a factory > The factory > Tasks that ship with the factory**, `flyte factory deploy` deploys their environments too, and `flyte deploy` isn't needed. `flyte factory deploy` checks every build against its deployed task, including argument names, required parameters, partition mappings, and the number of outputs. It checks every source against the registry, then registers the factory as a task of type `factory`. Mistakes fail here, with a message per build, instead of halfway through a backfill. Add `--dry-run` (or `analytics.deploy(dryrun=True)`) to validate without registering. ## One partition ### Programmatic ```python run = analytics.materialize(daily_report, date="2026-08-02") run.wait() ``` ### CLI ```bash flyte factory materialize analytics daily_report --partition date=2026-08-02 --wait ``` The factory walks back from `daily_report[2026-08-02]`. That partition needs `features` for three days, each of which needs `events` for every region, each of which needs `raw_events`. The whole materialization is one run, and each partition built along the way is a child action you can open in the UI. In Python, `materialize` returns an ordinary `flyte.remote.Run`. ## A range: backfill A backfill is the same command over a range: ### Programmatic ```python run = analytics.materialize(daily_report, date="2026-08-01..2026-08-31") ``` ### CLI ```bash flyte factory materialize analytics daily_report --partition date=2026-08-01..2026-08-31 ``` `a..b` is an inclusive range, expanded at the partition's granularity, and `a,b` lists values. The range crosses with the other keys, so this builds `events` for every region on every day that a report needs. Partitions build in parallel. Ordering follows the graph, not the calendar: the report for August 31 waits only on its own three-day window. * **Rerunning resumes.** Run the same command again. Everything already built is a cache hit, so only the failed partitions and what depends on them run. There is no separate backfill object or resume command. * **Failures are partial.** Partitions that succeeded are published and usable. A failed partition blocks only what depends on it, and the run fails naming them. * **A missing source blocks only its dependents.** If `raw_events` has no version for one day, the rest of the range still builds. ## Preview the plan ### Programmatic ```python run = analytics.materialize(daily_report, date="2026-08-01..2026-08-31", plan_only=True) run.wait() ``` ### CLI ```bash flyte factory plan analytics daily_report --partition date=2026-08-01..2026-08-31 ``` `plan` is short for `materialize --plan --wait`. It launches nothing and prints, per artifact, how many partitions are in each state: | State | Meaning | |---|---| | `source` | A source partition found in the registry | | `missing` | A source partition that doesn't exist, or a build partition with no published version yet | | `existing` | A published version exists. The cache decides at run time whether it is reused | | `reused` | During a run: a cache hit, nothing rebuilt | | `built` | During a run: the task ran and a new version was published | | `failed` / `blocked` | The task failed, or something upstream of it did | ## Freshness is the task cache A partition is fresh if calling its task with the same inputs is a cache hit. That means the same task version, the same upstream artifact versions, the same partition values, and the same constants. So there's nothing to configure: * **A code change** to `clean` changes its cache version, so `events` and everything downstream rebuild. * **A new upstream version**, such as a corrected `raw_events` for one day, changes the inputs for that day only. * **A task without caching** rebuilds every time. Use `cache="auto"` on factory tasks. To force work anyway: ### Programmatic ```python # Treat every partition of one build as stale. analytics.materialize(daily_report, date="2026-08-01..2026-08-31", rebuild=["events"]) # Ignore the cache everywhere. analytics.materialize(daily_report, date="2026-08-01..2026-08-31", rebuild_all=True) ``` ### CLI ```bash # Treat every partition of one build as stale. flyte factory materialize analytics daily_report --partition date=2026-08-01..2026-08-31 --rebuild events # Ignore the cache everywhere. flyte factory materialize analytics daily_report --partition date=2026-08-01..2026-08-31 --rebuild-all ``` `--rebuild` names a build by an artifact it makes, since the same task can back several builds. A task name also works. ## Other options | Python | CLI | Effect | |---|---|---| | `params={"events": {"min_quality": 20}}` | `--param events.min_quality=20` | Override a build's constant for this materialization only | | `concurrency=50` | `--concurrency 50` | Limit how many partitions build at once | | `queue="gpu"` | `--queue gpu` | Run the materialization and every build on this queue | | `downstream=True` | `--downstream` | Also refresh downstream partitions that become stale | | `versions={"events": ""}` | `--version events=` | Read that version of an artifact instead of building it, and skip what only it needed. This is how you **Factories > End in an app > One app, one partition** | | `run.wait()` | `--wait` | Wait for the run to finish. The CLI also prints the plan with results | ## What gets published Every artifact built during a materialization is published as a version with its partition values, not only the target you asked for. Each version's source is the action that ran the task, so **Artifacts > Automatic lineage tracking** points at the work that made it. From there the results behave like any other artifact: **Artifacts > Find and retrieve artifacts** by partition, **Triggers > Trigger on partitions**, or mount them in an **Artifacts > Use artifacts in apps**. ## Inspect factories ### Programmatic ```python print(analytics.graph()) # the definition, as Mermaid print(analytics.validate()) # structural problems, if any ``` ### CLI ```bash flyte factory get # factories in this project and domain flyte factory get analytics --graph # one factory's definition, as Mermaid ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/factories/serve === Deploy an app with the exact model version a factory built, after checks and a person's approval, and roll it back by pinning a version. # End in an app > [!NOTE] Preview feature > Factories are in preview. If you want changes or improvements, talk to the Union team. > > Serving from a factory requires `flyteplugins-union` 0.15.0 or later. A factory can end in a running [app](../apps/_index). Its target is then an **endpoint** rather than an artifact: materializing it builds and checks the model, then deploys the app serving that exact version. Add one with `factory.serve`: ```python approved = factory.build("beans_approved", kind="model").using(gate, model=model, report=metrics) api = factory.serve("beans-api").using(serving, model=approved) # serving is an AppEnvironment beans = factory.Factory("beans", api) ``` ```bash flyte factory materialize beans beans-api ``` The rest of this page covers the details: binding app parameters, what deploy and materialize do, gates and approvals, partitioned endpoints and rollback, and sharded models. ## Serve a model `factory.serve(name).using(app, **params)` works like `factory.build(...).using(task, **args)`. The name is the app's name, and each keyword binds one of the app's **Apps > Configure apps > Passing parameters into app environments** to an artifact: ```python from flyteplugins.union import factory from beans_app import serving # a FastAPIAppEnvironment named "beans-api" from beans_tasks import finetune, gate, prepare dataset = factory.build("beans_dataset").using(prepare, dataset="AI-Lab-Makerere/beans") model, metrics = factory.build("beans_classifier", "beans_metrics", kind={"beans_classifier": "model"}).using( finetune, data=dataset, epochs=2 ) approved = factory.build("beans_approved", kind="model").using(gate, model=model, report=metrics, min_accuracy=0.9) api = factory.serve("beans-api").using(serving, model=approved) beans = factory.Factory("beans", api) ``` The app is an ordinary app environment. Its parameter names the artifact it serves, and the factory binds it to one version at a time: ```python serving = FastAPIAppEnvironment( name="beans-api", app=app, image=flyte.Image.from_debian_base(name="beans-api").with_pip_packages("fastapi", "uvicorn", "transformers", "torch"), parameters=[ Parameter(name="model", value=flyte.app.ArtifactValue(name="beans_approved", type="directory"), mount="/tmp/model"), ], ) ``` `serve` returns an endpoint. You can materialize it and list it in `Factory(...)`, but no build can read it. Each parameter takes one artifact that holds a `flyte.io.File` or `flyte.io.Dir`. ## Deploy and materialize ```bash flyte factory deploy beans.py flyte factory materialize beans beans-api --wait ``` At deploy, the factory builds the app's image and code bundle and records the app definition. When you materialize the endpoint, the factory builds whatever is stale, then deploys the app with each parameter set to the artifact version it resolved. The factory task deploys the app itself, so no extra pod starts. The version is recorded as the app's input, so the artifact's page lists the app that serves it. Run it again and every build is a cache hit. The app's definition is unchanged, so it is left alone. ## Check before it goes live A gate is a build that returns its input or fails. When it fails, nothing after it is built and the app keeps serving the model it had: ```python @env.task(cache="auto") async def gate(model: Dir, report: File, min_accuracy: float = 0.9) -> Dir: async with report.open("rb") as fh: accuracy = json.loads(bytes(await fh.read()))["accuracy"] if accuracy < min_accuracy: raise flyte.errors.RuntimeUserError("BelowBar", f"accuracy {accuracy:.3f} is below {min_accuracy}") return model ``` To have a person approve a release, add a gate that waits on an **Tasks > Build tasks > External conditions**: ```python @env.task(cache="auto") async def release(model: Dir, report: File) -> Dir: decision = await flyte.new_condition.aio( "release-beans-classifier", prompt="**Release the new beans classifier?**", prompt_type="markdown", data_type=bool, timeout=datetime.timedelta(hours=24), ) if not await decision.wait.aio(): raise flyte.errors.RuntimeUserError("Rejected", "a reviewer rejected this model") return model released = factory.build("beans_released", kind="model").using(release, model=approved, report=metrics) api = factory.serve("beans-api").using(serving, model=released) ``` While it waits, the factory's materialization page shows a bar above the graph with the prompt and a **Review** button. You can also answer from the run page, or with `flyte signal condition true`. An approval is cached like any build, so a later materialization of the same model doesn't ask again. A rejection isn't cached, so the next materialization asks again. ## One app, one partition An endpoint is one app, so it serves one partition at a time. It can have at most one partition key, and it must be a time. For example, a model retrained each day: * **A range deploys the newest partition.** Materializing `--partition date=2026-09-01..2026-09-07` builds and deploys the September 7 model, and skips the older days' builds, since nothing would serve them. * **A newer model is never replaced by an older one.** If the app already serves September 7, a backfill or a late-arriving September 3 builds that day's model but leaves the app alone. * **Roll back by pinning.** `--version` reads a version instead of building it, and deploys it even when it is older: ```bash flyte factory materialize beans beans-api --version beans_released= --wait ``` ## Sharded models A model imported with **Inference > Prefetching models** and sharded for tensor parallelism can only be loaded with the GPU count and engine it was sharded for. The factory reads both from the artifact and refuses to deploy an app that asks for a different number of GPUs or runs a different engine. ## Examples The `flyteplugins-union` repository has runnable examples in `examples/factory/`: * `gates/`: two approvals and an automatic check between raw data and a small API. Each step runs in seconds. * `beans/`: data preparation, fine-tuning, an accuracy gate, an approval, daily batch scoring, and a FastAPI app. * `hf_model.py`: import a Hugging Face model, check it, and serve it with vLLM. Next, **Factories > Trigger a factory** to keep the app up to date. === PAGE: https://www.union.ai/docs/v2/union/user-guide/factories/triggers === Materialize automatically when a source gets a new version or on a schedule. # Trigger a factory > [!NOTE] Preview feature > Factories are in preview. If you want changes or improvements, talk to the Union team. > > Triggers on factories require `flyteplugins-union` 0.15.0 or later. A factory can materialize itself. A trigger starts a materialization when a source gets a new version, or on a schedule. Add triggers with `factory.on` and pass them to the factory: ```python sensors = factory.Factory( "sensors", daily, triggers=[ factory.on(readings), # each new version of the readings source factory.on(flyte.Cron("0 1 * * *"), daily), # every night at 01:00 ], ) ``` Each trigger starts an ordinary materialization, and a partition that is already up to date is a cache hit. The rest of this page covers the details: which partitions a source event or a schedule materializes, filters, lags and timezones, names, and limits. ## Declare triggers `factory.on(event, *targets)` takes a source handle, a `flyte.Cron`, or a `flyte.FixedRate`, and optionally the artifacts to materialize. Every form, on one graph: ```python import flyte from flyteplugins.union import factory readings = factory.source("readings", type=flyte.io.File, partitions={"date": factory.Daily, "site": str}) summary = factory.build("summary").using(summarize, readings=readings) daily = factory.build("rollup").using(rollup, summaries=summary.all("site")) sensors = factory.Factory( "sensors", daily, triggers=[ factory.on(readings), factory.on(readings, summary, site="north", name="north-only"), factory.on(flyte.FixedRate(60), name="hourly"), factory.on(flyte.Cron("0 1 * * *"), daily, lag=factory.TimeRange(days=1), name="yesterday"), ], ) ``` `flyte factory deploy` registers the triggers with the factory. A triggered materialization is an ordinary run, listed on the factory's **Materializations** tab. Its **Triggers** tab lists the factory's triggers. When nothing has changed, every build is a cache hit, so a trigger that fires often costs little. ## When a source gets a new version `factory.on(source)` fires when a new version of that source is published. It materializes the partition the new version belongs to: * **The partition comes from the event.** When `readings[2026-09-28, north]` is published, `rollup` is materialized for 2026-09-28. On a key the source doesn't carry, the target is materialized for every value the registry knows. * **Targets default to what the factory produces downstream of the source.** Name targets to narrow it, as `north-only` does with `summary`. A target doesn't have to be one of the artifacts listed in `Factory(...)`. * **Filter by partition** with keyword arguments: `site="north"` fires only for versions whose `site` is `north`. Filters match string keys. `name` and `lag` are the function's own arguments, so a key with either name can't be filtered on. Only a source can fire a trigger. To act on each new version of something the factory builds, add a build that reads it: materializing the new build builds what it reads first. ## On a schedule `factory.on(flyte.Cron(...))` and `factory.on(flyte.FixedRate(...))` fire on a schedule, and targets default to everything the factory produces: * **The partition is the fire time**, rounded down to the target's granularity. A daily target that fires at 14:00 builds that day. * **`lag=` moves it back.** `yesterday` fires at 01:00 and builds the previous day, when that day's data is complete. * **The day is named in the schedule's timezone.** `flyte.Cron("0 22 * * *", timezone="America/Los_Angeles")` builds that day in Los Angeles, not the next day in UTC. A schedule that fires every hour on a factory whose inputs rarely change is a cheap way to keep it fresh: most runs are all cache hits and finish in seconds. ## Names and inputs Each trigger has a name. It defaults to one derived from the event, such as `on-readings` or `every-60m`. Pass `name=` to choose one, using lowercase letters, digits, and `-`. A trigger with several targets registers one trigger per target, named `-`. A factory with triggers gets a few extra inputs that the triggers fill in: `trigger`, `at`, and one `at_` for each partition key a source event carries. You don't set them yourself. A factory without triggers keeps its original inputs. ## Limits * A source must be in the factory's project and domain to fire a trigger. * One source event starts one run per target. A trigger with many targets starts that many runs, and they share cache hits for what they have in common. === PAGE: https://www.union.ai/docs/v2/union/user-guide/user-management === Manage users, roles, and policies for your Union cluster. # User management Union includes role-based access control (RBAC) for managing user and application permissions. The system has four core concepts: * **Role**: A named set of actions (e.g. view inventory, create executions). * **Policy**: Binds one or more roles to specific projects, domains, or the entire organization. * **User / Application**: An actor assigned to policies. Users are identified by email; applications by ID. * **Action**: An operation like `view_flyte_inventory`, `create_flyte_executions` or `register_flyte_inventory`. See **User management > Available actions**. ## Built-in policies Union ships with three built-in policies: | Policy | Actions | Summary | |---|---|---| | **Admin** | All actions | Full control including user management and billing | | **Contributor** | `create_flyte_executions`, `register_flyte_inventory`, `view_flyte_executions`, `view_flyte_inventory`, `edit_execution_related_attributes`, `edit_cluster_related_attributes`, `view_llm_gateway`, `manage_llm_gateway_keys`, `view_secrets`, `manage_secrets`, `view_apps`, `manage_apps`, `view_triggers`, `manage_triggers`, `view_workspaces`, `manage_workspaces`, `view_artifacts`, `manage_artifacts`, `view_settings`, `edit_settings`, `manage_api_keys`, `view_clusters`, `view_usage`, `view_identities` | Register and run workflows | | **Viewer** | `view_flyte_executions`, `view_flyte_inventory`, `view_llm_gateway`, `view_apps`, `view_triggers`, `view_workspaces`, `view_artifacts`, `view_settings`, `view_clusters`, `view_usage`, `view_identities` | Read-only access | Built-in policies are managed by Union. Custom roles only hold the actions you give them. Users can hold multiple policies: permissions are the union of all assigned policies. ## Custom roles and policies For fine-grained control, create custom roles and policies using the CLI or programmatically. ### Prerequisites Install the Union CLI plugin: ```bash pip install 'flyteplugins-union>=0.20.2' ``` This adds `role`, `policy`, `assignment`, `user`, and `member` subcommands to the `flyte` CLI. > [!WARNING] > Use `flyteplugins-union` 0.20.2 or later. > With `flyte` 2.12.2 or later, earlier versions fail to import and the `flyte` CLI drops their subcommands. > Versions before 0.20.1 also don't support the actions listed after the table in **User management > Available actions** (all except `view_identities`), which the built-in policies hold. > On a role that holds one, `Role.actions` and `flyte update role` fail, > and `Role.update` silently removes those actions. ### Walkthrough: restrict a team to run workflows in production only The goal: create a role that can view and execute workflows but not register new ones, bind it to the production domain of a specific project, and assign it to a user. ### Programmatic ```python from flyteplugins.union.remote import Role, Policy, Assignment # Step 1 โ€” Create the role Role.create( "Production Runner", description="Can view and execute workflows", actions=[ "view_flyte_inventory", "view_flyte_executions", "create_flyte_executions", ], ) # Step 2 โ€” Create the policy Policy.create( "Team Prod Access", description="Production execution access for the team", bindings=[ { "role": "Production Runner", "resource": { "project": "my-project", "domain": "production", }, }, ], ) # Step 3 โ€” Assign the policy to a user Assignment.create(email="jane@example.com", policy="Team Prod Access") ``` ### CLI **Step 1: Create the role** Use `--edit` to open an interactive editor (no YAML file needed): ```bash flyte create role "Production Runner" --edit ``` Your `$EDITOR` opens with a template. Set the actions: ```yaml name: Production Runner description: Can view and execute workflows actions: - view_flyte_inventory - view_flyte_executions - create_flyte_executions ``` Save and close. The role is created. **Step 2: Create the policy** ```bash flyte create policy "Team Prod Access" --edit ``` Bind the role to a specific project and domain: ```yaml name: Team Prod Access description: Production execution access for the team bindings: - role: Production Runner resource: project: my-project domain: production ``` **Step 3: Assign the policy to a user** ```bash flyte create assignment --email jane@example.com --policy "Team Prod Access" ``` You can also assign by user subject or application credentials subject: ```bash flyte create assignment --user-subject user-123 --policy "Team Prod Access" flyte create assignment --creds-subject app-456 --policy "Team Prod Access" ``` ### Updating roles and policies ### Programmatic ```python from flyteplugins.union.remote import Role, Policy # Add an action to an existing role Role.update( "Production Runner", actions=[ "view_flyte_inventory", "view_flyte_executions", "create_flyte_executions", "register_flyte_inventory", # newly added ], ) # Update policy bindings policy = Policy.get("Team Prod Access") new_bindings = policy.bindings + [ { "role": "Production Runner", "resource": {"project": "my-project", "domain": "staging"}, }, ] Policy.update("Team Prod Access", old_bindings=policy.bindings, new_bindings=new_bindings) ``` ### CLI `update` opens the existing definition in your editor so you can modify it in place: ```bash flyte update role "Production Runner" flyte update policy "Team Prod Access" ``` ## Managing users in the UI Navigate to **Settings > User Management** to: * **View users**: see all users and their assigned policies. * **Add a user**: specify name, email, and policies. The user receives an email invite. * **Change policies**: select a user and edit their assignments. * **Remove a user**: select a user and remove them. ## Available actions | Action | Description | |---|---| | `administer_project` | Archive/update projects, manage customizable resources | | `manage_permissions` | View and edit roles and policies, and manage users, applications, and policy assignments | | `create_flyte_executions` | Launch runs and upload inputs | | `register_flyte_inventory` | Register and deploy workflows, tasks, and launch plans | | `view_flyte_executions` | View runs and actions | | `view_flyte_inventory` | View registered workflows, tasks, and launch plans | | `administer_account` | Manage billing and account-wide settings | | `manage_cluster` | Manage clusters | | `manage_queue` | Manage cluster queues | | `view_cluster_config` | View the component configuration of a cluster | | `edit_execution_related_attributes` | Edit execution-related attributes (task resources, workflow execution config, external resources) | | `edit_cluster_related_attributes` | Edit cluster-related attributes (cluster resources, cluster assignment) | | `edit_unused_attributes` | Edit execution queue, execution cluster label, quality of service, and plugin override attributes | | `support_system_logs` | View system logs | | `view_llm_gateway` | View the inference gateway, its providers, guardrails, and virtual keys (without their values) | | `manage_llm_gateway` | Deploy and delete the inference gateway, and manage its upstream providers and guardrails | | `manage_llm_gateway_keys` | Issue, revoke, and view inference gateway virtual keys, and view inference gateway usage | Roles also accept the following actions, but no Union service checks them, so granting one has no effect: `view_secrets`, `manage_secrets`, `view_apps`, `manage_apps`, `view_triggers`, `manage_triggers`, `view_workspaces`, `manage_workspaces`, `view_artifacts`, `manage_artifacts`, `view_settings`, `edit_settings`, `manage_api_keys`, `view_clusters`, `view_permissions`, `view_usage`, `view_identities`. A role that holds `create_flyte_executions` can list, get, create, update, and delete secrets at the scope it's bound to. Viewing triggers requires `view_flyte_inventory`. Creating, activating, deactivating, and deleting triggers requires `register_flyte_inventory`. ## CLI command reference | Command | Description | |---|---| | `flyte create role --edit \| --file ` | Create a role interactively or from YAML | | `flyte get role []` | List all roles or view a specific one | | `flyte update role ` | Edit a role in `$EDITOR` | | `flyte delete role ` | Delete a role | | `flyte create policy --edit \| --file ` | Create a policy interactively or from YAML | | `flyte get policy []` | List all policies or view a specific one | | `flyte update policy ` | Edit a policy in `$EDITOR` | | `flyte delete policy ` | Delete a policy | | `flyte create assignment --email \| --user-subject \| --creds-subject --policy ` | Assign a policy to a user or application | | `flyte get assignment [--user-subject \| --creds-subject ]` | View the policies assigned to a user or application | | `flyte delete assignment --user-subject \| --creds-subject --policy ` | Unassign a policy from a user or application | | `flyte get user []` | List all users or view a specific one | | `flyte delete user ` | Delete a user | | `flyte get member` | List all members (users and applications) | === PAGE: https://www.union.ai/docs/v2/union/user-guide/clusters-and-queues === Group clusters into pools, register clusters, and create queues that route and rate-limit your workloads. # Clusters and queues > [!NOTE] Requires the `flyteplugins-union` plugin > The `flyte` cluster, pool, queue, and node-groups commands and the Python objects on these > pages are provided by the `flyteplugins-union` package. Install it with > `pip install flyteplugins-union`. The node-groups commands need version 0.20.2 or later. As a Union.ai deployment grows past a single cluster, you need to control *where* a workload runs and *under what limits*. Three primitives do this: - **Cluster pool**: an isolation boundary. The clusters and queues inside a pool share one **data plane configuration**: the same object store, secret store, and container registry. Work cannot cross from one pool to another (see **Clusters and queues > How they fit together > Crossing a pool boundary**). - **Cluster**: an execution cluster that lives in exactly one pool. - **Queue**: what you submit work to. A queue lives in one pool, **routes** work to one or more clusters in that pool, and applies the concurrency, depth, and priority limits for the work it admits. A queue can also cap the CPU, memory, and GPUs its scheduled work uses, which is how teams share clusters without one team taking all of the capacity (see **Clusters and queues > Resource caps and scheduling**). Every cluster automatically gets a **co-named queue** that routes only to it, so any cluster can be targeted by name without creating anything (see **Clusters and queues > Managing queues > How a queue routes > Queues you get for free**). ## Tooling Pools, clusters, and queues are managed with the `flyte` CLI or the `flyteplugins.union.remote` Python objects, and are set up by your platform administrator. These are administrative tasks; most workflow authors only need **Tasks > Configure tasks > Queues**. ## Standing up a self-managed cluster? The pages here manage the **control-plane records** for pools, clusters, and queues. They do not provision the **data plane** itself: the cloud resources (object store, secret store, registry) and the install of the data plane on the cluster (by the agent from the Union.ai UI, or by a Helm release you run). If you run a self-managed deployment, provision the data plane first with [Self-managed deployment](../../deployment/selfmanaged/_index) (for example, [Provision your AWS resources](../../deployment/selfmanaged/aws/_index)), then use the commands here to add or change the pool, cluster, and queue records that route work to it. ## How they fit together ```mermaid flowchart TD Org["Organization"] Org --> PD Org --> PP subgraph PD["Cluster pool: default"] direction TB QD["Queue: default
selector: *"] CA["Cluster A"] CB["Cluster B"] QD --> CA QD --> CB end subgraph PP["Cluster pool: prod"] direction TB QP["Queue: prod-queue
selector: [Cluster C, Cluster D]"] QG["Queue: gpu-queue
selector: [Cluster C]"] CC["Cluster C"] CD["Cluster D"] QP --> CC QP --> CD QG --> CC end ``` A **cluster pool** is an isolation boundary: both **clusters** and **queues** live *inside* a pool, and everything in it shares one data plane. A **queue** routes work to one or more clusters **in its own pool**, and the three queues above show the routing choices you have: - **`default`** uses the wildcard selector `*`: it spreads across every cluster in its pool that is healthy and `active`, and picks up new clusters automatically as they join. An unhealthy cluster stops receiving new work until it recovers โ€” see **Clusters and queues > Managing queues > How a queue routes**. - **`prod-queue`** names both clusters in its pool explicitly. The result looks like the wildcard today, but the membership is frozen: a *Cluster E* added to `prod` later gets no work from this queue until you add it to the selector. - **`gpu-queue`** names a single cluster, pinning that lane to Cluster C while Cluster D stays free for other work. The key invariant: a queue can never reach a cluster outside its pool, because a run's inputs, code, and secrets are uploaded to that pool's data plane and no other pool's clusters can read them. That is what makes a pool an isolation boundary. ### Crossing a pool boundary Each pool has a separate data plane. A running workload cannot move between pools because clusters in the destination pool cannot access the source pool's data, images, code, or secrets. A **queue** can move to another pool only after it is fully **Clusters and queues > Managing queues > Drain and reactivate a queue**. A **cluster** can move only once its co-named queue is drained, which **Clusters and queues > Clusters > Drain and reactivate a cluster** takes care of. These requirements keep in-flight work from crossing the boundary. To route a workload through another pool, make its dependencies available in the destination data plane. Then move its drained queue or follow a **Clusters and queues > Managing queues > Move work to another pool**. > [!NOTE] The simple case is invisible > Each cluster is assigned exactly one pool. If no custom pool is specified when > the cluster is created, it joins the `default` pool. No organization starts with > one: if Union.ai set up your organization, `default` is created when its first > cluster is registered; if you created your organization yourself by > [signing up](../../deployment/sign-up/_index), you > **Self-managed deployment > Connect your cluster** before you > register your first cluster. So if you run a single cluster, or several > clusters that share one bucket, secret store, and registry, you don't need to > think about pools once `default` exists: your cluster lands in `default`, > queues route to `default`, and you can skip straight > to **Clusters and queues > Managing queues**. Pools only matter once you have clusters with **distinct** > data planes (for example, separate dev and prod cloud accounts). ## In this section ### **Clusters and queues > Cluster pools** Group clusters that share a data plane. Create and manage pools, or stay on the `default` pool if you only have one. ### **Clusters and queues > Clusters** Register execution clusters into a pool and inspect their state, capacity, and bound queues. ### **Clusters and queues > Managing queues** Create and manage the scheduling lanes that route workloads to a pool and enforce concurrency, resource caps, and priority. ### **Clusters and queues > Resource caps and scheduling** Share clusters across teams with per-queue CPU, memory, and GPU caps, and choose how a queue schedules work when capacity is tight. ### **Clusters and queues > Node groups** Inspect and update the node groups a cluster declares, the node shapes it can schedule onto. ## Subpages - **Clusters and queues > Cluster pools** - Group clusters that share a data plane. Create and manage pools, or stay on the `default` pool if you only have one. - **Clusters and queues > Clusters** - Register execution clusters into a pool and inspect their state, capacity, and bound queues. - **Clusters and queues > Managing queues** - Create and manage the scheduling lanes that route workloads to a pool and enforce concurrency, resource caps, and priority. - **Clusters and queues > Resource caps and scheduling** - Share clusters across teams with per-queue CPU, memory, and GPU caps, and choose how a queue schedules work when capacity is tight. - **Clusters and queues > Node groups** - Inspect and update the node groups a cluster declares, the node shapes it can schedule onto. === PAGE: https://www.union.ai/docs/v2/union/user-guide/clusters-and-queues/cluster-pools === Group clusters that share a data plane. Create and manage pools, or stay on the `default` pool if you only have one. # Cluster pools > [!NOTE] Requires the `flyteplugins-union` plugin > The cluster-pool CLI commands and Python objects on this page are provided by > the `flyteplugins-union` package. Install it with > `pip install flyteplugins-union`. A **cluster pool** is a named group of clusters that share one **data plane configuration**: the same object store, secret store, and container registry. Because every cluster in a pool reads and writes the same data plane, a workload can run on any healthy cluster in the pool and still find its inputs, code, and secrets. ## When you need more than one pool Most deployments need exactly one pool. Each cluster is assigned exactly one pool, and if no custom pool is specified when the cluster is created, it joins the `default` pool. No organization starts with one; see [Clusters and queues](./_index) for how `default` comes to exist. If your clusters share a bucket, secret store, and registry, leave them in `default` and move on to **Clusters and queues > Clusters**. Create additional pools when you have clusters with **distinct** data planes: for example, separate development and production cloud accounts, each with its own bucket, secrets vault, and registry. Each such environment becomes its own pool. ## Run on a queue in another pool A run's data must be in the object store of the pool its queue belongs to. Name the queue when you submit the run, and the SDK uploads the run's code bundle and inputs to that queue's pool, and places any remote image build the run needs on that queue: ```bash flyte run --queue hello.py main ``` `flyte.with_runcontext(queue=...)` does the same from Python. Without an explicit queue, the task's own queue is used. Requires `flyte` 2.12.2 or later, and a control plane that routes uploads by queue. Otherwise the code bundle and inputs go to the project/domain default pool. For deployed tasks, `flyte deploy --queue ` (or `flyte.deploy(..., queue=...)`) uploads the code bundle and trigger inputs to that queue's pool, under the same conditions. A run can be rejected at submission when its data is in a different pool's object store than its queue: - Its inputs were uploaded to another pool. - Its task was deployed to the project/domain's default pool, and the run is on a queue in another pool. Runs fired by triggers aren't checked; they fail in the task pod instead. Each rejection's error names the two fixes that apply: - **Inputs in another pool:** submit the run with `--queue ` (`flyte` 2.12.2 or later) so its inputs are uploaded to that queue's pool, or run it on a queue in the pool that holds its inputs. - **Task deployed to the default pool:** run it on a queue in the default pool, or redeploy the task with `--queue ` (`flyte` 2.12.2 or later). ## Create a pool A pool's config is the data plane contract its member clusters must satisfy: object store, secret store, and image registry. The object store URI and secret store type are required here; the image registry is optional to set, but member clusters are still expected to match it โ€” see **Clusters and queues > Cluster pools > How a pool's config is enforced** for how that contract works. ### CLI Create one interactively with an editor, or from a file: ```bash # Open an editor pre-filled with a template flyte create cluster-pool prod --edit # ...or create from a manifest you've prepared flyte create cluster-pool prod --file prod-pool.yaml ``` The manifest declares the shared data plane contract: ```yaml name: prod config: object_store_ref: uri: s3://my-prod-bucket/prefix endpoint: "" secret_store: type: AWS_SECRETS_MANAGER locator: us-east-1 image_registry: locator: 123456789012.dkr.ecr.us-east-1.amazonaws.com/union ``` ### Programmatic ```python from flyteplugins.union.remote import ClusterPool ClusterPool.create( "prod", object_store_uri="s3://my-prod-bucket/prefix", secret_store_type="AWS_SECRETS_MANAGER", secret_store_locator="us-east-1", image_registry="123456789012.dkr.ecr.us-east-1.amazonaws.com/union", ) ``` Supported `secret_store_type` values are `AWS_SECRETS_MANAGER`, `GCP_SECRET_MANAGER`, `AZURE_KEY_VAULT`, `KUBERNETES`, `VAULT`, and `OCI_VAULT`. ## How a pool's config is enforced Pool config is **not** enforced at join time. Any cluster is allowed to join a pool, and the check happens asynchronously afterwards: 1. A cluster joins the pool when its cluster record is created (see **Clusters and queues > Cluster pools > Manage membership**). The control plane accepts the membership without inspecting the cluster's actual data plane. 2. Once running, the cluster reports its real object store, secret store, and image registry to the control plane in periodic status updates. 3. The control plane compares each reported value against the pool's config. If they don't match, it records the mismatch as a `cluster_pool_config` entry, with health `UNHEALTHY`, in the cluster's monitoring info. The cluster's overall health and unhealthy reasons do not change, so every queue that **Clusters and queues > Managing queues > How a queue routes** to the cluster keeps sending it new work. A misconfigured cluster is accepted at join time and keeps receiving work. After registering a cluster into a custom pool, check `Cluster.get("").monitoring_info` for a `cluster_pool_config` entry. The console shows it on the cluster's page under **Cluster Pool Config**; `flyte get cluster ` does not show monitoring info. Note that while the image registry is optional to *set*, it is still part of the contract: a member cluster must report the same registry the pool declares to avoid a mismatch. If the pool declares none, it adopts the first registry a member reports, and later members are checked against that. ## Inspect pools ### CLI ```bash # List all pools flyte get cluster-pool # Inspect a specific pool โ€” its config and member clusters flyte get cluster-pool prod ``` ### Programmatic ```python from flyteplugins.union.remote import ClusterPool for pool in ClusterPool.listall(limit=100): print(pool.name, pool.member_clusters, pool.object_store_uri, pool.secret_store_type) pool = ClusterPool.get("prod") print(pool.name) print(pool.member_clusters) print(pool.object_store_uri) print(pool.secret_store_type) print(pool.image_registry) ``` `member_clusters` is derived from clusters that were registered into the pool. Assign clusters when you register them; see **Clusters and queues > Clusters**. ## Update a pool `flyte update cluster-pool` opens the pool in your `$EDITOR` as the same YAML manifest used to create it. Save and close to apply. ### CLI ```bash flyte update cluster-pool prod ``` ### Programmatic ```python from flyteplugins.union.remote import ClusterPool ClusterPool.update( "prod", object_store_uri="s3://my-prod-bucket/prefix", secret_store_type="AWS_SECRETS_MANAGER", secret_store_locator="us-east-1", image_registry="123456789012.dkr.ecr.us-east-1.amazonaws.com/union", ) ``` Editing the pool config changes the contract every member cluster is validated against, so a change that no longer matches a member cluster records a `cluster_pool_config` mismatch on that cluster on its next status report. This is also the fix for the opposite case: when a cluster reports config the pool doesn't expect, correct whichever side is wrong โ€” the pool here, or the cluster in its own deployment. ## Manage membership Cluster pool membership is normally set when clusters are registered: ### CLI ```bash flyte create cluster prod-us-east-1 --pool prod ``` ### Programmatic ```python from flyteplugins.union.remote import Cluster Cluster.create("prod-us-east-1", cluster_pool_name="prod") ``` You can also list clusters under `member_clusters` in the pool manifest to add them to the pool. That route only adds: it cannot remove a cluster from a pool or move one elsewhere. An existing cluster can be reassigned to another pool, but its co-named queue must be `drained` first; the simplest way to get there is to **Clusters and queues > Clusters > Drain and reactivate a cluster**. Wait for `flyte get cluster ` and `flyte get queue ` to report `drained`, then run `flyte update cluster --pool `. See **Clusters and queues > Clusters > Move a cluster to a different pool** for the complete workflow. ## Delete a pool A pool can be deleted only when it is **empty** โ€” it contains no live clusters and no live queues; otherwise the request is rejected. Clusters and queues that are themselves soft-deleted don't block the deletion, but neither can be restored until the pool has been restored. Empty the pool first: 1. Delete the member **Clusters and queues > Clusters > Delete a cluster**. Deleting a cluster also deletes its **Clusters and queues > Clusters > The co-named queue**, so the queues that came with the clusters go with them. 2. **Clusters and queues > Managing queues > Delete a queue** any queue you created in the pool yourself. The pool that holds the org-wide `default` queue (the `default` pool, unless your organization's first pool was created by hand and received that queue) follows the same rules: it can be deleted once emptied, which additionally means **Clusters and queues > Managing queues > Delete a queue** the `default` queue โ€” nothing is deleted on the pool's behalf. While the `default` pool is deleted, registering a cluster without naming a pool is rejected instead of falling back to it: name a pool explicitly, or undelete `default` first. ### CLI ```bash flyte delete cluster-pool prod flyte delete cluster-pool prod --yes # skip the confirmation prompt # List deleted pools, restore one flyte get cluster-pool --deleted flyte undelete cluster-pool prod ``` ### Programmatic ```python from flyteplugins.union.remote import ClusterPool ClusterPool.delete("prod") ClusterPool.undelete("prod") # restore a deleted pool ``` Deletion is a **soft delete**: the pool disappears from listings, but its name stays reserved โ€” creating a new pool under the same name is rejected โ€” and it can be restored with `flyte undelete cluster-pool `. ## Next With your pools defined, **Clusters and queues > Clusters** into them, then **Clusters and queues > Managing queues** to route workloads. === PAGE: https://www.union.ai/docs/v2/union/user-guide/clusters-and-queues/clusters === Register execution clusters into a pool and inspect their state, capacity, and bound queues. # Clusters > [!NOTE] Requires the `flyteplugins-union` plugin > The cluster CLI commands and Python objects on this page are provided by the > `flyteplugins-union` package. Install it with `pip install flyteplugins-union`. A **cluster** is an execution cluster registered with Union.ai. Every cluster subscribes to exactly one **Clusters and queues > Cluster pools**, which determines the data plane configuration (object store, secret store, container registry) the cluster uses. Creating a cluster record registers the cluster in the control plane. It does not install Kubernetes resources or deploy the data plane itself. For self-managed deployments, first provision and install the data plane using the appropriate [Self-managed deployment](../../deployment/selfmanaged/_index) guide, then use the commands or Python calls here to manage the control-plane record. ## Register a cluster If you omit the pool, the cluster is registered into the `default` pool. To use a custom pool, create that pool first. One edge case: if the `default` pool has been **Clusters and queues > Cluster pools > Delete a pool**, registering without a pool is rejected rather than falling back to it โ€” name a pool explicitly, or undelete `default`. ### CLI ```bash # Register in the default pool. flyte create cluster my-cluster # Register in a specific pool. flyte create cluster prod-us-east-1 --pool prod ``` ### Programmatic ```python from flyteplugins.union.remote import Cluster # Register in the default pool. Cluster.create("my-cluster") # Register in a specific pool. Cluster.create("prod-us-east-1", cluster_pool_name="prod") ``` Registration itself does not validate the cluster against the pool: any cluster is allowed to join. Validation happens asynchronously, once the cluster starts reporting its real object store, secret store, and container registry to the control plane. The control plane compares each reported value against the pool's config. It records a mismatch as a `cluster_pool_config` entry, with health `UNHEALTHY`, in the cluster's monitoring info. The cluster's overall health and unhealthy reasons do not change, so queues keep **Clusters and queues > Managing queues > How a queue routes** new work to it. See **Clusters and queues > Cluster pools > How a pool's config is enforced** for the full mechanism. After registering into a custom pool, check for a mismatch in `Cluster.get("").monitoring_info`. `flyte get cluster ` does not show monitoring info. The name `default` is reserved and cannot be used for a cluster (it collides with the org-wide `default` queue), and a cluster cannot share a name with an existing queue โ€” registration creates a queue named after the cluster, described next. ### The co-named queue Registering a cluster also creates an implicit **co-named queue**: a queue with the same name as the cluster, in the cluster's pool, whose selector names that one cluster explicitly โ€” not the `*` wildcard. So `flyte create cluster prod-us-east-1` also gives you a `prod-us-east-1` queue that routes only to `prod-us-east-1`, and every cluster can be targeted by name from day one, with no queue setup: ```python flyte.with_runcontext(queue="prod-us-east-1").run(main) ``` Registration additionally ensures the org-wide `default` queue exists โ€” unless that queue has been deliberately **Clusters and queues > Managing queues > Delete a queue**: nothing re-creates a soft-deleted `default` queue (or pool) implicitly; `flyte undelete` is the only way back. The `default` queue lives in the `default` pool with the `*` selector, so it routes to every healthy, `active` cluster in the `default` pool: a cluster registered there joins it automatically, while a cluster in any other pool never does. Both are ordinary queues โ€” they appear in `flyte get queue` (a co-named queue is flagged there as **cluster-managed**), carry the same concurrency, depth, and priority settings as any other, and are managed the same way on the **Clusters and queues > Managing queues** page. What sets the co-named queue apart is that its cluster selector and pool are managed by its cluster and cannot be edited directly: it follows its cluster if the cluster is **Clusters and queues > Clusters > Move a cluster to a different pool**. It also follows the cluster through the **Clusters and queues > Clusters > Cluster lifecycle**: draining the cluster drains it, activating the cluster activates it, and deleting the cluster deletes it. A co-named queue that was deleted on its own stays deleted, and while its cluster is `draining` or `drained` the queue cannot be activated on its own. The system confirms the cluster and queue transitions separately, so they may finish at slightly different times. See **Clusters and queues > Clusters > Cluster lifecycle > How the co-named queue follows its cluster**. ## Inspect clusters ### CLI ```bash # List all clusters with their lifecycle state, health, and capacity flyte get cluster # Inspect one cluster โ€” cloud config, state, capacity, and bound queues flyte get cluster prod-us-east-1 # Cap the number of results flyte get cluster --limit 50 ``` ### Programmatic ```python from flyteplugins.union.remote import Cluster for cluster in Cluster.listall(limit=100): print(cluster.name, cluster.pool, cluster.drain_state, cluster.health, cluster.capacity) cluster = Cluster.get("prod-us-east-1") print(cluster.name) print(cluster.pool) print(cluster.drain_state) print(cluster.queues) print(cluster.health, cluster.unhealthy_reasons) print(cluster.monitoring_info) print(cluster.capacity) print(cluster.config_drift) ``` The cluster's **Clusters and queues > Clusters > Cluster lifecycle** is the `drain_status.overall_state` field of the API response, which carries `CLUSTER_STATE_ACTIVE`, `CLUSTER_STATE_DRAINING`, `CLUSTER_STATE_DRAINED`, `CLUSTER_STATE_DELETING`, or `CLUSTER_STATE_DELETED`. The CLI shows it lowercased in the `Drain` column and Python exposes it the same way as `Cluster.drain_state`; the rest of this page uses the lowercase names. This is the state that `--drain`, `--activate`, `delete`, and `undelete` move, and the one to check before any maintenance on the cluster. The detailed view additionally shows the per-workload drain progress for runs and apps, available capacity, and the queues bound to the cluster. Fetching a cluster **by name** works in every lifecycle state, `deleted` included: `flyte get cluster ` and `Cluster.get` return a soft-deleted cluster with its deletion time (a `deleted at` row in the detailed view), so the record stays inspectable after deletion. Only the listing hides deleted clusters; `flyte get cluster --deleted` or `Cluster.listall(deleted=True)` lists them instead, which is how you find one to undelete. A `deleting` cluster is still live and appears in the normal listing. ## Cluster lifecycle A cluster is in one of five lifecycle states. The `drain`, `activate`, `delete`, and `undelete` transitions are requested by you; the moves into `drained` and `deleted` are made by the system once it confirms the cluster holds no more work. ```mermaid stateDiagram-v2 direction LR [*] --> active: register active --> deleting: delete draining --> deleting: delete deleting --> deleted: cleanup done (system) active --> draining: drain draining --> active: activate draining --> drained: no runs left (system) drained --> active: activate drained --> deleted: delete deleted --> drained: undelete ``` - **`active`**: accepting new work. Every cluster starts here. - **`draining`**: no new work; runs already on the cluster keep going. The system moves the cluster to `drained` once it confirms that no run or cleanup work remains on it. - **`drained`**: confirmed idle. The only state from which a delete completes in one step, and the state a restored cluster comes back in. - **`deleting`**: deletion requested while the cluster may still hold work. The system disconnects the cluster's workers, drops the cleanup work assigned to it, and fails the runs on it recoverably, so the retry path can place them on another eligible cluster. Runs that reached this cluster through its co-named queue are the exception: that queue enters `deleting` too, and its work fails for good. It then moves the cluster to `deleted`. - **`deleted`**: soft-deleted. The record and name are kept; the cluster is hidden from listings and refuses heartbeats and status reports. What each operation does from each state: | Current state | `--drain` | `--activate` | `flyte delete cluster` | `flyte undelete cluster` | |---|---|---|---|---| | `active` | โ†’ `draining` | no change | โ†’ `deleting` | rejected | | `draining` | no change | โ†’ `active` | โ†’ `deleting` | rejected | | `drained` | rejected (already drained) | โ†’ `active` | โ†’ `deleted` | rejected | | `deleting` | rejected | rejected | rejected | rejected | | `deleted` | rejected | rejected | rejected | โ†’ `drained` | Three rules follow from the table: - **Deleting a cluster is safe only from `drained`.** Unlike a queue, a cluster can be deleted from `active` or `draining`, and that path does not wait for work: actions on the cluster are failed and retried elsewhere only while they have retries left, and work that arrived through the co-named queue fails permanently. A drain followed by a delete is the safe sequence, because the system has confirmed the cluster is idle before anything is torn down. - Deletion cannot be canceled: once a cluster is `deleting`, the only way forward is `deleted`, and only then can it be undeleted. - `drained` and `deleted` are never requested directly; the system transitions into them. ### How the co-named queue follows its cluster The cluster's **Clusters and queues > Clusters > The co-named queue** moves with the cluster in the same transaction: | Cluster operation | Queue `active` | Queue `draining` | Queue `drained` | Queue `deleted` | |---|---|---|---|---| | drain | โ†’ `draining` | unchanged | unchanged | unchanged | | activate | unchanged | โ†’ `active` | โ†’ `active` | unchanged | | delete | โ†’ `deleting` | โ†’ `deleting` | โ†’ `deleted` | unchanged | | undelete | โ€” | โ€” | โ€” | โ†’ `drained` | A queue that is already `deleting` is left alone by every cluster operation, undelete included: it finishes deleting on its own, and once it is `deleted` you can restore it with `flyte undelete queue`. The system confirms the queue's `drained` and `deleted` transitions separately from the cluster's, so the two can finish in either order. The queue also has restrictions of its own while it is cluster-managed: it cannot be activated on its own while its cluster is `draining` or `drained` (`flyte update queue --activate` is rejected), and it cannot be undeleted on its own while its cluster is deleted. To keep a cluster from receiving work through its own queue while the cluster stays active, drain and then **Clusters and queues > Managing queues > Delete a queue**; activating the cluster does not bring a deleted queue back. ## Drain and reactivate a cluster Draining is the graceful way to take a cluster out of service: it stops new work from reaching the cluster while runs already there finish. A `draining` cluster drops out of every queue's routing, wildcard queues included. The cluster becomes `drained` once the system confirms that no run or cleanup work remains. You can reactivate it at any point while it is `draining` or after it is `drained`; reactivation resets the drain progress. A drain request is **rejected** while either of these holds: - **An app is assigned to the cluster.** Apps have no drain step, so [stop or reassign them](../apps/serve-and-deploy-apps/_index) first. The error names the blocking apps. - **Another live queue explicitly names the cluster** in its selector. Remove the cluster from that queue first. The error names the blocking queues. Wildcard (`*`) queues never block a drain. Draining a cluster also drains its co-named queue, and reactivating the cluster reactivates that queue; see **Clusters and queues > Clusters > Cluster lifecycle > How the co-named queue follows its cluster**. ### CLI ```bash flyte update cluster prod-us-east-1 --drain flyte get cluster prod-us-east-1 # wait for drain: drained flyte update cluster prod-us-east-1 --activate ``` `flyte update cluster` takes exactly one of `--drain`, `--activate`, or `--pool`. ### Programmatic ```python import time from flyteplugins.union.remote import Cluster cluster = Cluster.drain("prod-us-east-1") print(cluster.drain_state) # draining # Poll until the system confirms the cluster is idle. while Cluster.get("prod-us-east-1").drain_state != "drained": time.sleep(10) Cluster.activate("prod-us-east-1") ``` A `deleting` or `deleted` cluster cannot be drained or activated. To remove a cluster without waiting for its work to finish, **Clusters and queues > Clusters > Delete a cluster**. ## Move a cluster to a different pool A cluster can be reassigned to another pool in place, without deleting and re-registering it. The precondition that shapes the workflow is that the cluster's **Clusters and queues > Clusters > The co-named queue** must be `drained`, because that queue moves to the new pool with the cluster and a queue can only change pools when it holds no work. The move does not check the cluster's own lifecycle state, so the recommended way to satisfy the precondition is to **Clusters and queues > Clusters > Drain and reactivate a cluster**: that drains the co-named queue and additionally guarantees that no runs remain on the cluster. The move leaves the lifecycle state untouched, so a drained cluster stays `drained` afterwards and you can verify its new pool configuration before reactivating it. > [!WARNING] A pool move changes the cluster's data plane > The destination pool can use a different object store, secret store, and > container registry. Make the required data, images, and secrets available in > that data plane before moving the cluster. ### CLI ```bash flyte update cluster prod-us-east-1 --pool prod flyte update cluster prod-us-east-1 --pool prod --yes # skip the confirmation prompt ``` Without `--yes`, the CLI warns that the operation is unsafe and asks you to confirm. ### Programmatic ```python from flyteplugins.union.remote import Cluster Cluster.update("prod-us-east-1", cluster_pool_name="prod") ``` There is no confirmation prompt on this path. The destination pool must already exist โ€” the move never creates one โ€” and must differ from the cluster's current pool. ### Before you move a cluster 1. **Repoint other queues.** Any live queue other than the **Clusters and queues > Clusters > The co-named queue** that explicitly names the cluster must have it removed from its selector. Such a queue blocks both the cluster drain and the pool move. Wildcard (`*`) queues do not block either operation. `flyte get cluster ` lists the queues bound to the cluster. A soft-deleted queue that names the cluster does not block the move either; the cluster is dropped from its selector, because a deleted queue cannot follow the cluster into the new pool, so that the queue stays restorable. 2. **Stop apps and check for v1 executions.** A cluster does not only serve runs. [Apps](../apps/serve-and-deploy-apps/_index) assigned to the cluster block the drain: the drain request is rejected and names them, so stop or reassign them first. Legacy v1 executions, which Union.ai still supports today, are **not** tracked by the drain and do not block anything. Confirm out-of-band that none are running before continuing. 3. **Drain the cluster.** Run `flyte update cluster --drain`. This also drains its co-named queue. Wait until `flyte get cluster ` reports the cluster as `drained` and `flyte get queue ` reports the queue as `drained`. The move is rejected while the queue is still `draining`. 4. **Make sure the configs match.** The destination pool's config must match what the cluster reports. The control plane does not enforce this: a mismatch does not make the cluster unhealthy, so once activated it receives work like any other member of the pool โ€” see below. After the move, confirm the cluster is healthy and has no `cluster_pool_config` entry in its monitoring info, then run `flyte update cluster --activate`. Its co-named queue is activated with it. ### If the configs don't match after the move Pool config is validated asynchronously against what the cluster reports (see **Clusters and queues > Cluster pools > How a pool's config is enforced**), so a mismatch surfaces only after the move, on the cluster's next status report. It appears as a `cluster_pool_config` entry in `Cluster.get("").monitoring_info`, and on the cluster's page in the console under **Cluster Pool Config**. The health and unhealthy reasons that `flyte get cluster ` shows are unaffected, and **Clusters and queues > Managing queues > How a queue routes** keep routing new work to it once it is active. Fix whichever side is wrong: - **The cluster's config**: the reported values come from the deployed data plane, so change them where that deployment is defined (Terraform, Helm values, and so on) and redeploy the cluster. The control plane picks up the new values on the cluster's next status report. - **The pool's config**: run `flyte update cluster-pool `, which opens the pool in your `$EDITOR`. See **Clusters and queues > Cluster pools > Update a pool**. ## Delete a cluster You can delete a cluster from any live state, and the state decides whether the delete is safe: - **From `drained`, deletion is safe.** The system has already confirmed the cluster holds no work, so the cluster becomes `deleted` immediately and nothing is interrupted. - **From `active` or `draining`, deletion is not safe.** The cluster becomes `deleting`: the system disconnects the cluster's workers and fails the actions on that cluster, but in a recoverable manner. If there are retries remaining for those actions, the system retries them on healthy clusters of the queue the work was submitted on. Keep in mind, however, that actions which came in through the co-named queue end up failed permanently, since moving a cluster to `deleting` also moves the co-named queue to `deleting`. Once nothing remains on it, the cluster moves to `deleted`. Apps assigned to the cluster are ignored: deletion neither evicts nor reassigns them, so stop or reassign them yourself. Only a **Clusters and queues > Clusters > Drain and reactivate a cluster** is strict about apps, by refusing to start while any is assigned. A `deleting` cluster is still listed and rejects every further lifecycle request: it cannot be drained, activated, deleted again, or undeleted. > [!WARNING] Drain before you delete > Deletion does not wait for running work and cannot be canceled. To take a > cluster out of service without losing work, > **Clusters and queues > Clusters > Drain and reactivate a cluster** first, wait for `drained`, and > only then delete it. Deletion also does not remove Kubernetes pods that remain on the data plane, app pods included. **You are responsible for cleaning up those pods.** The cluster's **Clusters and queues > Clusters > The co-named queue** enters deletion with the cluster. A drained queue becomes `deleted` immediately; an active or draining queue becomes `deleting` until its cleanup finishes. This cluster-driven cascade is the only way an `active` queue ever enters `deleting`; `flyte delete queue` itself rejects an active queue. The cluster and queue reach `deleted` independently and may finish in either order. Any other live queue that explicitly names the cluster blocks deletion; remove the cluster from its selector first. Wildcard (`*`) queues do not block deletion, and neither does a soft-deleted queue that names the cluster: it keeps its reference, so it can only be undeleted once the cluster is. A queue whose selector you empty this way stops routing work anywhere until you point it at another cluster **in its pool** (or **Clusters and queues > Managing queues > Move work to another pool** once drained). ### CLI ```bash flyte delete cluster prod-us-east-1 flyte delete cluster prod-us-east-1 --yes # skip the confirmation prompt # List deleted clusters, restore one flyte get cluster --deleted flyte undelete cluster prod-us-east-1 ``` ### Programmatic ```python from flyteplugins.union.remote import Cluster Cluster.delete("prod-us-east-1") Cluster.undelete("prod-us-east-1") # restore a deleted cluster ``` The command returns after the cluster becomes either `deleting` or `deleted`, and says which. A `deleting` cluster remains visible in normal listings while teardown runs; watch it with `flyte get cluster `. Once `deleted`, it disappears from normal listings and stops accepting status reports and heartbeats. The record is retained and its name stays reserved, so registering another cluster with the same name is rejected. `flyte get cluster ` still returns the deleted cluster with its deletion time, and `flyte get cluster --deleted` lists every deleted cluster. A `deleting` cluster cannot be restored; wait for deletion to finish. Then use `flyte undelete cluster `. The cluster returns in the `drained` state, and so does its co-named queue if that queue is `deleted`, even if it had been deleted on its own before the cluster was. Undeleting the cluster is the only way to bring that queue back: `flyte undelete queue` refuses it while the cluster is deleted. A co-named queue that is still `deleting` is not touched; it finishes deleting on its own, and you can undelete it separately afterwards. The cluster's pool must itself be live; undelete the pool first if it was deleted. Run `flyte update cluster --activate` to reactivate cluster and queue together. ## Next Once your clusters are registered and healthy, **Clusters and queues > Managing queues** to route and govern the workloads that run on them. === PAGE: https://www.union.ai/docs/v2/union/user-guide/clusters-and-queues/queues === Create and manage the scheduling lanes that route workloads to a pool and enforce concurrency, resource caps, and priority. # Managing queues > [!NOTE] Requires the `flyteplugins-union` plugin > The queue CLI commands and Python objects on this page are provided by the > `flyteplugins-union` package. Install it with `pip install flyteplugins-union`. A **queue** is a named scheduling lane. It does two jobs at once: it **routes** work to a **Clusters and queues > Cluster pools** (and, optionally, specific clusters within it), and it **governs** that work with concurrency, depth, and priority limits, and with caps on the CPU, memory, and GPUs its scheduled work may use. This page covers creating and managing queues administratively, from either the CLI or Python. For how workflow authors *target* a queue from task code, see **Tasks > Configure tasks > Queues**. For sharing clusters across teams with resource caps, and for choosing how a queue schedules when capacity is tight, see **Clusters and queues > Resource caps and scheduling**. ## How a queue routes A queue lives inside one **cluster pool** and routes work to one or more clusters *within that pool*. By default (the `*` selector) it spreads across the pool's healthy, `active` clusters; you can also pin it to specific clusters. It can never reach a cluster in another pool: pools are isolation boundaries. ```mermaid flowchart TD R(["Runs & actions"]) subgraph Pdef["Cluster pool: default"] direction TB QD["Queue: default
selector: *"] CA["Cluster A"] CB["Cluster B"] QD --> CA QD --> CB end subgraph Pprod["Cluster pool: prod"] direction TB QP["Queue: prod-queue
selector: *"] QG["Queue: gpu-queue
pinned: Cluster C"] CC["Cluster C"] CD["Cluster D"] QP --> CC QP --> CD QG --> CC end R --> QD R --> QP R --> QG ``` Users submit to a **queue**, never to a pool or a cluster directly. Each queue sits inside exactly one pool: - **`default`** spreads across the eligible clusters in the `default` pool. - **`prod-queue`** spreads across the eligible clusters in the `prod` pool. - **`gpu-queue`** lives in the same `prod` pool but is pinned to a single cluster. > [!NOTE] Routing skips unhealthy and non-active clusters > A `*` selector does not mean *every* cluster in the pool โ€” it means every > cluster that is both **healthy** and **`active`** in its > **Clusters and queues > Clusters > Cluster lifecycle**, evaluated against the pool's > current state. Pinned selectors are filtered the same way: an unhealthy > cluster, or one that is `draining`, `drained`, or being deleted, receives no > new work from *any* queue, wildcard or pinned. > Say a pool holds two clusters and the second goes unhealthy: > the queue routes new runs and actions to the first cluster only, and sends > nothing to the second until it becomes healthy again. This governs the placement > of new work; it does not move work that has already been dispatched. Check with > `flyte get cluster `, which reports each cluster's lifecycle state, > health, and unhealthy reasons. ### Queues you get for free You don't have to create a queue to have one. Two exist without any action on your part: - The org-wide **`default`** queue, in the `default` pool with the `*` selector. Anything that doesn't explicitly target a queue goes here. (If the `default` queue is **Clusters and queues > Managing queues > Drain and reactivate a queue** or **Clusters and queues > Managing queues > Delete a queue**, untargeted submissions are rejected until it is active again โ€” a restored queue comes back `drained`, so after an undelete it must also be reactivated.) - A **co-named queue** for every cluster: registering a cluster creates a queue with the *same name as the cluster*, in that cluster's pool, whose selector names that one cluster explicitly rather than using `*`. Register `prod-us-east-1` and you get a `prod-us-east-1` queue that routes only to `prod-us-east-1` โ€” so any cluster can be targeted by name immediately, without setting up a queue for it. See **Clusters and queues > Clusters > The co-named queue**. Both are ordinary queues: they show up in `flyte get queue` and take the same settings and updates as queues you create yourself โ€” with one exception. A co-named queue's cluster selector and pool are managed by its cluster and cannot be edited directly: the queue follows its cluster if the cluster is **Clusters and queues > Clusters > Move a cluster to a different pool**. It also follows the cluster through drain, activate, and delete transitions, and it cannot be activated on its own while its cluster is `draining` or `drained` (see **Clusters and queues > Clusters > Cluster lifecycle > How the co-named queue follows its cluster**). The cluster and queue finish their transitions separately, so they may reach their final states at slightly different times. Its other settings (concurrency, depth, priority) stay editable like any queue's. Listings make the distinction visible: cluster-managed queues are flagged in the `flyte get queue` table (`cluster_managed`, exposed as `Queue.cluster_managed` in Python), and `flyte update queue --edit` says so at the top of the edit buffer. The selector (which clusters within the pool) is mutable and can be changed at any time. The pool a queue lives in can only change once the queue is fully **drained**: a pool move on an `active` or `draining` queue is rejected, because moving a queue that still holds work would cross an isolation boundary. See **Clusters and queues > Managing queues > Move work to another pool**. > [!NOTE] Queues are organization-scoped > Every queue is visible to the whole organization; a queue cannot yet be scoped > to a project or a domain. Some CLI and Python surfaces already expose `project` > and `domain` parameters, but project/domain-scoped queue creation is not > implemented yet and is rejected. Support is coming soon. ## Queue operations Every queue operation is available from the CLI and from Python. The sections below cover each one. | Operation | CLI | Python | |---|---|---| | **Clusters and queues > Managing queues > Create a queue** | `flyte create queue NAME` | `Queue.create` | | **Clusters and queues > Managing queues > Inspect queues** | `flyte get queue NAME` | `Queue.get` | | **Clusters and queues > Managing queues > Inspect queues** | `flyte get queue` (`--state`, `--deleted`) | `Queue.listall` | | **Clusters and queues > Managing queues > Change a queue's settings** | `flyte update queue NAME --edit`, or flags such as `--max-accelerators` | `Queue.update` | | **Clusters and queues > Managing queues > Drain and reactivate a queue** | `flyte update queue NAME --drain` / `--activate` | `Queue.drain` / `Queue.activate` | | **Clusters and queues > Managing queues > Delete a queue** | `flyte delete queue NAME` | `Queue.delete` | | **Clusters and queues > Managing queues > Delete a queue** | `flyte undelete queue NAME` | `Queue.undelete` | | **Clusters and queues > Managing queues > Inspect queues** | `flyte get queue NAME --watch` | `Queue.details`, `Queue.watch` | | **Clusters and queues > Resource caps and scheduling > See how much of a cap is in use** | `flyte get queue --watch` (`--pool`) | `Queue.watch_pool` | The resource cap flags of `flyte create queue` and `flyte update queue` are: | Flag | Python | What it does | |---|---|---| | `--max-resources NAME=QUANTITY` | `max_resources={...}` | Caps `cpu`, `memory`, or `ephemeral_storage`. Repeat for each resource. | | `--clear-max-resources` | `max_resources={}` | Removes the resource caps (update only). | | `--max-accelerators DEVICE=N` | `max_accelerators={...}` | Caps one device type, such as `H100=10`, `V6E=10`, or `A100/1g.5gb=4`, or with `nvidia_gpu=8` the GPUs requested without a device type. Repeat for each entry. | | `--clear-max-accelerators` | `max_accelerators={}` | Removes the accelerator caps (update only). | | `--scheduling` | `scheduling=` | `strict_fifo` or `greedy_capacity`. | See **Clusters and queues > Resource caps and scheduling** for how these caps work. ## Create a queue `run_concurrency` and `action_concurrency` are required; everything else has a sensible default. With no cluster selector, a queue spreads work across **all** healthy clusters in its pool. The name `default` is reserved, and a queue cannot share a name with a cluster โ€” every cluster already owns its **Clusters and queues > Clusters > The co-named queue** โ€” or with a soft-deleted queue, whose name stays reserved until it is **Clusters and queues > Managing queues > Delete a queue**. ### CLI ```bash flyte create queue my-queue \ --run-concurrency 100 \ --action-concurrency 1000 ``` Create a higher-priority queue in a specific pool: ```bash flyte create queue gpu-queue \ --cluster-pool prod \ --cluster prod-us-east-1 \ --run-concurrency 50 \ --action-concurrency 500 \ --depth 5000 \ --priority max ``` ### Programmatic ```python from flyteplugins.union.remote import Queue queue = Queue.create( "my-queue", run_concurrency=100, action_concurrency=1000, ) print(queue.to_dict()) ``` Create a higher-priority queue in a specific pool: ```python queue = Queue.create( "gpu-queue", cluster_pool="prod", clusters=["prod-us-east-1"], run_concurrency=50, action_concurrency=500, depth=5000, priority="max", ) ``` ### Console In the console, go to **Settings > Queues** and click **New Queue**. Fill in the **New queue** form and click **Create queue**. The fields map to the same settings the CLI and Python expose: ![The New queue form in the console](../../_static/images/user-guide/cluster-workload-management/queues/queues-new-form.png) | Form field | Setting | |---|---| | **Name** | the queue name | | **Priority** | `priority` (shown as Low / Medium / High, see below) | | **Cluster pool** | `cluster_pool` / `--cluster-pool` | | **Clusters** | `clusters` / `--cluster` ("All available clusters (default behavior)" routes to every cluster in the pool) | | **Depth** | `depth` / `--depth` | | **Run concurrency** | `run_concurrency` / `--run-concurrency` | | **Action concurrency** | `action_concurrency` / `--action-concurrency` | The console labels priority **Low**, **Medium**, and **High**; these are the same levels the CLI and Python call `min`, `medium`, and `max`. > [!NOTE] Queues are bound to a cluster pool > Every queue is bound to a cluster pool, chosen at creation time with > `cluster_pool` in Python or `--cluster-pool` in the CLI. If you omit it, the > queue is bound to the `default` cluster pool. ### What each setting controls | Python | CLI | Default | What it controls | |---|---|---|---| | `cluster_pool` | `--cluster-pool` | `default` pool | The pool this queue lives in. A queue can only route to clusters in its own pool. | | `clusters` | `--cluster` | `["*"]` (all clusters in the pool) | Pins the queue to one or more clusters in the pool. `*` means all `active`, healthy clusters in the pool (see **Clusters and queues > Managing queues > How a queue routes**) and must be the only entry if used. | | `run_concurrency` | `--run-concurrency` | Required | Maximum number of *runs* active on the queue at once. Children of an active run aren't counted. Use this to stop a job from overlapping with a previous invocation of itself. `0` means no limit. | | `action_concurrency` | `--action-concurrency` | Required | Maximum number of *actions* (tasks) running at once. A value of 1 serializes the queue, and higher values bound the burst rate. `0` means no limit. | | `depth` | `--depth` | `10000` | Total in-flight plus waiting items the queue will hold. `0` means no limit. | | `priority` | `--priority` | `medium` | `min`, `medium`, or `max`. Among queues contending for the same pool's capacity, higher-priority work is scheduled first. Priority controls ordering, not preemption. | | `max_resources` | `--max-resources` | No cap | Caps the CPU, memory, and ephemeral storage requested by the queue's in-flight actions, across every cluster the queue routes to. | | `max_accelerators` | `--max-accelerators` | No cap | Caps the queue's in-flight GPUs and other accelerators per device type, and with `nvidia_gpu` the GPUs requested without a device type. Repeat the flag for each entry. | | `scheduling` | `--scheduling` | `strict_fifo` | `strict_fifo` or `greedy_capacity`. Decides whether the queue waits or moves on when the next action in line does not fit. The `default` queue and co-named queues start with no policy (`unspecified`) and order actions by project and domain, round-robin. | Under the hood the priority levels map to enum values 1, 50, and 100; use `max` for a priority higher than 50. `max_resources`, `max_accelerators`, and `scheduling` are covered in **Clusters and queues > Resource caps and scheduling**. ## Inspect queues ### CLI ```bash # List all queues flyte get queue # List live queues in one state: active, draining, drained, or deleting flyte get queue --state draining # Inspect one queue's settings and status flyte get queue gpu-queue # Stream live metrics โ€” runs in-flight, actions in-flight, queue depth flyte get queue gpu-queue --watch # List soft-deleted queues (hidden from the plain listing) flyte get queue --deleted ``` `--watch` renders live progress bars for run concurrency, action concurrency, and depth, plus one for each **Clusters and queues > Resource caps and scheduling > See how much of a cap is in use**, so you can see a queue filling up or draining in real time. Metrics are available while a queue is `active`, `draining`, `drained`, or `deleting`. Watching a `draining` queue shows work finishing normally; watching a `deleting` queue shows its cleanup progress. A **Clusters and queues > Managing queues > Delete a queue** queue cannot be watched until you restore it. Fetching a queue **by name** works even after it has been **Clusters and queues > Managing queues > Delete a queue**: `flyte get queue ` returns the soft-deleted queue carrying its deletion time instead of failing, so a queue that an old run once targeted stays inspectable. Only the listing hides deleted queues, unless you pass `--deleted`; `--state deleted` without `--deleted` returns nothing for the same reason. ### Programmatic ```python from flyteplugins.union.remote import Queue for queue in Queue.listall(limit=100): print(queue.name, queue.status, queue.priority, queue.cluster_pool, queue.clusters) # Narrow the live listing to one lifecycle state: "active", "draining", # "drained", or "deleting" for queue in Queue.listall(state="draining"): print(queue.name) # Deleted queues are hidden from the listing unless you ask for them for queue in Queue.listall(deleted=True): print(queue.name) queue = Queue.get("gpu-queue") print(queue.to_dict()) ``` `Queue.get` works even on a **Clusters and queues > Managing queues > Delete a queue** queue: it returns the soft-deleted queue carrying its deletion time instead of failing, while `Queue.listall` hides deleted queues. ```python metrics = Queue.details("gpu-queue") print(metrics) ``` To stream metrics: ```python for metrics in Queue.watch("gpu-queue"): print(metrics) ``` `Queue.details` and `Queue.watch` work on live queues, including `draining`, `drained`, and `deleting` queues. Unlike `Queue.get`, neither works on a **Clusters and queues > Managing queues > Delete a queue** queue. ### Console Go to **Settings > Queues** to see all your queues. ![The console Queues list, grouped by cluster pool](../../_static/images/user-guide/cluster-workload-management/queues/queues-list.png) Queues are grouped by cluster pool (the **View by Pool** toggle), and each row shows its status, priority, and live **Depth**, **Runs**, and **Actions** counts against the queue's limits. Use the **Status** filter or the search box to narrow the list. Click a queue to open its detail view, which has four tabs: **Overview**, **Actions**, **Usage**, and **Settings**. **Overview** shows the queue's live state: its cluster pool, the clusters it is connected to and their CPU, GPU, and memory capacity, and live counts against the queue's limits: - **Total depth**: every admitted action the queue is still processing, whether waiting, in flight, or finishing up. This is what counts against `depth`. - **Waiting**: the subset of actions not yet dispatched to a worker. - **Runs in flight** and **Actions in flight**, against `run_concurrency` and `action_concurrency`. When the action at the head of a `strict_fifo` queue is waiting for resources, **Overview** shows a banner naming it, how long it has waited, and whether the queue's cap or cluster capacity is holding it, with links to its run and to the queue's settings. The queue list marks that queue with a badge. **Actions** lists the queue's pending and in-flight task actions across all runs, refreshing every 15 seconds. Each row shows the action, its phase, its run, its project and domain, and its **Time in Queue**: how long it waited from entering the queue until a worker picked it up. The time keeps counting while the action is still waiting and stops at worker assignment, so later resource waits and initialization don't count. It shows `โ€”` when the enqueue or assignment time wasn't recorded. An action shown as **Assigned** has been picked up by a worker but hasn't reported an execution phase yet. Use the search box to filter by action name, run, project, or domain. From a row's menu you can open the action, its run, or its project, copy the action or run ID, or abort the action or its whole run. Seeing this tab requires the `view_flyte_executions` action in the queue's scope, and aborting requires `create_flyte_executions` in the action's project (see **User management**). In a run's details, the **Queue** pill shows the queue the selected task action was routed to, including a queue set on that task that overrides the run's default. Click it to open that queue's detail view. **Usage** gives ready-to-copy snippets for routing work to this queue, at run level and per task, with the queue's name already filled in. These are the same routing methods described in **Tasks > Configure tasks > Queues**. **Settings** lists the queue's current configuration: its pool, connected clusters, and scope, plus its priority, depth, and run and action concurrency limits. ## Change a queue's settings You can update limits, priority, or cluster pinning. The update API replaces the full queue spec; the Python wrapper handles this by reading the current queue first, changing only the fields you pass, and writing the complete spec back. Resource caps and the scheduling policy can also be changed with dedicated flags, without opening an editor; see **Clusters and queues > Resource caps and scheduling > Set caps on a queue**. ### CLI ```bash flyte update queue gpu-queue --edit ``` This opens the queue in your `$EDITOR` so you can adjust the mutable settings. ### Programmatic ```python from flyteplugins.union.remote import Queue Queue.update( "gpu-queue", run_concurrency=75, action_concurrency=750, priority="max", clusters=["prod-us-east-1"], ) ``` Changing the **cluster selector within the same pool** (which clusters the queue pins to) takes effect immediately because every cluster in the pool shares the same data plane. Changing the queue's **pool** (`cluster_pool` in the YAML or Python) is allowed only when the queue is **Clusters and queues > Managing queues > Drain and reactivate a queue**, the destination pool exists, and every cluster in the queue's selector is a member of the destination pool โ€” see **Clusters and queues > Managing queues > Move work to another pool**. A cluster's **Clusters and queues > Clusters > The co-named queue** rejects selector and pool changes entirely: those are managed by its cluster. A soft-deleted queue cannot be updated at all; **Clusters and queues > Managing queues > Delete a queue** first. ## Queue lifecycle A queue is in one of five lifecycle states. The `drain`, `activate`, `delete`, and `undelete` transitions are requested by you; the moves into `drained` and `deleted` are made by the system once it confirms the queue holds nothing. ```mermaid stateDiagram-v2 direction LR [*] --> active: create active --> deleting: cluster deleted (co-named queue only) draining --> deleting: delete deleting --> deleted: cleanup done (system) active --> draining: drain draining --> active: activate draining --> drained: no work left (system) drained --> active: activate drained --> deleted: delete deleted --> drained: undelete ``` - **`active`**: accepting new submissions. - **`draining`**: no new submissions; in-flight work runs to completion. The system moves the queue to `drained` once it confirms the queue holds no run or cleanup work. - **`drained`**: confirmed empty. The only state from which a delete completes in one step, the only state in which the queue can change pools, and the state a restored queue comes back in. - **`deleting`**: deletion requested while the queue may still hold work. The system aborts the queue's remaining run work, waits for cleanup work, and then moves the queue to `deleted`. The queue stays listed meanwhile. - **`deleted`**: soft-deleted. Hidden from listings and never scheduled on; the name stays reserved and `flyte get queue ` still returns it. What each operation does from each state: | Current state | `--drain` | `--activate` | `flyte delete queue` | `flyte undelete queue` | Pool change | |---|---|---|---|---|---| | `active` | โ†’ `draining` | no change | rejected (drain first) | rejected | rejected | | `draining` | no change | โ†’ `active` | โ†’ `deleting` | rejected | rejected | | `drained` | rejected (already drained) | โ†’ `active` | โ†’ `deleted` | rejected | allowed | | `deleting` | rejected | rejected | rejected | rejected | rejected | | `deleted` | rejected | rejected | rejected | โ†’ `drained` | rejected | A cluster's co-named queue is the one exception in the `--activate` column: while its cluster is `draining` or `drained`, the queue cannot be activated on its own. Activating the cluster activates it. Three rules follow from the table: - **Deleting a queue is a safe archive operation.** A queue must always be drained before it can be deleted: there is no path from `active` into deletion that you can request on a queue, so deleting a queue that is accepting work always takes two calls, a drain and then a delete. A single misdirected command can never take a serving queue away, and the delete itself only archives the record. The one indirect path is **Clusters and queues > Clusters > Delete a cluster**, which takes the cluster's co-named queue into deletion whatever state it is in; that path is only as safe as the cluster delete that triggers it. - Deletion cannot be canceled: a `deleting` queue can only become `deleted`, and only then can it be undeleted. - `drained` and `deleted` are never requested directly; the system transitions into them once it has confirmed the queue holds nothing. Draining a cluster drains its co-named queue and activating the cluster activates it; see **Clusters and queues > Clusters > Cluster lifecycle > How the co-named queue follows its cluster**. ## Drain and reactivate a queue **Draining** takes a queue out of rotation without losing in-flight work: the queue stops admitting new submissions, work already in flight runs to completion, and once nothing is left the queue settles into the `drained` state. Use it before maintenance, deletion, or as part of **Clusters and queues > Managing queues > Move work to another pool**. ### CLI ```bash flyte update queue gpu-queue --drain # stop new submissions; let in-flight work finish flyte update queue gpu-queue --activate # put the queue back in rotation ``` ### Programmatic ```python from flyteplugins.union.remote import Queue Queue.drain("gpu-queue") # stop new submissions; let in-flight work finish Queue.activate("gpu-queue") # put the queue back in rotation ``` To see where things stand across the organization, filter listings by state: `flyte get queue --state draining` shows the queues still finishing in-flight work, `--state drained` the ones that are done, and `--state deleting` the ones being removed. An active queue must start draining before it can be **Clusters and queues > Managing queues > Delete a queue**, but you do not have to wait for `drained`: deleting a `draining` queue begins its cleanup immediately. A **Clusters and queues > Managing queues > Move work to another pool** does require the queue to be fully `drained`. Deleting a cluster automatically takes its co-named queue into deletion, whatever state that queue is in. Any queue can be drained, including the `default` queue and a queue configured as the default run queue (`run.default_queue`) in your organization's settings at any scope โ€” draining is how you stop scheduling on it, and the prerequisite for **Clusters and queues > Managing queues > Delete a queue**. A draining or drained queue still resolves as the default: runs that land on it are rejected with an error saying the queue is not accepting work. Only **Clusters and queues > Managing queues > Delete a queue** a queue referenced in settings is refused. ## Delete a queue A queue must be draining or drained before it is deleted: an `active` queue is rejected, so start draining it first. This is what makes deleting a queue a safe archive operation, in contrast to **Clusters and queues > Clusters > Delete a cluster**, which can interrupt work. Once the queue is draining you can choose whether to wait: - Deleting a `draining` queue moves it to `deleting`. Queued and running actions on it are failed rather than finished, as a final attempt that is not retried; cleanup work is left to run. The system moves the queue to `deleted` once nothing remains on it. - Deleting a `drained` queue moves it directly to `deleted`, because the system has already confirmed that no work or cleanup remains. Deletion cannot be canceled. A `deleting` queue rejects every further request: it cannot be drained, activated, deleted again, or undeleted. Wait until it becomes `deleted` before undeleting it. A queue referenced as the default run queue (`run.default_queue`) in settings at any scope can be drained but not deleted: update or unset those settings first. A cluster's **Clusters and queues > Clusters > The co-named queue** can be deleted on its own while the cluster lives. Deleting the cluster also deletes its co-named queue and is the only operation that can take that queue directly from `active` to `deleting`; that cascade does not apply the `run.default_queue` check, so a co-named queue used as a default run queue goes away with its cluster. The `default` queue is no exception: drain it, then delete it, like any other queue โ€” deleting it is also how the `default` pool is emptied of live queues so that **Clusters and queues > Cluster pools > Delete a pool**. While the `default` queue is deleted, submissions that name no queue and have no `run.default_queue` setting to fall back on are rejected at creation. Nothing re-creates it implicitly; `flyte undelete queue default` brings it back. ### CLI ```bash flyte delete queue gpu-queue flyte delete queue gpu-queue --yes # skip the confirmation prompt # List deleted queues, restore one flyte get queue --deleted flyte undelete queue gpu-queue ``` ### Programmatic ```python from flyteplugins.union.remote import Queue queue = Queue.delete("gpu-queue") print(queue.status) # deleting or deleted Queue.undelete("gpu-queue") # restore a deleted queue ``` A `deleting` queue remains visible in normal listings while cleanup runs, and it can still be inspected or watched. Once `deleted`, it is soft-deleted: it disappears from normal listings and is no longer scheduled on, but its name stays reserved. Fetching it by name still works โ€” `flyte get queue ` and `Queue.get` return the queue with its deletion time. Use `flyte get queue --deleted` to list deleted queues. Restore it with `flyte undelete queue `. The queue's pool and pinned clusters must still be live. A cluster's co-named queue undeletes like any other queue while its cluster is live; while the cluster is deleted, the undelete is refused and **Clusters and queues > Clusters > Delete a cluster** brings the queue back with it. The restored queue comes back `drained`; reactivate it to resume routing. ## Move work to another pool Moving work to a different **pool** crosses an isolation boundary. In-flight runs have already landed their data, containers, code, and secrets in the old pool's data plane, and a different pool's clusters cannot read them. So work in flight never moves: the migration is always drain-first, in one of two shapes. **Move the queue itself.** A queue can change pools once it holds no work: 1. **Clusters and queues > Managing queues > Drain and reactivate a queue** the queue and wait for it to reach the `drained` state. 2. Update the queue's pool โ€” `flyte update queue --edit` and change `cluster_pool` in the YAML, or `Queue.update(name, cluster_pool=...)` โ€” and set its cluster selector to clusters that are members of the destination pool (or `*`). 3. **Clusters and queues > Managing queues > Drain and reactivate a queue** the queue. Anything targeting the queue by name follows it to the new pool. New submissions made while it is drained are rejected, so coordinate the window with the queue's users. **Replace the queue.** Alternatively, keep the old queue's pool binding and shift traffic over: 1. Create a new queue in the destination pool. 2. Update workflows, launch plans, triggers, or run overrides to target the new queue. 3. **Clusters and queues > Managing queues > Drain and reactivate a queue** the old queue to shut out straggler submissions and let in-flight work finish. 4. **Clusters and queues > Managing queues > Delete a queue** the drained queue, or leave it idle โ€” an idle queue costs nothing. > [!NOTE] Queue overrides stay within a pool > A task can override its queue at runtime > (**Tasks > Configure tasks > Queues > Overriding a queue at runtime**), > but only to another queue in the **same pool** as the run's original queue. A > cross-pool override is rejected, for the same data plane reason that moving > work between pools requires a drain-and-replace migration. ## See also - **Tasks > Configure tasks > Queues**: routing work to a queue from task code, triggers, and per-run context. - **Clusters and queues > Resource caps and scheduling**: cap the resources a queue's scheduled work may use and choose its scheduling policy. - **Clusters and queues > Cluster pools** and **Clusters and queues > Clusters**: the routing targets a queue points at. === PAGE: https://www.union.ai/docs/v2/union/user-guide/clusters-and-queues/resource-caps-and-scheduling === Share clusters across teams with per-queue CPU, memory, and GPU caps, and choose how a queue schedules work when capacity is tight. # Resource caps and scheduling > [!NOTE] Requires `flyteplugins-union` 0.16.0 or later > The queue CLI commands and Python objects on this page are provided by the > `flyteplugins-union` package. Install it with > `pip install "flyteplugins-union>=0.16.0"`. Earlier versions send a > `nvidia_gpu` cap the server rejects. Two teams share one pool of GPU clusters. The research team launches a sweep that asks for every H100 in the pool, and the inference team's nightly evaluation, which needs four, waits for hours. Action concurrency limits do not fix this. One action can ask for half a CPU and the next for sixty-four GPUs, so the number of running actions says little about how much of the cluster a team is using. A resource cap limits the resources themselves. Give each team a queue and cap the CPU, memory, and GPUs that the queue's scheduled work may use at once. Both teams then run on the same clusters, and neither can take all of the capacity. ```bash flyte create queue research \ --run-concurrency 100 \ --action-concurrency 1000 \ --max-resources cpu=512 \ --max-resources memory=4Ti \ --max-accelerators H100=48 \ --scheduling greedy_capacity flyte create queue inference-eval \ --run-concurrency 50 \ --action-concurrency 500 \ --max-resources cpu=128 \ --max-accelerators H100=16 \ --scheduling greedy_capacity ``` The **Clusters and queues > Resource caps and scheduling > Choose a scheduling policy** decides what a queue does when the next action in line does not fit under its caps. This page covers a queue's resource and scheduling settings. To create, drain, or delete queues, see **Clusters and queues > Managing queues**. ## What a cap limits A cap limits the total resources requested by the actions a queue has scheduled and that have not finished. It adds up what each action asks for in its `resources`. Actual usage inside the container does not count. A queue has one cap for all the clusters it routes to. A queue still accepts as much work as its depth allows, and the cap limits how much of that work is scheduled at once. On a queue capped at 48 H100s, at most 48 H100s are scheduled at any moment, on one cluster or spread over four. The rest of the work waits in the queue. A cap applies only to the resources you name. `--max-resources cpu=512` caps CPU and leaves memory unlimited. A cap does not reserve capacity. The caps of queues that share clusters can add up to more than the clusters have, so a busy team can use capacity that an idle team is not using. An action is scheduled only when it fits under the queue's run concurrency, action concurrency, depth, and resource caps together. There are two cap settings: | Python | CLI | Limits | Values | |---|---|---|---| | `max_resources` | `--max-resources` | `cpu`, `memory`, `ephemeral_storage` | Kubernetes quantities such as `64`, `500m`, `512Gi` | | `max_accelerators` | `--max-accelerators` | GPUs and other accelerators, per device type, and NVIDIA GPUs requested without a device type | A whole number of devices for each entry | ## Cap GPUs and accelerators A task asks for a GPU in one of two ways. It names a device, such as `H100:1`, or it asks for a GPU of any type with `gpu=1`. `--max-accelerators` caps both: name a device type to cap that type, or use `nvidia_gpu` to cap the GPUs requested without a type. ### GPUs of a named type `--max-accelerators` caps one device type. Repeat it to cap several types on the same queue: ```bash # At most 48 H100s, 16 A100s, and 32 T4s scheduled at once flyte create queue research \ --run-concurrency 100 \ --action-concurrency 1000 \ --max-accelerators H100=48 \ --max-accelerators A100=16 \ --max-accelerators T4=32 ``` Each type has its own cap. A task that asks for T4s counts against the T4 cap only, so a team that has reached its H100 cap can still run T4 work. A type you do not name is unlimited. Name a device the way a task does (`T4`, `A100 80G`, `V6E`) or by its canonical name (`nvidia-t4`, `nvidia-a100-80gb`, `google-tpu-v6e`). The queue stores and prints the canonical name, for example `nvidia_gpu/nvidia-h100`. To cap one partition size of a device, add the partition: `A100/1g.5gb=4`. ### GPUs without a type `--max-accelerators nvidia_gpu=N` caps the GPUs requested without a device type. `gpu` works as a shorter name for `nvidia_gpu`. ```bash # At most 8 GPUs requested without a type, and separately at most 10 H100s flyte create queue mixed-gpu \ --run-concurrency 50 \ --action-concurrency 500 \ --max-accelerators nvidia_gpu=8 \ --max-accelerators H100=10 ``` The two caps are independent. A task that asks for `gpu=1` counts against the `nvidia_gpu` cap. A task that asks for `H100:1` counts against the H100 cap and not against the `nvidia_gpu` cap. In the example, the queue can have 8 untyped GPUs and 10 H100s scheduled at the same time. One queue can combine the `nvidia_gpu` cap with caps on several device types, including TPUs and partition sizes: ```bash flyte create queue mixed-gpu \ --run-concurrency 50 \ --action-concurrency 500 \ --max-accelerators nvidia_gpu=8 \ --max-accelerators H100=10 \ --max-accelerators V6E=10 \ --max-accelerators A100/1g.5gb=4 \ --scheduling greedy_capacity ``` `flyte get queue mixed-gpu` lists all four under `max_accelerators`. In Python, read them from `Queue.max_accelerators`: ```python from flyteplugins.union.remote import Queue queue = Queue.get("mixed-gpu") print(queue.max_accelerators) # {'nvidia_gpu': 8, 'nvidia_gpu/nvidia-h100': 10, # 'google_tpu/google-tpu-v6e': 10, 'nvidia_gpu/nvidia-a100/1g.5gb': 4} ``` Only NVIDIA GPUs can be capped without a device type. Cap TPUs and other accelerators per device: `--max-accelerators google_tpu=8` is refused. A TPU or other non-NVIDIA accelerator requested without a device is not limited by any queue cap. Two cases change which cap an untyped request counts against: - With **Clusters and queues > Resource caps and scheduling > Resource-aware scheduling**, the scheduler chooses a device for an untyped request. If it chooses a device that has its own cap, the request counts against that cap as well. On a cluster with T4, L4, and A10G nodes and a queue that caps L4s, a `gpu=1` task that the scheduler assigns to an L4 counts against both the `nvidia_gpu` cap and the L4 cap. Without resource-aware scheduling, an untyped request counts against the `nvidia_gpu` cap only. - If a default GPU type is set in Settings, an untyped request is treated as a request for that type. It counts against that type's cap, not against the `nvidia_gpu` cap. ## Set caps on a queue Set caps and the scheduling policy when you create a queue, or change them later. ### CLI ```bash # Create a queue with caps flyte create queue research \ --run-concurrency 100 \ --action-concurrency 1000 \ --max-resources cpu=512 \ --max-resources memory=4Ti \ --max-accelerators nvidia_gpu=8 \ --max-accelerators H100=48 \ --scheduling greedy_capacity # Change the caps on an existing queue flyte update queue research --max-resources cpu=768 --max-resources memory=6Ti flyte update queue research --max-accelerators nvidia_gpu=16 --max-accelerators H100=64 # Remove the caps flyte update queue research --clear-max-resources flyte update queue research --clear-max-accelerators # Change the scheduling policy flyte update queue research --scheduling strict_fifo ``` `flyte update queue --edit` opens the whole queue in your `$EDITOR`, including `max_resources`, `max_accelerators`, and `scheduling`. ### Programmatic ```python from flyteplugins.union.remote import Queue # Create a queue with caps Queue.create( "research", run_concurrency=100, action_concurrency=1000, max_resources={"cpu": "512", "memory": "4Ti"}, max_accelerators={"nvidia_gpu": 8, "H100": 48}, scheduling="greedy_capacity", ) # Change the caps on an existing queue Queue.update("research", max_resources={"cpu": "768", "memory": "6Ti"}) Queue.update("research", max_accelerators={"nvidia_gpu": 16, "H100": 64}) # Remove the caps Queue.update("research", max_resources={}) Queue.update("research", max_accelerators={}) # Change the scheduling policy Queue.update("research", scheduling="strict_fifo") ``` ### Console Go to **Settings > Queues**. The **New Queue** form and a queue's edit form have a **Scheduling policy** choice and **Resource caps** fields for CPU, memory, and ephemeral storage. The console does not edit GPU caps yet: set `--max-accelerators` from the CLI or Python. Editing a queue in the console keeps its GPU caps as they are. The form's **Scheduling policy** starts at **Default**, which creates the queue with no policy (`unspecified`): it orders actions by project and domain, round-robin, not first come, first served. Choose **Strict FIFO** or **Greedy capacity** to get the behavior described below. > [!WARNING] An update replaces every cap of the same kind > `--max-resources` on `flyte update queue` replaces all of the queue's resource > caps, so a resource you leave out becomes unlimited. To raise CPU on a queue > that also caps memory, pass both. `--max-accelerators` works the same way: to > change the H100 cap on a queue that also caps T4s and `nvidia_gpu`, pass all > three. The two settings do not affect each other. Changing > `--max-accelerators` leaves `--max-resources` as it is. > > In Python, passing `None` for `max_resources` or `max_accelerators` keeps the > current caps, a mapping replaces them, and `{}` removes them. ### Changes apply to a live queue You can change a queue's caps and scheduling policy without draining it. The scheduler picks up the new values shortly after the update and uses them for everything it schedules from then on. If you raise a cap, waiting actions are scheduled as soon as they fit. If you lower a cap below what is in use, running actions are not interrupted, and the queue schedules nothing new for that resource until enough work finishes to bring usage under the cap. If you lower a cap below what a single waiting action asks for, that action becomes **Clusters and queues > Resource caps and scheduling > Infeasible requests fail fast** and fails. ## See how much of a cap is in use A queue reports usage next to each cap. ### CLI ```bash # One queue: settings plus a usage bar for each cap flyte get queue research # The same view, updating live flyte get queue research --watch # Every live queue in one table flyte get queue --watch # Only the queues in one or more pools flyte get queue --watch --pool gpu-pool ``` With a queue name, the output has a bar for each cap showing `used / cap` and a percentage: one per capped resource and one per `--max-accelerators` entry, with `nvidia_gpu` for the GPUs requested without a type. They follow the bars for run concurrency, action concurrency, and depth. A resource without a cap shows its usage with no bar. Without a name, `--watch` shows one row per queue with its pool, scheduling policy, CPU and memory usage against their caps, GPUs in use, runs, actions, the number of waiting actions, and whether the head of the line is blocked. ### Programmatic ```python from flyteplugins.union.remote import Queue metrics = Queue.details("research") print(metrics["in_flight_resources"], metrics["max_resources"]) print(metrics["accelerator_charges"], metrics["max_accelerators"]) print(metrics["scheduling"], metrics["head_blocked"]) # Stream one queue for metrics in Queue.watch("research"): print(metrics["in_flight_resources"]) # Stream every live queue in the given pools (all pools when omitted) for snapshot in Queue.watch_pool(pools=["gpu-pool"]): for metrics in snapshot: print(metrics["pool"], metrics["name"], metrics["in_flight_resources"]) ``` `in_flight_resources` and `max_resources` are `{name: quantity}` mappings. `accelerator_charges` maps each GPU cap to the number of devices counted against it. GPUs requested without a type that no cap covers are counted under `nvidia_gpu`, and other devices with no cap under `other`. ## Choose a scheduling policy The scheduling policy decides what a queue does when the next action in line does not fit, under the queue's caps or on the clusters it routes to. Both policies consider actions in the order they were queued. > [!NOTE] Use `greedy_capacity` for most queues > `greedy_capacity` keeps capacity in use and keeps reusable containers busy. > Choose `strict_fifo` for queues that run gang-style jobs or that need strict > first come, first served ordering. > > A new queue is created as `strict_fifo` unless you pass > `--scheduling greedy_capacity`, or `scheduling="greedy_capacity"` in Python. > > The `default` queue and each cluster's co-named queue start with no policy, > and `flyte get queue` shows `unspecified`. Such a queue orders its actions by > project and domain, round-robin, and skips an action that does not fit. To give it a > policy, run `flyte update queue default --scheduling greedy_capacity`. | | Greedy capacity (recommended) | Strict FIFO | |---|---|---| | Setting | `greedy_capacity` | `strict_fifo` | | When the next action does not fit | Skips it and schedules the actions behind it that fit | Stops and waits for it | | Order | First come, first served among the actions that fit | First come, first served (on very deep queues, ordering is best effort) | | Idle capacity while work is waiting | No | Yes, while the head of the line is blocked | | Can a large action be starved? | Yes, while smaller actions keep fitting | No | | Reusable containers (warm pools) | Actions for a running warm pool keep being scheduled | Actions for a running warm pool wait behind the blocked head | | Use it for | Most queues | Gang-style jobs and strict ordering | ### An example A queue is capped at 8 GPUs and 6 are in use, so 2 are free. Three actions are waiting, in this order: | Position | Action | Asks for | Greedy capacity | Strict FIFO | |---|---|---|---|---| | 1 | `train` | 4 GPUs | Waits. It does not fit in the 2 free GPUs. | Waits. It does not fit in the 2 free GPUs. | | 2 | `evaluate` | 1 GPU | Scheduled now. | Waits behind `train`. | | 3 | `embed` | 1 GPU | Scheduled now. | Waits behind `train`. | Under greedy capacity the queue runs at 8 of 8 GPUs, and `train` starts once 4 GPUs are free at the same moment. Under strict FIFO the queue stays at 6 of 8 until 2 more GPUs free up. Then `train` starts, followed by `evaluate` and `embed`. ### Greedy capacity Set with `--scheduling greedy_capacity`. The queue goes through the line in arrival order. When an action does not fit, the queue moves on to the next one and schedules every action that fits. Use it for queues that carry a mix of small and large actions, for work that runs in reusable containers, and when you want the capacity you pay for to stay in use. A very large action can wait a long time when smaller ones keep arriving and keep fitting. If a queue carries both, move the large jobs to their own strict FIFO queue, or give them a **Tasks > Configure tasks > Retries and timeouts > Timeouts > `max_queued_time`: fail fast when capacity isn't available** so they fail after a set wait. ### Strict FIFO Set with `--scheduling strict_fifo`. The queue schedules actions in arrival order. When the action at the head of the line does not fit, the queue schedules nothing behind it until it does. On a very deep queue, the order is best effort: the scheduler sorts each batch of waiting actions it reads, not the whole queue. As running work finishes, the freed capacity accumulates for the head of the line, and later, smaller actions cannot take it. Use it for gang-style jobs. A distributed training job that needs 32 GPUs at once starts only when 32 are free together. Under greedy capacity, a steady stream of one-GPU actions can take each GPU as it frees up, and the large job never starts. Also use it when work must start in the order it was submitted. Capacity sits idle while the head of the line waits, and every action behind it waits too, including the ones that would fit. ### Reusable containers (warm pools) A **Tasks > Configure tasks > Reusable containers** keeps a pool of warm containers alive and runs many actions in them. A queue counts the pool's containers against its caps, not each action that runs in them. The first action of an environment starts the pool, and it has to fit under the cap at the pool's minimum size. An action that joins a running pool is scheduled without adding to the cap. When the pool scales up to run more actions at once, the queue counts the added containers too, up to the pool's maximum size. A pool that runs on several clusters is counted on each of them. | | Greedy capacity | Strict FIFO | |---|---|---| | Actions for a warm pool that is already running | Scheduled past a blocked action, since joining a running pool adds nothing to the cap | Wait behind the blocked head | | The warm pool while a large action is blocked | Stays busy | Sits idle | | An action that starts a new pool | Scheduled if the pool fits. If it does not fit, the queue moves on to the next action | Scheduled if the pool fits. If it does not fit, it blocks the line | On a strict FIFO queue with little free capacity, one large job at the head of the line stalls every reusable environment on the queue. If an environment has no running actions for longer than its `idle_ttl`, the whole pool can shut down, and the next action then starts cold. Put work that runs in reusable containers on a greedy capacity queue. If the same team also runs gang-style jobs, give those jobs their own strict FIFO queue. ### When the line is blocked A strict FIFO queue reports when its head is blocked and for how long. `flyte get queue --watch` shows a head-of-line banner with the number of actions waiting behind it, and the `flyte get queue --watch` table marks the queue as blocked. In Python, `Queue.details` returns `head_blocked` and `head_blocked_since`. A blocked head clears as running work finishes. To let the waiting actions that fit run now, switch the policy: ```bash flyte update queue research --scheduling greedy_capacity ``` ## Resource-aware scheduling When Union knows each cluster's configuration, a queue schedules against what the clusters can run. The configuration is the cluster's node pools, the size of the nodes in each pool, the accelerators they have, and how far each pool can scale. With it, the scheduler does the following for every action: - It considers only the clusters that can run the action. Each container the action asks for must fit on a node of some node pool in the cluster: its requests fit one node, the pool has its accelerator, and its node selector is compatible with the pool's labels. - It waits when a cluster is full. An action that fits a cluster's node pools but not the room left at full scale stays queued under the queue's scheduling policy. On a strict FIFO queue it blocks the line. - Among the clusters with room, it places the action on the least loaded one. > [!NOTE] Resource-aware scheduling is enabled per organization > It is off until the Union team turns it on for your organization, and it > needs Union to have your cluster configuration. Union BYOC deployments > already have the configuration; for self-managed deployments, the Union team > sets it up. Talk to the Union team to have resource-aware scheduling turned > on for your organization. Without it, a queue treats a cluster as able to run anything > and places work on any healthy cluster it routes to. Resource caps and the > scheduling policy apply either way. ## Infeasible requests fail fast Some requests can never run, however long they wait. An action that asks for 64 CPUs on a queue capped at 32 does not fit even when the queue is empty. On a strict FIFO queue it would also block everything behind it. The scheduler fails such an action as soon as it sees it. With **Clusters and queues > Resource caps and scheduling > Resource-aware scheduling**, the check also covers the clusters. An action then also fails as infeasible when no cluster its queue routes to could ever run it: - It asks for an accelerator that none of those clusters has. - One of its containers is larger than any node those clusters can launch. - Its total request is more than those clusters have at full scale. - The task is interruptible and none of those clusters has a spot node pool it fits. Mark the task non-interruptible, or add a spot node pool. An infeasible action fails with the error code `INFEASIBLE` and is not retried. The error message names the request and what the queue or the clusters offer. Reduce the request, route the task to a different queue, or raise the cap. An action that fits the cap and the clusters, but not the room available right now, stays queued and runs once capacity frees up. To limit that wait, set **Tasks > Configure tasks > Retries and timeouts > Timeouts > `max_queued_time`: fail fast when capacity isn't available** on the task. ## See also - **Clusters and queues > Managing queues**: create, drain, move, and delete queues. - **Tasks > Configure tasks > Queues**: route work to a queue from task code. - **Tasks > Configure tasks > Reusable containers**: how reusable environments are sized. === PAGE: https://www.union.ai/docs/v2/union/user-guide/clusters-and-queues/node-groups === Inspect and update the node groups a cluster declares, the node shapes it can schedule onto. # Node groups > [!NOTE] Requires the `flyteplugins-union` plugin > The `flyte get node-groups` and `flyte update node-groups` commands are > provided by `flyteplugins-union`. Use 0.20.2 or later: with `flyte` 2.12.2 or > later, earlier versions fail to import and the `flyte` CLI drops their > subcommands. Install it with > `pip install 'flyteplugins-union>=0.20.2'`. A cluster's **node groups** are the node shapes it can schedule onto: for each group, the instance types, the node count range, the allocatable CPU and memory of one node, the pod slots per node, accelerators, architecture, capacity types, weight, limits, labels, and taints. Use `flyte get node-groups` to see what a **Clusters and queues > Clusters** declares. On a self-managed cluster, use `flyte update node-groups` to change it (see **Clusters and queues > Node groups > Who can write node groups**). ## Inspect node groups ```bash # Show the node groups as a table flyte get node-groups my-cluster # Show them as JSON flyte -of json get node-groups my-cluster # Save them as YAML, in the format `flyte update node-groups -f` reads flyte get node-groups my-cluster --export > node-groups.yaml ``` The output shows the node groups as stored, including every label and taint. The table has one row per group, with the columns **Name**, **Instance types**, **Nodes**, **Limits**, **Cpu**, **Memory**, **Accelerators**, **Arch**, **Capacity**, **Weight**, **Spot**, **Labels**, and **Taints**. **Nodes** shows `min-max`, or `min+ (no node limit)` when `max_nodes` is `0`. **Limits** shows the group's limits, for example `cpu=20000, nvidia.com/gpu=2`. The exported YAML lists every editable field of each group, using the field names of the `NodeGroup` message: CODE0 `weight` is optional and appears only when a group has one (1 to 100, the Karpenter NodePool weight). `capacity_types` takes `CAPACITY_TYPE_ON_DEMAND`, `CAPACITY_TYPE_SPOT`, and `CAPACITY_TYPE_RESERVED`. `max_pods` and `limits` appear in the output: - `max_nodes: 0` means the group has no node-count bound. Only `limits`, if set, caps it. - `limits` is the Karpenter NodePool `spec.limits`: totals the group may not exceed across all its nodes, as a Kubernetes resource name and a quoted quantity, for example `cpu: '20000'`. The command rejects a bare number before it writes anything, and the control plane rejects a value that isn't a non-negative quantity. - `max_pods` is the number of pod slots on one node of the group. `0` means it isn't recorded. ## Update node groups CODE1 An update **replaces the cluster's complete set** of node groups. A group you leave out of the edited YAML or the file is removed from the cluster. To change one group with `-f`, export the current set, edit it, and apply the whole file. Before it writes, the command prints which groups are added, removed, or changed, by name. If any group would be removed, it asks you to confirm. Pass `--yes` to skip the prompt. If you decline, nothing is written. If the prompt gets no answer (end of input or Ctrl-C), the command fails with `removal of node groups not confirmed; pass --yes to apply non-interactively`. The command refuses these inputs before it writes anything: - **A document that declares nothing.** An empty file, a file with only comments, or `{}` is rejected. To remove every node group, write `node_groups: []`. - **Duplicate names.** Each node group needs a unique name. - **Fields your plugin doesn't know.** If the control plane returns node group fields that your version of `flyteplugins-union` can't represent, writing would drop them, so `update` refuses and tells you to upgrade `flyteplugins-union`. `get --export` prints a warning to stderr and leaves those fields out of the YAML. In the editor, a validation error asks whether to edit again, save the YAML to a file you can apply with `--file`, or abort. Errors that editing can't fix, such as a permission or conflict error, end the command instead. ### Concurrent edits When the control plane reports a generation for the node groups, the editor path sends the generation it read with the write. If the node groups changed in between, the write is refused with `node groups changed since they were read`. Re-run the command to edit the current set. If the control plane reports generation `0` (it doesn't track one, or the node groups have never been written), the editor sends no generation and prints a notice that the last write wins. `-f` never sends a generation: the file always replaces whatever is stored. ### Who can write node groups The control plane decides whether you may write a cluster's node groups. Node groups of a cluster that Union.ai provisions (BYOC) are managed by provisioning, so a write to one is refused, and the CLI shows the control plane's error. A cluster with no recorded type is refused the same way. On a cluster you manage, you need permission to manage that cluster. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns === Patterns for BYO images, monorepos with uv, CI/CD, multi-team resource management, the software development lifecycle, and an advanced end-to-end project. # Project patterns The rest of the user guide explains what Flyte can do. This section explains how we recommend you structure real projects. These are opinionated guides. They represent patterns we've seen work well across many teams and production deployments. If you're starting a new project or scaling an existing one, start here. ### **Project patterns > Bring your own image** Two patterns for teams that own their Docker images and want Flyte for orchestration without handing over their build pipeline. ### **Project patterns > Structuring Flyte projects with uv** How to structure Flyte projects with uv, from single-package setups to multi-team monorepos with shared and independent lockfiles. ### **Project patterns > CI/CD deployments** How to deploy a Flyte project from CI. Uses GitHub Actions as the reference, but the building blocks (API key, `flyte deploy`, commit-pinned versions) translate to any runner. ### **Project patterns > Resource management and multi-team scaling** Projects, domains, quotas, RBAC, and secrets: the primitives to set up before you have ten teams and a noisy-neighbor problem. ### **Project patterns > Software development lifecycle** Automate your own development process with Flyte, using event-driven runs, review and release gates, human approvals, and evaluation gates for systems whose behavior depends on data and models. ### **Project patterns > Advanced project: LLM reporting agent** An advanced guide for building an LLM reporting agent on Flyte. ## Subpages - **Project patterns > Bring your own image** - Two patterns for teams that own their Docker images and want Flyte for orchestration without handing over their build pipeline. - **Project patterns > Structuring Flyte projects with uv** - How to structure Flyte projects with uv, from single-package setups to multi-team monorepos with shared and independent lockfiles. - **Project patterns > CI/CD deployments** - How to deploy a Flyte project from CI. Uses GitHub Actions as the reference, but the building blocks (API key, `flyte deploy`, commit-pinned versions) translate to any runner. - **Project patterns > Resource management and multi-team scaling** - Projects, domains, quotas, RBAC, and secrets: the primitives to set up before you have ten teams and a noisy-neighbor problem. - **Project patterns > Software development lifecycle** - Automate your own development process with Flyte, using event-driven runs, review and release gates, human approvals, and evaluation gates for systems whose behavior depends on data and models. - **Project patterns > Advanced project: LLM reporting agent** - An advanced guide for building an LLM reporting agent on Flyte. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/bring-your-own-image === Two patterns for teams that own their Docker images and want Flyte for orchestration without handing over their build pipeline. # Bring your own image This guide is for teams who own their Docker images and want Flyte for orchestration without handing over their build pipeline. > [!NOTE] > This guide does **not** cover `flyte.Image.from_debian_base()`, the Flyte-managed image builder. It assumes you already have images. ## The multi-team problem Two teams. Two images. One workflow. | | Team A (data-prep) | Team B (training) | |---|---|---| | Base | `python:3.11-slim` | `python:3.10-slim` (prod: CUDA) | | Python | 3.11 | 3.10 | | WORKDIR | `/app` | `/workspace` | | Packages | pandas, pyarrow | torch, numpy | The `prepare` task runs in Team A's container. It processes the input and calls `train`, which runs in Team B's container. One workflow, two images, different filesystem layouts. Two patterns solve this. Pick based on who controls what: | | Pattern 1: Pure BYOI | Pattern 2: Remote Builder | |---|---|---| | Who owns the image? | Each team owns everything | Each team owns the base | | Flyte-aware? | Yes: code is baked in | No: Flyte adapts on top | | Code change = image rebuild? | Yes | No | | Use when | Teams can't let Flyte touch images | Teams can hand off a base | ## Pattern 1: Pure BYOI Teams build complete, Flyte-aware images. Workflow code is COPYed into the Dockerfile. Flyte runs the container as a black box: it sends no code and modifies nothing. ### Dockerfiles Both teams install `flyte` and COPY the shared `workflow_code/` into their image. The only difference is their base, Python version, and WORKDIR. **Team A (data prep):** ```dockerfile # Team A's image: data preparation # # This team owns this entire Dockerfile. They control Python version, WORKDIR, # and PYTHONPATH. Flyte has no say here. # # Pure BYOI constraint: workflow code must be baked in because there is no # code bundle. Every code change requires rebuilding and pushing this image. FROM python:3.11-slim # System deps this team needs RUN apt-get update && apt-get install -y --no-install-recommends \ libpq-dev \ && rm -rf /var/lib/apt/lists/* # Team A's WORKDIR. Python will find modules here because PYTHONPATH includes it. WORKDIR /app # Team A's Python packages. These are their own dependencies โ€” Flyte doesn't # install anything on top in pure BYOI mode. RUN pip install --no-cache-dir \ flyte \ pandas==2.1.4 \ pyarrow==14.0.1 # Bake the workflow code into the image. # In pure BYOI, this is the ONLY way Flyte can find your task functions. # Downside: every edit to tasks.py requires a new image tag + CI build. COPY workflow_code/ /app/workflow_code/ # /app is on PYTHONPATH so `import workflow_code.tasks` resolves at runtime. ENV PYTHONPATH=/app CODE0dockerfile # Team B's image: model training (GPU workload) # # Intentionally different from Team A: # - Different base: CUDA runtime instead of debian slim # - Different Python version: 3.10 (team B's standard) # - Different WORKDIR: /workspace (not /app) # - Different PYTHONPATH: /workspace # - Different system packages: CUDA tools # # Pure BYOI: Flyte injects nothing at runtime. Everything must be baked in. # Each team owns their filesystem layout entirely. # # In practice this would be: # FROM nvidia/cuda:12.1.0-cudnn8-runtime-ubuntu22.04 # Using python:3.10-slim here so you can build/test without a GPU machine. FROM python:3.10-slim RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ && rm -rf /var/lib/apt/lists/* # Team B uses /workspace, not /app. Each team controls their own layout. WORKDIR /workspace RUN pip install --no-cache-dir \ flyte \ torch==2.1.2 \ numpy==1.26.4 # Bake in workflow code at /workspace/workflow_code/. # Python finds it because PYTHONPATH includes /workspace. COPY workflow_code/ /workspace/workflow_code/ # /workspace is on PYTHONPATH โ€” same import path as Team A's image despite # the different WORKDIR. Both images expose `import workflow_code.tasks`. ENV PYTHONPATH=/workspace ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/pure_byoi/training/Dockerfile* Both expose `import workflow_code.tasks` at runtime because each image's PYTHONPATH points to its own WORKDIR where the code was COPYed. ### Build and push The build context is the `pure_byoi/` directory so that `workflow_code/` is available to both Dockerfiles: CODE1 ### Python code **Environment definitions**. Image names are specified via `from_ref_name()`: CODE2 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/pure_byoi/workflow_code/envs.py* `from_ref_name()` is a placeholder resolved at runtime. The actual URIs are passed in the entry point via `init_from_config(images=...)`. This is necessary because the envs file is COPYed into both images. Hardcoding a URI would create a circular reference. **Task definitions:** CODE3 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/pure_byoi/workflow_code/tasks.py* **Entry point**. This is where image URIs are wired in: CODE4 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/pure_byoi/main.py* ### Run and deploy CODE5 There is no separate deploy step. The image tag is the version. To ship a code change: edit tasks, rebuild both images, push new tags, update the tag constants in `main.py`, run again. ## Pattern 2: Remote builder Teams hand you their base images. They built these images for their own purposes. Flyte was never a consideration. Your job is to adapt them. > [!TIP] > Want Union to optimize your images so image pulls for a new image (cold-start) drops from minutes to under a second? See [Layering on top of an existing image build](cicd.md#layering-on-top-of-an-existing-image-build) for the equivalent flow when your base is built in CI. ### The base images **Team A** uses `continuumio/miniconda3` as their base: CODE6 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/remote_builder/data_prep/Dockerfile* - Python at `/opt/conda/bin/python` (conda manages this) - conda's Dockerfile already adds `/opt/conda/bin` to `PATH` - No PYTHONPATH set - WORKDIR `/app` **Team B** uses `python:3.10-slim` with a pip venv at `/opt/venv`: CODE7 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/remote_builder/training/Dockerfile* - Python at `/opt/venv/bin/python` - `PATH` does **not** include `/opt/venv/bin`: the venv was created but never activated - No PYTHONPATH set - WORKDIR `/workspace` ### Adapting with `flyte.Image` `flyte.Image.from_base()` takes the base URI and lets you layer on top. This is where the adaptation happens: CODE8 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/remote_builder/tasks/envs.py* **Team A** only needs `flyte` installed and `PYTHONPATH` set. conda's PATH is already correct. **Team B** needs three things: `flyte` installed in the venv, `PATH` updated so the venv's `python` is the default, and `PYTHONPATH` set. `$PATH` in an `ENV` instruction expands at Docker build time. `.with_code_bundle()` tells Flyte to inject task source at runtime (dev) or bake it into the image at deploy time (prod). ### Task definitions CODE9 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/remote_builder/tasks/tasks.py* ### Entry point CODE10 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/bring-your-own-image/remote_builder/main.py* ### Run and deploy CODE11 During development you only rebuild the base image when the Dockerfile changes. Code changes are free: they travel as a tarball at runtime. ### Base image USER and WORKDIR requirements The remote builder honors whatever `USER` and `WORKDIR` your base image declares โ€” it does not override them. The runtime extracts the code bundle into the container's `WORKDIR` at the start of every task, so the resolved `USER` needs to be able to read, write, and traverse that directory. #### What the runtime needs The container's working directory must satisfy all three for the resolved `USER`: | Permission | Why | |---|---| | `+x` (traverse) | The runtime stats the bundle path before extracting. | | `+w` (write) | `tar -xvf` writes the extracted bundle here. | | `+r` (read) | Subsequent imports resolve from this directory. | A base image with `USER root` (or no `USER` declared) trivially satisfies this. Hardened bases that ship a non-root `USER` (UBI `nonroot` uid `65532`, distroless `nonroot`, chainguard `nonroot`) are fine **as long as their `WORKDIR` is a path that user owns** โ€” for example `/home/nonroot`, `/app`, or `/workspace`. The trap is when a hardened base image leaves `WORKDIR` empty or set to `/root`: that path is typically owned by `root` with mode `0700`, and the non-root `USER` cannot use it. #### What you'll see The remote builder logs the resolved runtime identity at the end of every build: CODE12 If the resolved `USER` and `WORKDIR` are incompatible (non-root `USER` with `WORKDIR` set to `""`, `/`, or `/root`), the builder emits a warning naming the problem and pointing here. **Fix the base image when you see this warning.** If you ignore it, your tasks will fail at start with: CODE13 inside `flyte._internal.runtime.entrypoints.download_code_bundle`. The runtime does not paper over the misconfiguration โ€” there is no silent fallback path. #### Inspecting your base image `docker inspect ` shows the two fields you need to reconcile: CODE14 In that example, `User` is non-root but `WorkingDir` is `/root` โ€” the runtime warning will fire. Fix the base image's Dockerfile so the runtime `USER` actually owns its `WORKDIR`. > [!WARNING] > **`USER` must come *before* `WORKDIR` in your Dockerfile.** BuildKit's `WORKDIR` directive creates the directory if it doesn't exist, and it inherits ownership from the *currently active `USER`*. So this works: > > CODE15 > > But these silently produce a root-owned WORKDIR that the runtime can't write to: > > CODE16 > > CODE17 > > In both broken cases the OCI config shows `WorkingDir: "/home/nonroot"` (so the build-time WARN won't fire โ€” the path itself isn't on the blocklist), but at runtime the resolved `nonroot` user can't write the code bundle into a directory it doesn't own. Three patterns that work โ€” pick whichever fits your base: CODE18 CODE19 CODE20 To verify a built image's WORKDIR ownership before deploying: CODE21 The `.` line should show the directory's owner matching the `id` user. If owner is `root` and you're not running as root, the runtime cannot write there โ€” re-order your Dockerfile so `USER` comes before `WORKDIR`. #### If you cannot modify the base image If you do not control the base image, override its `WORKDIR` with `.with_workdir()` and point it at a path the declared `USER` already owns (commonly `/home/`, created by `useradd -m` in the base): CODE22 > [!WARNING] > `.with_commands()` runs as the base image's declared `USER` โ€” there is no `--user=root` escape hatch. Telling customers to layer `chmod 0755 /root && chown 65532:65532 /root` via `.with_commands()` looks plausible but fails the build with: > > CODE23 > > because non-root users cannot change ownership of root-owned paths. Use `.with_workdir()` to redirect the WORKDIR instead, or modify the base image. First confirm the target path exists and is owned by the declared `USER`: CODE24 If `/home/` does not exist either (some hardened bases ship neither `/home/` nor a writable `WORKDIR`), there is no workaround that stays inside the Flyte build โ€” you must publish a new base image whose `WORKDIR` is owned by the declared `USER`. ## Decision matrix | Scenario | Pattern | |---|---| | Teams own full images, can't let Flyte touch them | Pure BYOI | | Teams hand off a base image (no Flyte knowledge required) | Remote Builder | | Code change should not require image rebuild | Remote Builder + `with_code_bundle()` | | Base has non-standard Python location | `.with_commands()` to fix PATH before Flyte uses it | | Base runs as a non-root `USER` | Make sure base's `WORKDIR` is owned by that `USER`; if not, use `.with_workdir("")` to redirect (see above) | | Production deploy, self-contained containers | `copy_style="none"` in `flyte.deploy()` | === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/monorepo-with-uv === How to structure Flyte projects with uv, from single-package setups to multi-team monorepos with shared and independent lockfiles. # Structuring Flyte projects with uv ## The two layers Every Flyte + uv project involves two distinct layers. Understanding this distinction is the foundation for every decision that follows. **The image** (slow-changing): the Python environment, installed packages, system dependencies, the interpreter. The SDK computes an MD5 hash of the image's layer stack and only rebuilds when a layer actually changes. **The code bundle** (fast-changing): your task source code, packaged as a tarball and uploaded on every run. The container downloads and unpacks it at startup. ``` +-----------------------------------+ | Docker Image (slow path) | | Python interpreter | | Installed packages (uv sync) | <- rebuilt only when deps change | System packages (apt) | | Content-hashed, registry-cached | +-----------------------------------+ | Code Bundle (fast path) | | Your task source files | <- uploaded on every run | Local library code | | Tarball extracted at startup | +-----------------------------------+ ``` Keep these two layers separate. Your image definition should describe only the environment. Source code travels in the code bundle (in fast-deploy mode) or gets baked in at deploy time (in full-build mode). Violating this principle (copying source into the image with `with_source_folder()` or using `install_project` mode for local code) means your image hash changes on every code edit, causing a full Docker build and push on every iteration. ## How the image gets built `flyte.Image` is a frozen, content-addressed layer stack. Each `.with_*()` call appends an immutable layer. The final image tag is an MD5 hash of all layers. The primary method for uv projects is `.with_uv_project()`: ```python image = flyte.Image.from_debian_base().with_uv_project( pyproject_file=Path("my_app/pyproject.toml"), ) ``` **Two installation modes:** - `dependencies_only` (default): Only `pyproject.toml` and `uv.lock` are included in the build context. The image hash covers only these two files. Your code does not affect the image hash. - `install_project`: The entire project directory is copied into the build context. Any code change triggers a full image rebuild. Use this only when you need the project installed as a proper package (e.g., when you need package entry points or compiled extension modules). ## `with_code_bundle()`: one image for dev and prod `with_code_bundle()` is how you write an image definition that works for both development and production without changing any code. ```python image = ( flyte.Image.from_debian_base() .with_uv_project(pyproject_file=Path("pyproject.toml")) .with_code_bundle() ) ``` Its behavior depends on `copy_style` at run time: - **Fast deploy** (default): `with_code_bundle()` is a no-op. Source travels as a tarball. The image only rebuilds when `pyproject.toml` or `uv.lock` changes. - **Full build** (`copy_style="none"`): `with_code_bundle()` resolves to a `COPY` instruction. Source is baked into the image. This is your production path. ```python # Development flyte.run(my_task) # Production flyte.deploy(my_env, copy_style="none", version="1.2.3") ``` ## `root_dir` `root_dir` tells Flyte where to look when building the code bundle and what path prefix to strip when packaging. **The rule:** set `root_dir` to the directory you would `cd` into before running `python -c "import my_module"`. For **src-layout** projects, set `root_dir` to `src/`: ```python flyte.init_from_config(root_dir=Path(__file__).parent.parent) # -> src/ ``` For **flat layout** projects, set `root_dir` to the project root: ```python flyte.init_from_config(root_dir=Path(__file__).parent) # -> my_project/ ``` ## Monorepo patterns Three patterns cover most cases: | | Pattern A: Shared Lockfile | Pattern B: Independent Packages | Pattern C: uv workspace | |---|---|---|---| | Lockfile | One `uv.lock` for everything | Each package has its own | One `uv.lock` for the whole workspace | | Package model | Single package; libraries are modules under one `src/` | Separate, independently-locked packages | Multiple installable members sharing the root lockfile | | Sibling code reaches the container via | Code bundle (fast deploy) | `with_source_folder()` baked into the image | Code bundle, `root_dir` = workspace root (fast deploy) | | Use when | Packages developed together, shared dep graph | Different release cadences, fully independent | Multiple versioned packages developed and locked together | ### Pattern A: Shared lockfile (recommended) All packages live under one `src/` directory with a single `pyproject.toml` and `uv.lock`. Tasks install different subsets via dependency groups. ``` workspace_root/ โ”œโ”€โ”€ pyproject.toml <- defines dependency groups โ”œโ”€โ”€ uv.lock <- one lockfile for everything โ””โ”€โ”€ src/ โ”œโ”€โ”€ workspace_app/ โ”‚ โ”œโ”€โ”€ main.py โ”‚ โ””โ”€โ”€ tasks/ โ”‚ โ”œโ”€โ”€ envs.py โ”‚ โ”œโ”€โ”€ etl_tasks.py โ”‚ โ””โ”€โ”€ ml_tasks.py โ”œโ”€โ”€ lib_transforms/ โ”‚ โ””โ”€โ”€ ops.py โ””โ”€โ”€ lib_models/ โ””โ”€โ”€ baseline.py ``` **`pyproject.toml`**: only external PyPI deps in dependency groups. Local libraries travel via the code bundle: ```toml [project] name = "workspace-app" version = "0.1.0" description = "uv workspace monorepo example for Flyte" requires-python = ">=3.11" dependencies = ["flyte>=2.0"] [build-system] requires = ["uv_build>=0.9,<0.10"] build-backend = "uv_build" [tool.uv] package = true [dependency-groups] # Only external PyPI deps. lib_transforms and lib_models live under src/ alongside # workspace_app and are included in the code bundle automatically. etl = ["pandas"] ml = ["scikit-learn"] dev = ["pytest", "ruff"] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/01_workspace_monorepo/pyproject.toml* **Per-task images using dependency groups:** ```python import pathlib import flyte WORKSPACE_ROOT = pathlib.Path(__file__).parent.parent.parent.parent # -> 01_workspace_monorepo/ etl_env = flyte.TaskEnvironment( name="etl", resources=flyte.Resources(memory="512Mi", cpu="1"), image=flyte.Image.from_debian_base() .with_uv_project( pyproject_file=WORKSPACE_ROOT / "pyproject.toml", extra_args="--only-group etl", ) .with_code_bundle(), ) ml_env = flyte.TaskEnvironment( name="ml", resources=flyte.Resources(memory="1Gi", cpu="1"), image=flyte.Image.from_debian_base() .with_uv_project( pyproject_file=WORKSPACE_ROOT / "pyproject.toml", extra_args="--only-group ml", ) .with_code_bundle(), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/01_workspace_monorepo/src/workspace_app/tasks/envs.py* Both `etl_env` and `ml_env` point to the same `pyproject.toml` but install different dependency groups. The `extra_args` string is included in the image hash, so they produce separate images. **ETL tasks** (use the shared `lib_transforms` library): ```python from lib_transforms.ops import normalize from workspace_app.tasks.envs import etl_env @etl_env.task async def load_data(n: int) -> list[float]: """Simulate loading raw data.""" return [float(i * 1.5) for i in range(n)] @etl_env.task async def transform_data(raw: list[float]) -> list[float]: """Normalize raw data.""" return normalize(raw) @etl_env.task async def etl_pipeline(n: int) -> list[float]: """Load and normalize data end-to-end.""" raw = await load_data(n=n) return await transform_data(raw=raw) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/01_workspace_monorepo/src/workspace_app/tasks/etl_tasks.py* **ML tasks** (use the shared `lib_models` library): ```python from lib_models.baseline import predict, train_mean_predictor from workspace_app.tasks.envs import ml_env @ml_env.task async def train(features: list[float], labels: list[float]) -> dict: """Train a simple model.""" return train_mean_predictor(features, labels) @ml_env.task async def evaluate(model: dict, features: list[float]) -> float: """Evaluate the model on a set of features.""" return predict(model, features) @ml_env.task async def ml_pipeline(features: list[float], labels: list[float]) -> float: """Train and evaluate a model end-to-end.""" model = await train(features=features, labels=labels) return await evaluate(model=model, features=features) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/01_workspace_monorepo/src/workspace_app/tasks/ml_tasks.py* **Entry point**: `root_dir` is set to `src/` so the code bundle covers all packages: ```python import pathlib import flyte from workspace_app.tasks.etl_tasks import etl_pipeline from workspace_app.tasks.ml_tasks import ml_pipeline SRC_DIR = pathlib.Path(__file__).parent.parent # -> 01_workspace_monorepo/src/ if __name__ == "__main__": flyte.init_from_config(root_dir=SRC_DIR) features = [1.5, 3.0, 4.5, 6.0, 7.5] labels = [0.0, 1.0, 2.0, 3.0, 4.0] # Development: fast deploy (code bundle delivers source at runtime) etl_run = flyte.run(etl_pipeline, n=10) print(f"ETL run: {etl_run.url}") ml_run = flyte.run(ml_pipeline, features=features, labels=labels) print(f"ML run: {ml_run.url}") # Production: bake source into the image (uncomment and set a version) # flyte.deploy(etl_env, copy_style="none", version="1.0.0") # flyte.deploy(ml_env, copy_style="none", version="1.0.0") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/01_workspace_monorepo/src/workspace_app/main.py* ### Pattern B: Independent packages Each package has its own `pyproject.toml` and `uv.lock`. Fully independent image builds. ``` repo_root/ โ”œโ”€โ”€ pyproject.toml <- dev-only convenience (optional) โ”œโ”€โ”€ my_app/ โ”‚ โ”œโ”€โ”€ pyproject.toml <- lists external deps + my-lib as editable path dep โ”‚ โ”œโ”€โ”€ uv.lock <- deployment lockfile โ”‚ โ””โ”€โ”€ src/my_app/ โ”‚ โ”œโ”€โ”€ env.py โ”‚ โ”œโ”€โ”€ main.py โ”‚ โ””โ”€โ”€ tasks.py โ””โ”€โ”€ my_lib/ โ”œโ”€โ”€ pyproject.toml โ””โ”€โ”€ src/my_lib/ โ””โ”€โ”€ stats.py ``` **Root `pyproject.toml`**: dev-only, installs both packages as editable for local development: ```toml [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [project] name = "sibling-packages-dev" version = "0.1.0" description = "Dev-only root: installs both packages as editable for local development" requires-python = ">=3.11" dependencies = ["my-app", "my-lib"] [tool.uv.sources] my-app = { path = "my_app", editable = true } my-lib = { path = "my_lib", editable = true } [tool.hatch.build.targets.wheel] packages = [ "my_app/src/my_app", "my_lib/src/my_lib", ] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/02_sibling_packages/pyproject.toml* **`my_app/pyproject.toml`**: declares `my-lib` as an editable path dep: ```toml [project] name = "my-app" version = "0.1.0" description = "Flyte app" requires-python = ">=3.11" dependencies = ["flyte>=2.0", "my-lib"] [tool.uv] package = true [tool.uv.sources] my-lib = { path = "../my_lib", editable = true } [build-system] requires = ["uv_build>=0.9,<0.10"] build-backend = "uv_build" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/02_sibling_packages/my_app/pyproject.toml* **Image definition**: sibling library baked into the image via `with_source_folder()`: ```python import pathlib import flyte MY_APP_ROOT = pathlib.Path(__file__).parent.parent.parent # -> my_app/ MY_LIB_PKG = MY_APP_ROOT.parent / "my_lib" / "src" / "my_lib" # -> my_lib/src/my_lib/ env = flyte.TaskEnvironment( name="my_app", resources=flyte.Resources(memory="256Mi", cpu="1"), # my_lib is an editable path dep in pyproject.toml (so uv_build can find its source # during image build). Its package files are also baked into the image at /root/my_lib/ # via with_source_folder, so they're importable at runtime without relying on the # editable install's .pth file (which points to a build-stage-only path). image=flyte.Image.from_debian_base() .with_uv_project(pyproject_file=MY_APP_ROOT / "pyproject.toml") .with_source_folder(MY_LIB_PKG) .with_code_bundle(), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/02_sibling_packages/my_app/src/my_app/env.py* `with_source_folder(MY_LIB_PKG)` copies the `my_lib` package directory into the image at `/root/my_lib/`. This is necessary because the editable install's `.pth` file points to a path that only exists during the image build stage. The `my_lib` layer is part of the image hash, so the image rebuilds when `my_lib` changes: correct behavior for a dependency. **Task definitions:** ```python from my_app.env import env @env.task async def compute_stats(values: list[float]) -> dict: """Compute basic statistics using the my_lib utility library.""" from my_lib.stats import mean, std return { "mean": mean(values), "std": std(values), "count": len(values), } @env.task async def summarize(stats: dict) -> str: return f"n={stats['count']}, mean={stats['mean']:.2f}, std={stats['std']:.2f}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/02_sibling_packages/my_app/src/my_app/tasks.py* **Entry point**: `root_dir` covers only `my_app` source; `my_lib` is baked into the image: ```python import pathlib import flyte from my_app.env import env from my_app.tasks import compute_stats, summarize MY_APP_ROOT = pathlib.Path(__file__).parent.parent.parent # -> my_app/ SRC_DIR = MY_APP_ROOT / "src" # -> my_app/src/ @env.task async def stats_pipeline(values: list[float]) -> str: stats = await compute_stats(values=values) return await summarize(stats=stats) if __name__ == "__main__": # my_lib is installed in the image; root_dir only needs to cover my_app source flyte.init_from_config(root_dir=SRC_DIR) # Development -- run a task directly, code bundle handles source delivery run = flyte.run(stats_pipeline, values=[1.0, 2.0, 3.0, 4.0, 5.0]) print(f"Run URL: {run.url}") # Production -- deploy an environment with source baked into the image # flyte.deploy(env, copy_style="none", version="1.0.0") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/project-patterns/monorepo-with-uv/02_sibling_packages/my_app/src/my_app/main.py* ### Pattern C: uv workspace (`[tool.uv.workspace]`) A uv *workspace* is uv's native mechanism for a multi-package repository: several packages share **one root `uv.lock`**, and any package can depend on its siblings through `[tool.uv.sources]` entries marked `{ workspace = true }`. Unlike Pattern A, each member is a real installable package rather than a plain module under a shared `src/`; unlike Pattern B, you manage a single lockfile for the whole tree instead of one per package. Reach for a workspace when your packages are distinct, versioned distributions that are nonetheless developed and locked together. ``` albatross/ โ”œโ”€โ”€ pyproject.toml <- workspace root: [tool.uv.workspace] + shared deps โ”œโ”€โ”€ uv.lock <- ONE lockfile for the whole workspace โ”œโ”€โ”€ src/ โ”‚ โ””โ”€โ”€ albatross/ <- the root package's source โ”‚ โ”œโ”€โ”€ main.py โ”‚ โ””โ”€โ”€ condor/ โ”‚ โ””โ”€โ”€ strategy.py โ””โ”€โ”€ packages/ <- workspace members โ”œโ”€โ”€ bird_feeder/ โ”‚ โ”œโ”€โ”€ pyproject.toml <- member package โ”‚ โ””โ”€โ”€ src/bird_feeder/actions.py โ””โ”€โ”€ seeds/ โ”œโ”€โ”€ pyproject.toml โ””โ”€โ”€ src/seeds/... ``` **Workspace root `pyproject.toml`** โ€” declares the members and wires the sibling packages as workspace sources: ```toml [project] name = "albatross" version = "0.1.0" requires-python = ">=3.12" dependencies = ["bird-feeder"] [tool.uv.sources] bird-feeder = { workspace = true } seeds = { workspace = true } [tool.uv.workspace] members = ["packages/*"] [build-system] requires = ["uv_build>=0.9.3,<0.10.0"] build-backend = "uv_build" [dependency-groups] albatross = ["numpy", "bird-feeder"] ``` `members = ["packages/*"]` includes every package under `packages/`. The `{ workspace = true }` sources tell uv to resolve `bird-feeder` and `seeds` from the workspace instead of PyPI, so a single `uv.lock` covers the whole tree. A member package is an ordinary package that can itself depend on other members: ```toml # packages/bird_feeder/pyproject.toml [project] name = "bird-feeder" version = "0.1.0" requires-python = ">=3.10" dependencies = ["seeds"] [tool.uv] package = true ``` **Building the image** โ€” point `.with_uv_project()` at the *workspace-root* `pyproject.toml`. Because `project_install_mode` defaults to `dependencies_only`, only the workspace's `pyproject.toml` and `uv.lock` enter the build context, so the image rebuilds only when dependencies change โ€” fast registration is preserved. `extra_args` is forwarded to the `uv sync` that installs the dependencies (not to `pip install`), so `uv sync` flags apply โ€” here `--only-group albatross` installs just that dependency group, keeping the image lean: ```python from pathlib import Path from bird_feeder.actions import bird_env, get_feeder from seeds.actions import get_seed import flyte from albatross.condor.strategy import get_strategy UV_WORKSPACE_ROOT = Path(__file__).parent.parent.parent # -> albatross/ env = flyte.TaskEnvironment( name="uv_workspace", image=flyte.Image.from_debian_base().with_uv_project( pyproject_file=UV_WORKSPACE_ROOT / "pyproject.toml", extra_args="--only-group albatross", ), depends_on=[bird_env], ) ``` You do **not** need `with_source_folder()` to bake sibling code into the image (as Pattern B requires): in the default `dependencies_only` build `uv sync` resolves the members `bird-feeder` and `seeds` from the shared `uv.lock` (uv reads the member metadata during the sync), but their **code is not baked into the image** โ€” only `pyproject.toml` and `uv.lock` enter the build context. The sibling source (`from bird_feeder.actions import ...`, `from seeds.actions import ...`) travels in the **code bundle** instead (the entry point below sets `root_dir` to the workspace root, so the bundle packages every member) and is on `sys.path` at runtime. The `[tool.uv.workspace]` config's job is to let uv resolve the siblings from the one lockfile; it does not put their code in the image. **Entry point** โ€” set `root_dir` to the *workspace root* (here `albatross/`), **not** to any single member's `src/`. A workspace spreads its members across several `src/` trees (`src/albatross/`, `packages/bird_feeder/src/`, โ€ฆ), so the workspace root is the one directory whose bundle captures them all โ€” this is the `root_dir` rule from the start of this page applied to a multi-member tree, not an exception to it. With every member's source in the bundle, imports resolve the same way locally and at runtime: ```python @env.task async def albatross_task() -> str: get_feeder() get_strategy() seed = get_seed(seed_name="Sun Flower seed") return f"Get bird feeder and feed with {seed}" if __name__ == "__main__": flyte.init_from_config(root_dir=UV_WORKSPACE_ROOT) run = flyte.run(albatross_task) print(run.url) ``` Each member can define its own `TaskEnvironment` pointing at the same workspace-root `pyproject.toml`; because they all resolve against the one lockfile, their images stay mutually consistent. For production, bake the bundle with `flyte.deploy(env, copy_style="none", version="1.2.3")` exactly as in the other patterns. ## The full build path (production) For production deployments where you need immutable, self-contained images: ```python flyte.deploy(my_env, copy_style="none", version="1.2.3") ``` `with_code_bundle()` on the image resolves to a `COPY` instruction. The image is fully self-contained. Use a deterministic version string: a git commit SHA, a git tag, a CI build number. Avoid auto-generated strings so you can trace which code is in which image. > [!IMPORTANT] > Do not use `install_project` mode for production builds. `install_project` copies the entire project directory into the build context and hashes all of it. Every code change triggers a full image rebuild. `with_code_bundle()` + `copy_style="none"` is more surgical: only the files you select are in the image. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/cicd === How to deploy a Flyte project from CI. Uses GitHub Actions as the reference, but the building blocks (API key, `flyte deploy`, commit-pinned versions) translate to any runner. # CI/CD deployments This guide walks through deploying a Flyte project from CI. It uses GitHub Actions as the reference implementation, but the building blocks (a non-interactive credential, `flyte deploy`, and a commit-pinned version) translate to GitLab CI, Buildkite, CircleCI, or any runner that can run a Python script. The examples below assume the project layout and image definitions from the **Project patterns > Structuring Flyte projects with uv** pattern; that guide covers how to structure `pyproject.toml`, `envs.py`, and task modules in a way that makes the `flyte deploy` commands shown here work cleanly. ## What CI needs to do A deploy pipeline has three jobs: 1. **Install** the project and the `flyte` CLI. 2. **Authenticate** non-interactively against your instance. 3. **Run `flyte deploy`** for every `TaskEnvironment` in your project, pinned to the commit SHA. Everything else (branch protections, approvals, notifications) is generic CI concerns and out of scope. ## Authentication: API keys Locally, `flyte deploy` typically authenticates via a browser login (PKCE). A CI runner has no browser and no human to click through a consent screen, so you need a credential the CLI can use without any prompts: an **API key**. ### Mint the key The `flyte create api-key` command is provided by the `flyteplugins-union` package. Add it to a dev dependency group so it's available locally but not baked into task images: ```toml # pyproject.toml [dependency-groups] dev = ["flyteplugins-union"] ``` Then, from a machine already logged in to your instance: ```bash uv run flyte create api-key --name ci-cd-key ``` The output is a single base64-encoded string of the form `endpoint:client_id:client_secret:org`. **It's shown only once**: copy it immediately. The creation call doesn't take a permissions argument: the key is created under the caller's organization and identity context. If you need the key's privileges to be narrower than the minting user's, assign a dedicated role or policy to the key's identity using `flyte create role`, `flyte create policy`, and `flyte create assignment`. ### Store the key as a CI secret Add the string to your CI system's secret store. However it's configured, the secret needs to: - Be exposed to the deploy job as an environment variable named `FLYTE_API_KEY`. - Be masked in logs (most CI systems do this automatically for secrets). - Be scoped to the branches/environments that actually deploy: typically `main` or a release branch, not every feature branch or fork PR. When `FLYTE_API_KEY` is present in the environment at deploy time, the `flyte` CLI uses it for `ClientSecret` auth, overriding any auth mode configured in `config.yaml`. ### Key scope and rotation The key inherits the permissions of the user who minted it. For CI you typically want a dedicated service identity with narrow scope: deploy rights on the target project/domain only. Rotate on a schedule (90 days is a reasonable default) by running `flyte create api-key` again and updating the secret. ## Project configuration Two files drive `flyte deploy` behavior in CI: `pyproject.toml` (or `uv.lock`) for dependencies, and `config.yaml` for your endpoint and image-builder settings. ### `config.yaml` Save this at `.flyte/config.yaml` (or `config.yaml`) in your repo and check it in. In CI the `flyte` CLI auto-discovers config from the repo checkout: repo-relative paths (`./config.yaml`, `./.flyte/config.yaml`, `/.flyte/config.yaml`) take precedence over any home-directory config, so it's picked up automatically after checkout with no `--config` flag needed. See [the config discovery order](../../api-reference/flyte-sdk/flyte.config/_index#auto) for the full precedence; pass `--config ` only to point at a non-standard location. It supplies the project, domain, and image builder settings, the things the API key doesn't carry: ```yaml admin: endpoint: dns:///.hosted.unionai.cloud image: builder: remote task: project: domain: development ``` ## The GitHub Actions workflow A minimal deploy workflow, one job, one step per `TaskEnvironment`: ```yaml # .github/workflows/deploy.yml name: Deploy to Union on: push: branches: [main] workflow_dispatch: env: FLYTE_PROJECT: my-project FLYTE_DOMAIN: development jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install uv uses: astral-sh/setup-uv@v5 with: enable-cache: true - name: Sync dependencies run: uv sync --group etl --group ml --group dev - name: Deploy etl_env env: FLYTE_API_KEY: ${{ secrets.FLYTE_API_KEY }} run: | uv run flyte deploy \ --copy-style none \ --version ${{ github.sha }} \ --project "$FLYTE_PROJECT" \ --domain "$FLYTE_DOMAIN" \ src/workspace_app/tasks/etl_tasks.py etl_env - name: Deploy ml_env env: FLYTE_API_KEY: ${{ secrets.FLYTE_API_KEY }} run: | uv run flyte deploy \ --copy-style none \ --version ${{ github.sha }} \ --project "$FLYTE_PROJECT" \ --domain "$FLYTE_DOMAIN" \ src/workspace_app/tasks/ml_tasks.py ml_env ``` ### Key flag choices - **`--copy-style none`**: bakes source into the image as part of the build layer. Combined with `.with_code_bundle()` on your `flyte.Image` (see **Project patterns > Structuring Flyte projects with uv**), this resolves to a `COPY` instruction so the image is fully self-contained. This is the production path: one immutable artifact per commit, no runtime code bundle download. - **`--version ${{ github.sha }}`**: makes deploys idempotent and traceable. Re-running the same commit produces the same version identifier; tasks already registered at that version are no-ops. - **Path argument points at the task file, not `envs.py`.** `flyte deploy` only imports the file you give it, so tasks decorated with `@env.task` in separate files won't register unless you point at (or transitively import) those files. Pointing at `etl_tasks.py` pulls in `envs.py` via its import chain and runs the `@etl_env.task` decorators. As an alternative, you can point at a directory and pass `--recursive` to load every task module under it in one command. For a `src/` layout project, also pass `--root-dir src` so shared modules like `envs.py` resolve to a single import path instead of being loaded twice: ```yaml - name: Deploy all envs env: FLYTE_API_KEY: ${{ secrets.FLYTE_API_KEY }} run: | uv run flyte deploy \ --copy-style none \ --version ${{ github.sha }} \ --project "$FLYTE_PROJECT" \ --domain "$FLYTE_DOMAIN" \ --root-dir src --recursive src/workspace_app/tasks ``` ### Splitting build from deploy `flyte deploy` builds any missing images before it registers tasks. If you'd rather treat image builds as a separate CI concern (for clearer logs, independent retry, or parallel builds per env), run `flyte build` first and let deploy reuse the result: ```yaml - name: Build etl image env: FLYTE_API_KEY: ${{ secrets.FLYTE_API_KEY }} run: | uv run flyte build \ --copy-style none --root-dir src \ src/workspace_app/tasks/etl_tasks.py etl_env - name: Deploy etl_env env: FLYTE_API_KEY: ${{ secrets.FLYTE_API_KEY }} run: | uv run flyte deploy \ --copy-style none \ --version ${{ github.sha }} \ --project "$FLYTE_PROJECT" --domain "$FLYTE_DOMAIN" \ --root-dir src src/workspace_app/tasks/etl_tasks.py etl_env ``` Image tags are content hashes of the `flyte.Image` definition: `flyte build` pushes `:flyte-`, and `flyte deploy` computes the same hash, sees the image already in the registry, and skips rebuilding. `--copy-style` must match between the two commands; otherwise the hashes diverge and deploy will build again. ## Layering on top of an existing image build If your team already builds container images in CI from a Dockerfile, you can still route them through `flyte build` to get **lazy-loading container pulls**: pod startup that's seconds instead of minutes, regardless of image size. On a 5GB image we measured cold-node pull time drop from ~1m37s to **839ms**, and published benchmarks show 9.9GB CUDA + PyTorch images going from 4m38s to ~1.2s, roughly 240ร—. You get this for free whenever you use `flyte.Image` with the remote builder. Images built outside of it, straight from your own `docker build` and `docker push`, don't get the optimization, which is why this section adds a single `flyte build` step on top of your existing pipeline. How it works: rather than downloading the full image up front, the cluster fetches a small (~14MB) metadata index, mounts the filesystem immediately, and streams file chunks from the registry as the container actually reads them. Files the task never touches never transfer, and chunks are cached on the node so subsequent pulls of the same or related images are sub-second. The CI shape is two stages: your existing job builds and pushes the base, then a follow-up job runs `flyte build` to layer on top and `flyte deploy` to register tasks against the result. ```yaml # .github/workflows/deploy.yml jobs: build-base: runs-on: ubuntu-latest outputs: base_uri: ${{ steps.build.outputs.uri }} steps: # Whatever your team already does to build and push the base image. # Output the full URI tagged with the commit SHA. - id: build run: | ./your-existing-build.sh echo "uri=ghcr.io/myorg/base:${{ github.sha }}" >> "$GITHUB_OUTPUT" deploy: needs: build-base runs-on: ubuntu-latest env: BASE_IMAGE: ${{ needs.build-base.outputs.base_uri }} FLYTE_API_KEY: ${{ secrets.FLYTE_API_KEY }} steps: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v5 - run: uv sync --group dev - run: uv run flyte build --copy-style none --root-dir src src/myproj/envs.py train_env - run: uv run flyte deploy --copy-style none --version ${{ github.sha }} --root-dir src src/myproj/envs.py train_env ``` `envs.py` reads the base URI from the environment, so each commit's overlay is pinned to that commit's base: ```python # src/myproj/envs.py import os import flyte train_env = flyte.TaskEnvironment( name="train", image=flyte.Image.from_base(os.environ["BASE_IMAGE"]).clone( name="train", extendable=True, ), ) ``` > [!NOTE] > This snippet assumes the base image already has the `flyte` SDK installed and your task code on the right `PYTHONPATH`. If it doesn't, see **Project patterns > Bring your own image > Pattern 2: Remote builder** for the `with_commands()` / `with_env_vars()` / `with_code_bundle()` calls that adapt a Flyte-unaware base. The `flyte build` job is idempotent; it skips when the same image content has already been published. Workflow code edits don't trigger image rebuilds; only `envs.py` or base-image changes do. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/resource-management === Projects, domains, quotas, RBAC, and secrets: the primitives to set up before you have ten teams and a noisy-neighbor problem. # Resource management and multi-team scaling This guide covers the foundational primitives Union provides for multi-tenancy (projects, domains, quotas, task-level resources, RBAC, and secrets) and the patterns that work best as you scale to multiple teams. Teams that set these up well early avoid most of the noisy-neighbor, cache-bleed, and resource-starvation problems that surface later. ## Project-domain structure The combination of **project ร— domain** is Union's primary unit of isolation. Each pair gets its own quota budget. RBAC and secrets are flexible: they can be scoped narrowly to a project-domain pair, or broadened across projects, across domains, or organization-wide depending on how you want to share access. ### One project per team or ML product Every independent team or ML product should have its own Union project. Projects are isolated from one another by default, though you can reference workflows or tasks across projects to reuse generalizable resources. ### Domains are environments, not teams Domains are orthogonal to projects. They represent distinct environments (typically development, staging, and production) and enable dedicated configurations, permissions, secrets, cached execution history, and resource allocations for each environment. A production domain in particular ensures a clean slate, so cached executions from development don't produce unexpected behavior in production runs. A common pattern is to split clusters and networking across domains as well: for example, a dedicated production cluster with stricter network controls, separate from the cluster development and staging share. See **BYOC deployment > Multi-cluster and multi-cloud** for how this maps to underlying cloud accounts. ## Resource limits ### Set per-task resource limits per project-domain pair Resource limits are configured through the **Get started > Core concepts > Settings** hierarchy, which resolves through the org โ†’ domain โ†’ project chain. Set them for a whole domain, or narrow them to a single project-domain pair: ```bash # Domain-wide, inherited by every project in the domain flyte edit settings --domain production # Narrowed to one project-domain pair flyte edit settings --domain production --project team-alpha ``` The command opens an editor. Uncomment and set the `task_resource` keys you want: - **`task_resource.max.cpu`**, **`task_resource.max.memory`**, **`task_resource.max.storage`**: hard per-task ceilings. A per-task `flyte.Resources` request above the maximum is **capped to the maximum rather than rejected**. This is how you bound how large any single task in a domain or project can get. - **`task_resource.min.cpu`**, **`task_resource.min.memory`**, **`task_resource.min.storage`**: the default request applied when a task doesn't specify one. - **`task_resource.max.gpu`**, **`task_resource.min.gpu`**: the same ceiling and default, applied to GPU. For scripted or CI setup, apply a YAML file non-interactively instead of opening the editor: ```bash flyte edit settings --domain production --from-file limits.yaml ``` ```yaml task_resource.max.cpu: "8" task_resource.max.memory: 32Gi task_resource.max.gpu: "4" ``` See **Get started > Core concepts > Settings** for the full key list and how inheritance and overrides work. ### Why limits matter These are per-task ceilings, not a namespace-wide aggregate: they bound how large any individual task can get, which keeps a single oversized task from claiming a whole node's worth of capacity. Setting a sane `task_resource.max` per domain (tighter in development, looser in production) is a low-effort guardrail against noisy-neighbor contention. Coordinate the ceilings with whoever sizes tasks so requests stay within them. ## Task-level resources ### Declare resources on the task environment Set resources on a `flyte.TaskEnvironment` (or override per task) using `flyte.Resources`: ```python import flyte env = flyte.TaskEnvironment( name="my_env", resources=flyte.Resources(cpu="4", memory="16Gi", disk="50Gi"), ) @env.task def my_task(): ... ``` If a task requests more than the `task_resource.max` ceiling set for its project-domain, the request is capped to that ceiling rather than rejected, so the task still runs but with the maximum the scope allows. Teams should know the ceilings before sizing tasks. Coordinate with whoever owns the **Get started > Core concepts > Settings** for the scope so requests stay within the ceiling, or so the ceiling gets raised intentionally. ### Be explicit about ephemeral storage By default, `disk` is unset, so no ephemeral-storage request or limit is applied. A task pod can still consume node storage as needed, and it may be evicted if the node comes under storage pressure. Any team doing heavy data processing should always set `disk` explicitly. ## RBAC and secrets ### Roles vs policies Union splits access control into two concepts: - **Roles** are named sets of actions (for example, "can register workflows", "can launch executions"). They describe *what* a principal can do. - **Policies** bind roles to a scope: a specific project-domain pair, a whole domain (across all projects), a whole project (across all domains), or the entire organization. They describe *where* the role applies. This split means you don't have to define roles per project-domain pair. A single "Contributor" role can be bound by one policy to `team-alpha/development`, and by another policy to *every* `production` domain across the organization. Pick the binding scope that matches the access you actually want to grant. A reasonable default: - **Development domains**: bind contributor roles broadly so everyone on the team can register and run workflows. - **Production domains**: restrict to CI/CD service accounts and admins only. See **User management** for the full walkthrough on creating roles, policies, and assignments. ### Scope secrets as narrowly as possible Union supports secrets at the project-domain level, ensuring API keys, tokens, and other sensitive material are only accessible within the workflows that need them. Like RBAC, secrets can also be scoped more broadly when shared across projects or domains, but default to the narrowest scope that satisfies the workflows that need access. ## Multi-team scaling patterns ### Establish naming conventions early Once you have ten or more projects, discoverability degrades quickly. A `-` pattern (for example, `ml-training`, `data-etl`, `inference-serving`) makes quota management, RBAC, and billing attribution substantially easier. ### Put shared utility tasks in a dedicated project If multiple teams need to share preprocessing tasks or model wrappers, create a `shared-utils` or `platform` project rather than duplicating code. Other teams target these without pulling in the implementation by referencing them through the **Tasks > Build tasks > Remote tasks**: ```python import flyte.remote shared_preprocess = flyte.remote.Task.get( "shared-utils.preprocess", # . project="shared-utils", auto_version="latest", ) ``` Without `domain`, the lookup uses the caller's own domain, so deploy the shared tasks to every domain that calls them, or pass `domain=` to pin one. To look the task up, the caller needs the `view_flyte_inventory` action (granted by the Viewer role) on `shared-utils` in that domain. Sharing tasks this way requires governance around versioning and backward compatibility, but it scales better than copy-paste. ### Route work to the right cluster pool in multi-cluster deployments In a multi-cluster deployment, work reaches a cluster through a **Clusters and queues > Managing queues**, which routes to a **Clusters and queues > Cluster pools**. To pin a project or domain's work to a specific pool (for example, a GPU pool), create a queue in that pool and set it as the default queue for the scope: ```bash flyte edit settings --domain production --project team-alpha ``` Set `run.default_queue` to a queue that lives in the target pool: ```yaml run.default_queue: gpu-queue ``` An individual task environment can also target a queue directly with the `queue` parameter. See **Clusters and queues > Managing queues** for how queues bind to pools and clusters. ### Treat production as a managed service Each `/production` pair should have its own quota budget and change-management process. Quota changes in production should go through review rather than ad-hoc CLI updates. The [Union Terraform provider](../../deployment/terraform/_index) is a good fit for this: it lets you manage projects, roles, policies, and access assignments declaratively, so production configuration lives in version control and changes go through PR review like any other infrastructure change. ## Quick reference | Decision | Recommendation | |---|---| | Team isolation | One project per team or ML product | | Environments | Use domains (dev / staging / prod) | | Resource limits | Per-task ceilings via settings, scoped per project-domain | | Task resources | Declare `cpu`, `memory`, and `disk` on `flyte.Resources` and stay within your limits | | Ephemeral storage | Set `disk` explicitly for data-heavy tasks | | RBAC | Bind roles via policies at the scope you actually need (project-domain, domain, project, or org) | | Production access | CI/CD service accounts + admins only | | Secrets | Scope to narrowest project-domain | | Multi-cluster | Route via queues to a cluster pool | | Shared tasks | Put in a dedicated project, target via `flyte.remote.Task` | | Production config | Manage with the Union Terraform provider | | Naming | `-` once you exceed ~10 projects | === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/software-development-lifecycle === Automate your own development process with Flyte, using event-driven runs, review and release gates, human approvals, and evaluation gates for systems whose behavior depends on data and models. # Software development lifecycle The process around your workloads can run on Flyte too. Triage an issue when it is filed, rebuild a dataset when a schema changes, evaluate a model before it is promoted, or wait days for a person to approve a release. As Flyte runs, these chores are typed, retried, observable, and auditable. ## Why data and AI systems need more than CI A conventional software project has one input that changes: code. Everything downstream of a commit is reproducible from that commit, so a pull request fully describes a change and a green build fully answers whether it is safe. A data or AI system has four inputs that change: code, data, models, and prompts. Three of them change without a commit, which breaks the assumptions CI is built on: | CI assumes | For a data or AI system | |---|---| | A change arrives as a diff | A retrained model, a drifted upstream table, or a provider's model update arrives with no diff | | The same input gives the same output | Generative steps are non-deterministic, so two runs of one suite can disagree | | Tests pass or fail | Quality is a distribution. The question is whether the change is worse than what is live by more than the noise | | A build takes minutes and is cheap to repeat | An evaluation can need GPUs, paid API calls, and an hour | | The artifact under test is in the repository | A 40 GB checkpoint is not, and the comparison point is whatever is in production | So the useful gate is rarely "do the tests pass". It is "is this model better than the one serving, on the slice that matters, by more than the run-to-run variance". Answering that takes a pipeline: fan-out over a dataset, GPUs, caching, retries, a readable report, and often a human decision. Running that pipeline on the same orchestrator as production gives you one system, one set of credentials, and one place to look when something goes wrong. ## What Flyte provides The section uses no special lifecycle features. Each need maps to an ordinary part of Flyte: | Need | Use | |---|---| | Start a run from GitHub, Slack, Linear, ClickUp, Jira, or GitLab | [Software development tools](../../../integrations/software-development-tools/_index) | | Start a run on a schedule | [Triggers](../../triggers/_index) | | Launch once per event when a delivery is retried or resent | `run_once`, keyed on the event. See **Project patterns > Software development lifecycle > Event-driven automation > Launch once per event** for the concurrent case. | | Wait for a person, possibly for days | **Tasks > Build tasks > External conditions** | | Keep an expensive gate fast | **Tasks > Configure tasks > Caching**, **Tasks > Build tasks > Fanout**, and per-task **Tasks > Configure tasks > Resources** | | Survive a flaky provider | **Tasks > Configure tasks > Retries and timeouts** | | Trace an output back to its inputs and commit | Run history, task reports, and **Project patterns > Software development lifecycle > Notifications and observability > Track what produced an output** | | Tell a person the result | **Project patterns > Software development lifecycle > Notifications and observability > Notify on a terminal state**, or a Slack message from inside the run | [Artifacts](../../artifacts/_index) add data and model versions to the picture: lineage across runs, and **Triggers > Trigger on new artifact versions** that start the next stage when a new version is published. ## Integrations by stage Most teams use a handful of these. None is required. | Stage | Integrations | |---|---| | Trigger a run from an event | **Software development tools > GitHub**, **Software development tools > Slack**, **Software development tools > Linear**, **Software development tools > ClickUp**, **Software development tools > Jira**, **Software development tools > GitLab** | | Configure the run | [Hydra](../../../integrations/hydra/_index), [OmegaConf](../../../integrations/omegaconf/_index) | | Validate inputs | [Pandera](../../../integrations/pandera/_index) for dataframe contracts, [TypeSafe AI](../../../integrations/typesafe-ai/_index) for typed, confidence-scored model answers | | Test generated code | [Code generation](../../../integrations/codegen/_index), which runs generated code in a sandbox | | Compute | [Ray](../../../integrations/ray/_index), [Spark](../../../integrations/spark/_index), [Dask](../../../integrations/dask/_index), [PyTorch](../../../integrations/pytorch/_index) | | Read from a warehouse | [Snowflake](../../../integrations/snowflake/_index), [BigQuery](../../../integrations/bigquery/_index), [Databricks](../../../integrations/databricks/_index) | | Move data between steps | [Polars](../../../integrations/polars/_index), [Lance](../../../integrations/lance/_index), [JSONL](../../../integrations/jsonl/_index), [Hugging Face](../../../integrations/huggingface/_index) | | Record results | [MLflow](../../../integrations/mlflow/_index), [Weights & Biases](../../../integrations/wandb/_index) | | Report to a reviewer | [Papermill](../../../integrations/papermill/_index), for a parameterized notebook as the gate's output | | Run agents | [Agent frameworks](../../../integrations/agents/_index), with ten SDKs that run as durable tasks | | Observe production | [OpenTelemetry](../../../integrations/opentelemetry/_index), [Grafana Agent](../../../integrations/grafana-agent-observability/_index) | ## Scope of this section - **Deploying from CI** is covered in **Project patterns > CI/CD deployments**: API keys, `flyte deploy`, and commit-pinned versions. This section assumes you have that in place. - **Your CI system stays.** Keep linting, unit tests, and type checking in CI. They are fast and need no cluster. Use Flyte for checks that need real data, real compute, retries, or a person. {{< subpage-cards >}} ## Subpages - **Project patterns > Software development lifecycle > Event-driven automation** - Choose what starts a run, and launch once per event rather than once per delivery. - **Project patterns > Software development lifecycle > Review and release gates** - Gate a change on its way from pull request to production, including changes to a model or dataset that never appear as a diff. - **Project patterns > Software development lifecycle > Human gates and approvals** - Put a person in the loop with a condition, and decide what happens when nobody answers. - **Project patterns > Software development lifecycle > Evaluation gates** - Promote on measured quality instead of a green checkmark, comparing against what is live with enough samples to tell a real change from noise. - **Project patterns > Software development lifecycle > Notifications and observability** - Get a run's outcome to the people who need it, and see what production is doing without reading logs. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/software-development-lifecycle/event-driven-automation === Choose what starts a run, and launch once per event rather than once per delivery. # Event-driven automation Every automation starts with a cause. The cause determines whether the automation runs on time, whether it fires twice, and whether anyone can later tell why it ran. ## Choose the cause | The cause is | Use | |---|---| | A person acted in GitHub, Slack, Linear, ClickUp, Jira, or GitLab | A [software development tool webhook](../../../integrations/software-development-tools/_index). It fires when the action happens and carries who did what. | | Time | A **Triggers > Schedule triggers**. | | Another external system calls you | A [custom provider](../../../integrations/software-development-tools/_index) or a **Apps > Native app integrations > FastAPI app**. | | An outside system needs to drive Flyte itself | A **Apps > Native app integrations > Flyte webhook**, which exposes Flyte's own operations over HTTP. | Use a schedule only when time is the cause, such as a weekly report or a nightly compaction. A nightly job that rebuilds a dataset "after the upstream load finishes" runs late when the load is early, and on stale data when the load is late. Neither failure raises an error. When the cause is new data, use an **Triggers > Trigger on new artifact versions**. Register the upstream output as an artifact, and the downstream run starts when a new version is published. ## Receive a webhook A webhook receiver is an app that verifies each inbound delivery with the sending product's own scheme, normalizes it, and launches a run. One app can serve any combination of the six supported products: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-github[app]>=2.10.6", # ] # /// """GitHub webhook receiver. An app that verifies GitHub deliveries, parses them into `WebhookEvent`s, and launches the tasks in `github_tasks.py`. Deploy those tasks first. Deploy the app, then set the payload URL from its dashboard in GitHub: python github_webhooks.py """ import pathlib # {{docs-fragment app}} import flyte from flyte.extras.webhooks import WebhookAppEnvironment, WebhookEvent, run_once from flyteplugins.github import GitHubProvider, events # Serves the receiver at /webhook/github and a setup dashboard at /. # GITHUB_WEBHOOK_SECRET is mounted automatically. # # `scopes` lists the repositories to act on. Deliveries from other # repositories, or with no repository, are acknowledged but not dispatched. app_env = WebhookAppEnvironment( name="github-webhooks", providers=[GitHubProvider()], scopes=["octo/repo"], image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github[app]"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment app}} # {{docs-fragment handler}} @app_env.on_event(events.PullRequest.OPENED) async def on_pull_request_opened(event: WebhookEvent) -> dict: """Launch triage once per pull request. Retried and resent deliveries have the same `dedupe_key()`, so `run_once` launches only one run for them. Use `await run_once.aio(...)`: the blocking form stalls the app's event loop, and GitHub times out a delivery after ten seconds. """ import flyte.remote as remote task = remote.Task.get(name="github-triage.triage_pr", auto_version="latest") result = await run_once.aio( task, key=event.dedupe_key(), repo=event.scope, number=event.payload["pull_request"]["number"], ) if not result.created: # An earlier delivery of this event already launched a run. return {"skipped": result.run.name, "url": result.run.url} return {"run": result.run.name, "url": result.run.url} # {{/docs-fragment handler}} # {{docs-fragment serve}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployment = flyte.serve(app_env) # The dashboard shows the payload URL to enter in GitHub under # Settings -> Webhooks -> Add webhook. print(f"Setup dashboard: {deployment.url}") # {{/docs-fragment serve}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/github/github_webhooks.py* Each provider's secret is mounted automatically. The dashboard at `/` shows the payload URL to paste into the product's webhook settings. ## Launch once per event Webhook senders retry on any non-2xx response, pollers overlap their windows, and operators re-trigger by hand. Without protection, one pull request can launch four triage runs and leave four comments. `run_once` deduplicates on the event rather than the delivery: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-github[app]>=2.10.6", # ] # /// """GitHub webhook receiver. An app that verifies GitHub deliveries, parses them into `WebhookEvent`s, and launches the tasks in `github_tasks.py`. Deploy those tasks first. Deploy the app, then set the payload URL from its dashboard in GitHub: python github_webhooks.py """ import pathlib # {{docs-fragment app}} import flyte from flyte.extras.webhooks import WebhookAppEnvironment, WebhookEvent, run_once from flyteplugins.github import GitHubProvider, events # Serves the receiver at /webhook/github and a setup dashboard at /. # GITHUB_WEBHOOK_SECRET is mounted automatically. # # `scopes` lists the repositories to act on. Deliveries from other # repositories, or with no repository, are acknowledged but not dispatched. app_env = WebhookAppEnvironment( name="github-webhooks", providers=[GitHubProvider()], scopes=["octo/repo"], image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github[app]"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) # {{/docs-fragment app}} # {{docs-fragment handler}} @app_env.on_event(events.PullRequest.OPENED) async def on_pull_request_opened(event: WebhookEvent) -> dict: """Launch triage once per pull request. Retried and resent deliveries have the same `dedupe_key()`, so `run_once` launches only one run for them. Use `await run_once.aio(...)`: the blocking form stalls the app's event loop, and GitHub times out a delivery after ten seconds. """ import flyte.remote as remote task = remote.Task.get(name="github-triage.triage_pr", auto_version="latest") result = await run_once.aio( task, key=event.dedupe_key(), repo=event.scope, number=event.payload["pull_request"]["number"], ) if not result.created: # An earlier delivery of this event already launched a run. return {"skipped": result.run.name, "url": result.run.url} return {"run": result.run.name, "url": result.run.url} # {{/docs-fragment handler}} # {{docs-fragment serve}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployment = flyte.serve(app_env) # The dashboard shows the payload URL to enter in GitHub under # Settings -> Webhooks -> Add webhook. print(f"Setup dashboard: {deployment.url}") # {{/docs-fragment serve}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/github/github_webhooks.py* How it behaves: - Every run launched this way carries the label `dedupe=`. A launch is refused if a run with that label is live or has succeeded. - Failed, aborted, and timed-out runs don't block a new launch, so re-triggering after a failure retries the work. - `dedupe_key()` includes the provider's timestamp, so a later change to the same resource gets a new key and launches a new run. - The key is a string. Build your own for a different scope, such as one run per thread instead of one per message. > [!WARNING] Make side effects idempotent > `run_once` guarantees one run per event, not one side effect. Two deliveries that arrive at the same moment can both launch, because the label check is a read followed by a launch. > > Where a duplicate would be visible or harmful, such as a second comment or a second charge, make the task idempotent as well. The [ClickUp example](../../../integrations/software-development-tools/clickup.md) reads the current state and does nothing if it is already correct. ## Keep the receiver thin The receiver should verify, decide, and launch. Do the work in the launched task. The receiver is an app with a request deadline: GitHub waits 10 seconds for a response. Work done in the handler isn't retried and doesn't appear as a run. Work done in the launched task is retried, observable, and recorded. - Call `await run_once.aio(...)` in handlers. The blocking form stalls the app's event loop, and under load the receiver stops responding. - Keep the app and the tasks in separate files. Importing a module that constructs a `WebhookAppEnvironment` requires `fastapi`, so a shared file puts `fastapi` in every task image. ## Restrict scopes `scopes` is an allowlist of repositories, channels, teams, lists, or project keys. Events from anywhere else are acknowledged, so the sender stops retrying, but they are not dispatched. Always set `scopes`. Without it, the receiver acts on any repository whose webhook points at it. The webhook secret authenticates the sender, not the repository. Events that carry no scope are also not dispatched. If a webhook seems not to fire, check the product page for where that provider reads its scope from. ## Test in stages When nothing happens, the cause could be credentials, parsing, or networking. Test in this order to separate them: 1. Run the task directly with `flyte run `. This tests the credentials and the logic without a webhook. 2. Replay the plugin's `SAMPLE_DELIVERY`. Every provider plugin ships one, so this tests verification and parsing without a product account. 3. Deploy the receiver and send a real delivery. This tests the remaining wiring. ## See also - **Project patterns > Software development lifecycle > Review and release gates** for what the launched run can do. - [Software development tools](../../../integrations/software-development-tools/_index) for each provider's events and setup. - [Triggers](../../triggers/_index) for schedules. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/software-development-lifecycle/review-and-release-gates === Gate a change on its way from pull request to production, including changes to a model or dataset that never appear as a diff. # Review and release gates A gate is a check that must pass before a change can proceed. CI handles cheap checks well. Use Flyte for the checks that need real data, real compute, or a person, and for changes that never appear as a diff. ## Match the gate to the change | The change is | It arrives as | Gate it with | |---|---|---| | Code | A commit | Lint, type checks, and unit tests, in CI | | Code that changes behavior | A commit | An **Project patterns > Software development lifecycle > Evaluation gates** on real data | | A model, prompt, or dataset | No commit: a training run finished, or an upstream table changed | An evaluation run against what is currently live | For the third kind of change there is no pull request to attach a check to. The gate has to start when the new model or dataset appears, and it has to record its verdict somewhere other than a PR status. Register the model or dataset as an artifact, and use an **Triggers > Trigger on new artifact versions** to start the evaluation when a new version is published. ## Gate a pull request The **Software development tools > GitHub** receives the pull request event and launches a task. The receiver is the one shown in **Project patterns > Software development lifecycle > Event-driven automation > Launch once per event**. The launched task does the work and writes the result back to the pull request. This one labels the pull request by size: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-github[review,auth]>=2.10.6", # "PyGithub>=2", # ] # main = "replay_sample_delivery" # params = "" # /// """Tasks launched by the GitHub webhook receiver. - `triage_pr` labels a pull request by size, calling PyGithub directly. - `gated_merge` uses `review_pr` to pause the run until a person reviews the pull request in the Flyte UI. - `clone_at_head` mints a short-lived GitHub App installation token. `replay_sample_delivery` runs without a GitHub account, webhook, or credentials: flyte run --local github_tasks.py replay_sample_delivery """ import flyte # {{docs-fragment task}} env = flyte.TaskEnvironment( name="github-triage", image=flyte.Image.from_debian_base().with_pip_packages("PyGithub"), # Token for reading the pull request. The webhook secret is mounted on # the receiver app, not here. secrets=[flyte.Secret(key="github-token", as_env_var="GITHUB_TOKEN")], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @env.task async def triage_pr(repo: str, number: int) -> str: """Label a pull request by size.""" import os from github import Auth, Github client = Github(auth=Auth.Token(os.environ["GITHUB_TOKEN"])) pull = client.get_repo(repo).get_pull(number) changed = pull.additions + pull.deletions label = "size/s" if changed < 50 else "size/m" if changed < 500 else "size/l" pull.add_to_labels(label) return label # {{/docs-fragment task}} # {{docs-fragment review-gate}} review_env = flyte.TaskEnvironment( name="github-review", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github[review]"), secrets=[flyte.Secret(key="github-token", as_env_var="GITHUB_TOKEN")], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @review_env.task async def gated_merge(repo: str, number: int) -> str: """Wait for a review decision in the Flyte UI, then act on it. `review_pr` creates a condition carrying the pull request's metadata and waits for a reviewer to answer it. The condition is stored on the backend, so the run survives restarts while it waits. """ from flyteplugins.github import review_pr decision = await review_pr(repo, number, instructions="Block on missing tests.") if decision.is_approved: return f"approved by {decision.reviewer}: {decision.summary}" blocking = ", ".join(c.path for c in decision.blocking_comments) return f"{decision.verdict}: {decision.summary} ({blocking})" # {{/docs-fragment review-gate}} # {{docs-fragment app-token}} agent_env = flyte.TaskEnvironment( name="github-agent", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github[auth]"), # Each key maps to the environment variable `mint_installation_token` # reads (github-app-id -> GITHUB_APP_ID), so `as_env_var=` isn't needed. secrets=[ flyte.Secret(key="github-app-id"), flyte.Secret(key="github-app-installation-id"), flyte.Secret(key="github-app-private-key"), ], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @agent_env.task async def clone_at_head(repo: str) -> str: """Build an authenticated clone URL with a GitHub App installation token. The token expires after one hour. """ import asyncio from flyteplugins.github import clone_url, mint_installation_token # mint_installation_token is synchronous; run it off the event loop. # It returns None if the App credentials are missing. token = await asyncio.to_thread(mint_installation_token) url = clone_url(repo, token) # Never return or log the token itself. return url.replace(token, "***") if token else url # {{/docs-fragment app-token}} # {{docs-fragment replay}} # A separate environment with no secrets, so the replay runs before any # secret is created. replay_env = flyte.TaskEnvironment( name="github-replay", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) @replay_env.task async def replay_sample_delivery() -> dict[str, str]: """Verify and parse the sample delivery bundled with the plugin. `SAMPLE_DELIVERY` is a recorded GitHub payload and a function that signs it. The body is real; the signature header is generated by the plugin. """ import flyteplugins.github as plugin secret = "a-test-signing-secret" sign, body = plugin.SAMPLE_DELIVERY headers = sign(body, secret) assert plugin.verify(body, headers, secret), "a correctly signed delivery must verify" assert not plugin.verify(body, headers, "wrong-secret"), "a bad signature must not" event = plugin.parse(headers, body) return { # Matched by `on_event`. `events.PullRequest.OPENED` equals this string. "qualified_type": event.qualified_type, # Matched against `scopes`. "scope": event.scope or "", "title": event.title or "", "actor": event.actor or "", # The key `run_once` deduplicates on. "dedupe_key": event.dedupe_key(), } # {{/docs-fragment replay}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(replay_sample_delivery) print(run.name) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/github/github_tasks.py* To make the result a required status, have the task publish a check run through the GitHub API (for example, `Repository.create_check_run` in PyGithub), and require that check in branch protection. GitHub accepts check runs only from a GitHub App, so authenticate with an [installation token](#gate-agent-pull-requests) rather than a personal access token. Running the gate as a Flyte task instead of a CI job lets it: - Hold a GPU for only the step that needs it, with per-task [resources](../../tasks/task-configuration/resources.md). - Skip the expensive work on a re-run, with [caching](../../tasks/task-configuration/caching.md). - Run a thousand-case suite in parallel, with [fan-out](../../tasks/task-programming/fanout.md). - Absorb a provider's transient 503 with [retries](../../tasks/task-configuration/retries-and-timeouts.md), instead of failing the build. ## Gate on a person's review `review_pr` pauses a run on a condition that carries the pull request's metadata, waits for a person to answer in the Union.ai UI, and returns a typed verdict: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-github[review,auth]>=2.10.6", # "PyGithub>=2", # ] # main = "replay_sample_delivery" # params = "" # /// """Tasks launched by the GitHub webhook receiver. - `triage_pr` labels a pull request by size, calling PyGithub directly. - `gated_merge` uses `review_pr` to pause the run until a person reviews the pull request in the Flyte UI. - `clone_at_head` mints a short-lived GitHub App installation token. `replay_sample_delivery` runs without a GitHub account, webhook, or credentials: flyte run --local github_tasks.py replay_sample_delivery """ import flyte # {{docs-fragment task}} env = flyte.TaskEnvironment( name="github-triage", image=flyte.Image.from_debian_base().with_pip_packages("PyGithub"), # Token for reading the pull request. The webhook secret is mounted on # the receiver app, not here. secrets=[flyte.Secret(key="github-token", as_env_var="GITHUB_TOKEN")], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @env.task async def triage_pr(repo: str, number: int) -> str: """Label a pull request by size.""" import os from github import Auth, Github client = Github(auth=Auth.Token(os.environ["GITHUB_TOKEN"])) pull = client.get_repo(repo).get_pull(number) changed = pull.additions + pull.deletions label = "size/s" if changed < 50 else "size/m" if changed < 500 else "size/l" pull.add_to_labels(label) return label # {{/docs-fragment task}} # {{docs-fragment review-gate}} review_env = flyte.TaskEnvironment( name="github-review", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github[review]"), secrets=[flyte.Secret(key="github-token", as_env_var="GITHUB_TOKEN")], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @review_env.task async def gated_merge(repo: str, number: int) -> str: """Wait for a review decision in the Flyte UI, then act on it. `review_pr` creates a condition carrying the pull request's metadata and waits for a reviewer to answer it. The condition is stored on the backend, so the run survives restarts while it waits. """ from flyteplugins.github import review_pr decision = await review_pr(repo, number, instructions="Block on missing tests.") if decision.is_approved: return f"approved by {decision.reviewer}: {decision.summary}" blocking = ", ".join(c.path for c in decision.blocking_comments) return f"{decision.verdict}: {decision.summary} ({blocking})" # {{/docs-fragment review-gate}} # {{docs-fragment app-token}} agent_env = flyte.TaskEnvironment( name="github-agent", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github[auth]"), # Each key maps to the environment variable `mint_installation_token` # reads (github-app-id -> GITHUB_APP_ID), so `as_env_var=` isn't needed. secrets=[ flyte.Secret(key="github-app-id"), flyte.Secret(key="github-app-installation-id"), flyte.Secret(key="github-app-private-key"), ], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @agent_env.task async def clone_at_head(repo: str) -> str: """Build an authenticated clone URL with a GitHub App installation token. The token expires after one hour. """ import asyncio from flyteplugins.github import clone_url, mint_installation_token # mint_installation_token is synchronous; run it off the event loop. # It returns None if the App credentials are missing. token = await asyncio.to_thread(mint_installation_token) url = clone_url(repo, token) # Never return or log the token itself. return url.replace(token, "***") if token else url # {{/docs-fragment app-token}} # {{docs-fragment replay}} # A separate environment with no secrets, so the replay runs before any # secret is created. replay_env = flyte.TaskEnvironment( name="github-replay", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) @replay_env.task async def replay_sample_delivery() -> dict[str, str]: """Verify and parse the sample delivery bundled with the plugin. `SAMPLE_DELIVERY` is a recorded GitHub payload and a function that signs it. The body is real; the signature header is generated by the plugin. """ import flyteplugins.github as plugin secret = "a-test-signing-secret" sign, body = plugin.SAMPLE_DELIVERY headers = sign(body, secret) assert plugin.verify(body, headers, secret), "a correctly signed delivery must verify" assert not plugin.verify(body, headers, "wrong-secret"), "a bad signature must not" event = plugin.parse(headers, body) return { # Matched by `on_event`. `events.PullRequest.OPENED` equals this string. "qualified_type": event.qualified_type, # Matched against `scopes`. "scope": event.scope or "", "title": event.title or "", "actor": event.actor or "", # The key `run_once` deduplicates on. "dedupe_key": event.dedupe_key(), } # {{/docs-fragment replay}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(replay_sample_delivery) print(run.name) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/github/github_tasks.py* See [Human gates and approvals](human-gates-and-approvals.md) for timeouts, who may answer, and how long a run can wait. ## Promote the same version Treat a release as a promotion: the same versioned code moves between domains as it passes each gate, instead of being rebuilt for each environment. 1. On every merge, deploy to `development` pinned to the commit, with `flyte deploy --version ${{ github.sha }}`. See [CI/CD deployments](../cicd.md). 2. Run the gate there, against real data. 3. If it passes, promote the same version to `staging`, then to `production`. Deploying the same commit twice produces the same version, and tasks already registered at that version are not registered again. Every run traces back to its commit. If you rebuild for each environment, you can no longer show that what you tested is what you shipped. ## Gate agent pull requests When an agent opens pull requests, change two things. **Credentials.** Authenticate the agent as a GitHub App. It mints a short-lived installation token for each operation instead of holding a personal access token: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-github[review,auth]>=2.10.6", # "PyGithub>=2", # ] # main = "replay_sample_delivery" # params = "" # /// """Tasks launched by the GitHub webhook receiver. - `triage_pr` labels a pull request by size, calling PyGithub directly. - `gated_merge` uses `review_pr` to pause the run until a person reviews the pull request in the Flyte UI. - `clone_at_head` mints a short-lived GitHub App installation token. `replay_sample_delivery` runs without a GitHub account, webhook, or credentials: flyte run --local github_tasks.py replay_sample_delivery """ import flyte # {{docs-fragment task}} env = flyte.TaskEnvironment( name="github-triage", image=flyte.Image.from_debian_base().with_pip_packages("PyGithub"), # Token for reading the pull request. The webhook secret is mounted on # the receiver app, not here. secrets=[flyte.Secret(key="github-token", as_env_var="GITHUB_TOKEN")], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @env.task async def triage_pr(repo: str, number: int) -> str: """Label a pull request by size.""" import os from github import Auth, Github client = Github(auth=Auth.Token(os.environ["GITHUB_TOKEN"])) pull = client.get_repo(repo).get_pull(number) changed = pull.additions + pull.deletions label = "size/s" if changed < 50 else "size/m" if changed < 500 else "size/l" pull.add_to_labels(label) return label # {{/docs-fragment task}} # {{docs-fragment review-gate}} review_env = flyte.TaskEnvironment( name="github-review", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github[review]"), secrets=[flyte.Secret(key="github-token", as_env_var="GITHUB_TOKEN")], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @review_env.task async def gated_merge(repo: str, number: int) -> str: """Wait for a review decision in the Flyte UI, then act on it. `review_pr` creates a condition carrying the pull request's metadata and waits for a reviewer to answer it. The condition is stored on the backend, so the run survives restarts while it waits. """ from flyteplugins.github import review_pr decision = await review_pr(repo, number, instructions="Block on missing tests.") if decision.is_approved: return f"approved by {decision.reviewer}: {decision.summary}" blocking = ", ".join(c.path for c in decision.blocking_comments) return f"{decision.verdict}: {decision.summary} ({blocking})" # {{/docs-fragment review-gate}} # {{docs-fragment app-token}} agent_env = flyte.TaskEnvironment( name="github-agent", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github[auth]"), # Each key maps to the environment variable `mint_installation_token` # reads (github-app-id -> GITHUB_APP_ID), so `as_env_var=` isn't needed. secrets=[ flyte.Secret(key="github-app-id"), flyte.Secret(key="github-app-installation-id"), flyte.Secret(key="github-app-private-key"), ], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @agent_env.task async def clone_at_head(repo: str) -> str: """Build an authenticated clone URL with a GitHub App installation token. The token expires after one hour. """ import asyncio from flyteplugins.github import clone_url, mint_installation_token # mint_installation_token is synchronous; run it off the event loop. # It returns None if the App credentials are missing. token = await asyncio.to_thread(mint_installation_token) url = clone_url(repo, token) # Never return or log the token itself. return url.replace(token, "***") if token else url # {{/docs-fragment app-token}} # {{docs-fragment replay}} # A separate environment with no secrets, so the replay runs before any # secret is created. replay_env = flyte.TaskEnvironment( name="github-replay", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-github"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) @replay_env.task async def replay_sample_delivery() -> dict[str, str]: """Verify and parse the sample delivery bundled with the plugin. `SAMPLE_DELIVERY` is a recorded GitHub payload and a function that signs it. The body is real; the signature header is generated by the plugin. """ import flyteplugins.github as plugin secret = "a-test-signing-secret" sign, body = plugin.SAMPLE_DELIVERY headers = sign(body, secret) assert plugin.verify(body, headers, secret), "a correctly signed delivery must verify" assert not plugin.verify(body, headers, "wrong-secret"), "a bad signature must not" event = plugin.parse(headers, body) return { # Matched by `on_event`. `events.PullRequest.OPENED` equals this string. "qualified_type": event.qualified_type, # Matched against `scopes`. "scope": event.scope or "", "title": event.title or "", "actor": event.actor or "", # The key `run_once` deduplicates on. "dedupe_key": event.dedupe_key(), } # {{/docs-fragment replay}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(replay_sample_delivery) print(run.name) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/github/github_tasks.py* Installation tokens expire after one hour. That is long enough for a clone or a `gh pr create`, and a leaked token stops working soon after. **Review load.** An agent can open more pull requests than reviewers can read carefully. To keep review meaningful: - Make an automated gate the only gate for mechanical changes, and reserve human review for changes that alter behavior. - Test generated code before review. The [code generation integration](../../../integrations/codegen/_index) runs it in a sandbox first. [Agent frameworks](../../../integrations/agents/_index) covers running agent SDKs as durable tasks, and [Agents](../../agents/_index) covers Flyte's own agent harness. ## Gate a dataset change Gate a dataset change like a model change, and add a schema check in front of it. [Pandera](../../../integrations/pandera/_index) validates dataframes at task boundaries, so a changed column type or an unexpected null fails at the step that introduced it. See **Project patterns > Software development lifecycle > Evaluation gates > Gate the input** for input checks on model output. ## Gates to avoid A gate that people work around gives false assurance. Avoid these: - **A non-deterministic gate with no tolerance.** If it fails one run in five, people re-run it until it passes. - **An absolute threshold.** "Accuracy above 0.9" turns permanently red when the data shifts, or permanently passes. Compare against what is live instead. See **Project patterns > Software development lifecycle > Evaluation gates**. - **A slow gate in front of a fast loop.** A 40-minute gate belongs after merge, with the ability to roll back. ## See also - **Project patterns > Software development lifecycle > Evaluation gates** for measuring quality well enough to gate on it. - **Project patterns > Software development lifecycle > Human gates and approvals** for putting a person in the loop. - **Project patterns > CI/CD deployments** for deployment from CI. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/software-development-lifecycle/human-gates-and-approvals === Put a person in the loop with a condition, and decide what happens when nobody answers. # Human gates and approvals Use a human gate for decisions that should not be automated, such as a production deploy, a schema migration, or an agent action with real consequences. The gate is an **Tasks > Build tasks > External conditions**: an action that pauses a run until a signal arrives. The condition and its answer are stored on the backend. The task that waits on the condition is not suspended: its pod keeps running and holds its resources until the condition is answered or times out. See **Tasks > Build tasks > External conditions > Resources while waiting**. ## Choose where the person answers | Approach | The person answers in | Use it when | |---|---|---| | A **Tasks > Build tasks > External conditions** | The Union.ai UI | The approver works in Union.ai, or needs the run's context to decide | | A **Software development tools > Slack** | Slack, with a button | The approver works in chat | | A **Software development tools > GitHub** | The Union.ai UI, with the PR's metadata shown | The decision is about a specific pull request | A Slack approval is a condition underneath. If nobody clicks the button in Slack, the same condition can still be answered in the Union.ai UI. ## Ask in Slack ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-slack>=2.10.6", # ] # main = "replay_sample_delivery" # params = "" # /// """Tasks that post to Slack and wait for approval button clicks. - `answer` posts a threaded reply with `notify.post`, then edits it with `notify.update`. - `deploy_with_approval` uses `approval.request` to pause the run until someone clicks a button. `replay_sample_delivery` runs without a Slack workspace: flyte run --local slack_tasks.py replay_sample_delivery """ import flyte from flyteplugins.slack import approval, notify # {{docs-fragment task}} env = flyte.TaskEnvironment( name="slack-bot", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-slack"), # The bot token (xoxb-...) from OAuth & Permissions. Posting requires the # `chat:write` scope, and the bot must be invited to the channel. secrets=[flyte.Secret(key="SLACK_BOT_TOKEN", as_env_var="SLACK_BOT_TOKEN")], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @env.task async def answer(channel: str, text: str, thread_ts: str) -> str: """Post a threaded reply, then edit it when the work finishes. `post` returns the message's `ts`, which `update` uses to edit it. """ ts = await notify.post(channel, f"Working on: {text}", thread_ts=thread_ts) await notify.update(channel, ts, f"Done: {text}") return ts # {{/docs-fragment task}} # {{docs-fragment approval}} @env.task async def deploy_with_approval(release: str, channel: str = "C0DEPLOYS") -> str: """Post approval buttons and wait for a click. `approval.request` posts Block Kit buttons and waits on a `flyte.new_condition`. The handler added by `approval.register` resolves the condition when someone clicks. The condition can also be resolved from the Flyte UI. """ decision = await approval.request.aio( channel, f"Deploy `{release}` to prod?", options=["approve", "reject"], timeout=3600, ) if decision != "approve": return f"{release}: not deployed ({decision})" return f"{release}: deployed" # {{/docs-fragment approval}} # {{docs-fragment replay}} # A separate environment with no secrets, so the replay runs before any # secret is created. replay_env = flyte.TaskEnvironment( name="slack-replay", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-slack"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) @replay_env.task async def replay_sample_delivery() -> dict[str, str]: """Verify and parse the sample delivery bundled with the plugin. The provider rejects deliveries more than five minutes old, so `SAMPLE_DELIVERY` signs the payload with the current time when called. """ import flyteplugins.slack as plugin secret = "a-test-signing-secret" sign, body = plugin.SAMPLE_DELIVERY headers = sign(body, secret) assert plugin.verify(body, headers, secret), "a correctly signed delivery must verify" assert not plugin.verify(body, headers, "wrong-secret"), "a bad signature must not" event = plugin.parse(headers, body) return { "qualified_type": event.qualified_type, "scope": event.scope or "", "title": event.title or "", "actor": event.actor or "", "dedupe_key": event.dedupe_key(), # Maximum delivery age, in seconds. "max_request_age": str(plugin.MAX_REQUEST_AGE_SECONDS), } # {{/docs-fragment replay}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(replay_sample_delivery) print(run.name) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/slack/slack_tasks.py* The task posts Block Kit buttons and pauses the run. When someone clicks a button, the receiver signals the condition and replaces the buttons with a "decided by" line. The button's `value` carries the run, action, and condition names, so the receiver needs only one setting to answer: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-slack[app]>=2.10.6", # ] # /// """Slack webhook receiver for Events API callbacks, interactivity, and slash commands. `SlackProvider` verifies and parses all three delivery types on one route; `on_event` selects between them. Deploy the app, then enter the payload URL from its dashboard at api.slack.com/apps under Event Subscriptions, Interactivity & Shortcuts, and each slash command: python slack_webhooks.py """ import pathlib # {{docs-fragment app}} import flyte from flyte.extras.webhooks import WebhookAppEnvironment, WebhookEvent, run_once from flyteplugins.slack import SlackProvider, approval, events, notify # SLACK_SIGNING_SECRET is mounted automatically. It's the signing secret from # Basic Information, not the bot token, which goes on the task environment. # # `scopes` lists the channel IDs to act on: where the bot is mentioned, where # /deploy is used, and where approvals are posted. Events from other channels # are acknowledged but not dispatched. app_env = WebhookAppEnvironment( name="slack-webhooks", providers=[SlackProvider()], scopes=["C0DEPLOYS"], image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-slack[app]"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) # Adds a handler that resolves the condition behind each button posted by # `approval.request`. Each button's value carries the run, action, and # condition names, so no other configuration is needed. approval.register(app_env) # {{/docs-fragment app}} # {{docs-fragment handler}} @app_env.on_event(events.AppMention.ANY) async def on_mention(event: WebhookEvent) -> dict: """Launch a run for each @-mention. The dedupe key identifies one message. For one run per thread, build a key from `thread_ts` and pass it to `run_once` instead. """ import flyte.remote as remote task = remote.Task.get(name="slack-bot.answer", auto_version="latest") slack_event = event.payload["event"] result = await run_once.aio( task, key=event.dedupe_key(), channel=event.scope, text=event.title or "", thread_ts=slack_event.get("thread_ts") or slack_event["ts"], ) return {"run": result.run.name, "created": result.created} @app_env.on_event(events.Command, action="/deploy") async def on_deploy_command(event: WebhookEvent) -> dict: """Acknowledge the /deploy slash command. `respond` posts to the command's `response_url` and needs no bot token. Slack expects a reply within three seconds, so acknowledge here and do longer work in a launched run. """ await notify.respond(event.payload["response_url"], "Deploy queued.") return {"ok": True} # {{/docs-fragment handler}} # {{docs-fragment serve}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployment = flyte.serve(app_env) print(f"Setup dashboard: {deployment.url}") # {{/docs-fragment serve}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/slack/slack_webhooks.py* ## Set a timeout A condition with no timeout waits indefinitely, and the run can sit "in progress" for weeks with nobody responsible for it. `approval.request` times out after one hour by default. On expiry, `wait()` raises `flyte.errors.ConditionTimedoutError`. Catch it and decide what a timeout means: - **No.** The right default for anything with consequences. Take the safe branch. - **Escalate.** Ask again in another channel, or page someone. - **Yes.** Rarely appropriate. If an unanswered hour counts as approval, the gate does not protect anything. ## Make the prompt decidable The person answering is often not the author of the change, and may be on a phone. "Approve deploy?" sends them looking for context, so they approve without it or don't answer. Put the facts needed to decide in the prompt: what is changing, what it was measured against, what the measurement showed, and what happens on "no". `review_pr` includes the pull request's metadata. For Slack, build a richer Block Kit message with `approval.blocks(...)`, including context, fields, and a link to the report. The registered handler still answers it. ## Control who can answer Anyone who can see a Slack channel can click its buttons. For a low-stakes deploy, that is acceptable. Otherwise, post to a channel whose membership is the set of approvers, or use a condition answered in the Union.ai UI, where platform permissions control access. See **Project patterns > Resource management and multi-team scaling** for the RBAC primitives. ## Keep human gates rare A gate on every merge trains people to approve without reading. Gate on changes that are rare and consequential, such as a production promotion, a migration, or a first rollout to real traffic. If a human gate fires more than a few times a day, replace it with an **Project patterns > Software development lifecycle > Evaluation gates** and an alert. ## Review AI output by exception Reviewing AI output, such as a generated summary or an agent's proposed action, differs from approving a change because its volume grows with traffic. Send only the uncertain cases to a person: 1. Get a typed answer with a confidence score instead of free text. [TypeSafe AI](../../../integrations/typesafe-ai/_index) does this, and [Decision models](../../inference/decision-models/_index) covers the pattern. 2. Act automatically on confident answers. 3. Pause the uncertain ones on a condition. 4. Record each human answer. These answers are labeled data for your next **Project patterns > Software development lifecycle > Evaluation gates**. ## See also - **Tasks > Build tasks > External conditions** for the full condition API. - **Project patterns > Software development lifecycle > Evaluation gates** for measurements that reduce how often a person must decide. - **Software development tools > Slack** for approvals, messages, and the receiver. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/software-development-lifecycle/evaluation-gates === Promote on measured quality instead of a green checkmark, comparing against what is live with enough samples to tell a real change from noise. # Evaluation gates An evaluation gate decides whether a model, prompt, or dataset change may proceed by scoring it against what is currently live. Use one wherever a test suite can't answer the question: the system under test is non-deterministic, quality is a distribution, and a run costs GPUs or paid API calls. ## Build the gate The gate scores every case against both the candidate and the baseline, several times each, and then compares the two sets of scores: ```python import asyncio import flyte env = flyte.TaskEnvironment( name="eval-gate", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-mlflow"), resources=flyte.Resources(cpu=4, memory="8Gi"), ) @env.task(cache="auto", retries=3) async def score_one(model_uri: str, case: dict, repeat: int) -> float: """Score one case against one model. `repeat` makes each sample a separate cache entry.""" ... @env.task async def score_all(model_uri: str, cases: list[dict], repeats: int = 3) -> list[float]: """Score every case `repeats` times.""" samples = [(case, r) for case in cases for r in range(repeats)] return [ score async for score in flyte.map.aio( score_one, [model_uri] * len(samples), [case for case, _ in samples], [r for _, r in samples], return_exceptions=False, ) ] def decide(candidate: list[float], baseline: list[float]) -> bool: """Your comparison rule. See "Compare honestly" below.""" ... @env.task(report=True) async def gate(candidate_uri: str, baseline_uri: str, cases: list[dict]) -> bool: candidate, baseline = await asyncio.gather( score_all(candidate_uri, cases), score_all(baseline_uri, cases), ) passed = decide(candidate, baseline) await flyte.report.replace.aio( f"

{'Pass' if passed else 'Fail'}

" f"

Candidate mean: {sum(candidate) / len(candidate):.3f} ({candidate_uri})

" f"

Baseline mean: {sum(baseline) / len(baseline):.3f} ({baseline_uri})

", do_flush=True, ) return passed ``` Three settings do most of the work: - `cache="auto"` on `score_one`. The baseline's scores are the same for every candidate you test against it, so after the first gate they come from the cache. `repeat` is an input, so each repeat is a separate sample rather than a cache hit on the first one. - `retries=3` on `score_one`, not on `gate`. A transient provider error retries one case. A retry on `gate` would re-run every case. - `flyte.map.aio` for the fan-out. Each case is its own action, so a failure at case 900 doesn't lose the first 899. The cache key is the task's code plus its inputs, so cached scores are only valid while `model_uri` names exactly one model. Pass an immutable identifier, such as a registry version or a provider's dated model snapshot, never an alias like `latest`. If anything else that affects scoring changes, such as a judge model or a dependency, add it as an input to `score_one` so both sides are rescored. `flyte.map` passes the lists to `score_one` position by position, like Python's built-in `map`. `return_exceptions=False` makes a case that exhausts its retries fail the gate instead of appearing as an exception in the score list. Don't measure the noise floor by passing the same model URI to both sides of `gate`. Both sides have identical inputs, so they read the same cached scores and the measured noise is zero. Instead, run `score_all` on the baseline with `repeats=6` and compare repeats 0โ€“2 of each case with repeats 3โ€“5. ## Why a test suite doesn't fit | A unit test | An evaluation | |---|---| | Deterministic | Non-deterministic, for anything generative | | Pass or fail | A distribution of scores | | Milliseconds, free | Minutes to hours, with GPUs and paid API calls | | Asserts against a fixed expectation | Compares against what is currently live | | A failure means the code is wrong | A failure can mean the data moved, the provider changed a model, or chance | Two common shapes fail: - **A hard threshold.** `assert accuracy > 0.9` goes permanently red when the data shifts, or stays green and stops carrying information. - **A single comparison run.** One run per side measures noise. A difference between them is not evidence of a change. An evaluation gate has to do four things: 1. Hold the evaluation set fixed, and version it so scores are comparable across weeks. 2. Score the candidate and the baseline under the same conditions: same set, same prompts, same scoring code. 3. Take more than one sample per side, so it can tell a real difference from noise. 4. Produce a report a person can read, because the final decision is often a judgment the number informs. To version the evaluation set, register it as an [artifact](../../artifacts/_index). ## Compare honestly - **Repeat both sides.** If the system is non-deterministic, score each case several times on each side and compare distributions. - **Pair by case.** Compare the candidate and baseline scores for the same case. Case difficulty is usually the largest source of variance, and pairing cancels it. - **Set the threshold in units of noise.** Measure run-to-run variance on the baseline first, as described above. A difference smaller than that is not a result. A threshold below the noise floor makes the gate fire at random. - **Slice before aggregating.** An overall mean can improve while the slice you care about gets worse. Gate on each slice as well as the total. - **Define "worse" per metric.** Latency and cost usually have hard ceilings, and quality usually has a tolerance. "No regression on any slice beyond noise, and no latency increase beyond 10%" is a gate. "Better on average" is not. ## Record the result [MLflow](../../../integrations/mlflow/_index) and [Weights & Biases](../../../integrations/wandb/_index) both log from inside a task, so the recorded metrics trace back to the run that produced them. For the readable half, `report=True` gives the gate a task report, which the example fills with `flyte.report.replace.aio`. Add per-slice scores and the worst-scoring cases there. If the reviewer needs plots and tables, [Papermill](../../../integrations/papermill/_index) runs a parameterized notebook as a task, so the notebook is the gate's output. ## Gate the input Validating inputs catches a problem before any scoring compute is spent: - [Pandera](../../../integrations/pandera/_index) validates dataframes at task boundaries. A column that changed type, or an unexpected null, fails at the step that introduced it instead of surfacing later as a regression. - [TypeSafe AI](../../../integrations/typesafe-ai/_index) returns typed, confidence-scored answers from a model, which you can check directly instead of parsing free text. [Decision models](../../inference/decision-models/_index) covers the pattern. ## Scale the compute - [`flyte.map`](../../tasks/task-programming/fanout.md) for per-case fan-out. This is usually enough. - [Ray](../../../integrations/ray/_index), [Spark](../../../integrations/spark/_index), or [Dask](../../../integrations/dask/_index) when scoring needs a cluster rather than many independent tasks. - Per-task **Tasks > Configure tasks > Resources**, so only the step that needs a GPU holds one. - [Snowflake](../../../integrations/snowflake/_index), [BigQuery](../../../integrations/bigquery/_index), or [Databricks](../../../integrations/databricks/_index) when the evaluation set is in a warehouse. - [Polars](../../../integrations/polars/_index), [Lance](../../../integrations/lance/_index), [JSONL](../../../integrations/jsonl/_index), or [Hugging Face](../../../integrations/huggingface/_index) to pass scored data between steps without writing your own serialization. ## Record the configuration A score is only comparable if you know how it was produced. [Hydra](../../../integrations/hydra/_index) and [OmegaConf](../../../integrations/omegaconf/_index) pass structured configuration between tasks as typed inputs, so the configuration is recorded with the run instead of living in environment variables. ## Evaluate agents An agent's output is a trajectory, not a single value. A correct answer reached by a wasteful or unsafe path is not equivalent to the same answer reached directly, so score more than the final output: - Task completion, on a fixed set of scenarios. - Tool-call correctness: the right tools, with the right arguments, in a sensible order. - Cost and turn count. These often regress first when a prompt changes. - Safety behaviors, on cases chosen to provoke them. [Agent plugins](../../../integrations/agents/_index) run each tool call as a child action and record each model turn, so the trajectory is already in the run. Completed turns replay on retry instead of calling the model again. ## See also - **Project patterns > Software development lifecycle > Review and release gates** for wiring the verdict into a promotion. - **Project patterns > Software development lifecycle > Human gates and approvals** for the decision the number informs. - **Project patterns > Software development lifecycle > Notifications and observability** for catching in production what the gate missed. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/software-development-lifecycle/notifications-and-observability === Get a run's outcome to the people who need it, and see what production is doing without reading logs. # Notifications and observability Notifications tell a person that a specific run finished or failed. Observability lets someone investigate what the system is doing across runs. Keep them separate: if every run posts to a channel, people mute the channel and miss the message that mattered. | | Notification | Observability | |---|---|---| | Answers | "This run finished, or failed" | "What is the system doing" | | Audience | Whoever must act | Whoever is investigating | | Destination | Slack, email, or a webhook | Traces and metrics in your own backend | | Volume | Low | High, and queried rather than read | ## Notify on a terminal state Start with the built-in notifications, which need no plugin. **Tasks > Run and deploy tasks > Run with notifications** sends a message when a run reaches a terminal state, through email, Slack, Teams, or a generic webhook. **Triggers > Notifications** does the same for triggered runs. They are declarative, need no code, and fire even if the task itself crashed. ## Post from inside a run When the message needs results the run computed, such as which model won or which rows failed, post from inside the run with the **Software development tools > Slack**: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-slack>=2.10.6", # ] # main = "replay_sample_delivery" # params = "" # /// """Tasks that post to Slack and wait for approval button clicks. - `answer` posts a threaded reply with `notify.post`, then edits it with `notify.update`. - `deploy_with_approval` uses `approval.request` to pause the run until someone clicks a button. `replay_sample_delivery` runs without a Slack workspace: flyte run --local slack_tasks.py replay_sample_delivery """ import flyte from flyteplugins.slack import approval, notify # {{docs-fragment task}} env = flyte.TaskEnvironment( name="slack-bot", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-slack"), # The bot token (xoxb-...) from OAuth & Permissions. Posting requires the # `chat:write` scope, and the bot must be invited to the channel. secrets=[flyte.Secret(key="SLACK_BOT_TOKEN", as_env_var="SLACK_BOT_TOKEN")], resources=flyte.Resources(cpu=1, memory="512Mi"), ) @env.task async def answer(channel: str, text: str, thread_ts: str) -> str: """Post a threaded reply, then edit it when the work finishes. `post` returns the message's `ts`, which `update` uses to edit it. """ ts = await notify.post(channel, f"Working on: {text}", thread_ts=thread_ts) await notify.update(channel, ts, f"Done: {text}") return ts # {{/docs-fragment task}} # {{docs-fragment approval}} @env.task async def deploy_with_approval(release: str, channel: str = "C0DEPLOYS") -> str: """Post approval buttons and wait for a click. `approval.request` posts Block Kit buttons and waits on a `flyte.new_condition`. The handler added by `approval.register` resolves the condition when someone clicks. The condition can also be resolved from the Flyte UI. """ decision = await approval.request.aio( channel, f"Deploy `{release}` to prod?", options=["approve", "reject"], timeout=3600, ) if decision != "approve": return f"{release}: not deployed ({decision})" return f"{release}: deployed" # {{/docs-fragment approval}} # {{docs-fragment replay}} # A separate environment with no secrets, so the replay runs before any # secret is created. replay_env = flyte.TaskEnvironment( name="slack-replay", image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-slack"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) @replay_env.task async def replay_sample_delivery() -> dict[str, str]: """Verify and parse the sample delivery bundled with the plugin. The provider rejects deliveries more than five minutes old, so `SAMPLE_DELIVERY` signs the payload with the current time when called. """ import flyteplugins.slack as plugin secret = "a-test-signing-secret" sign, body = plugin.SAMPLE_DELIVERY headers = sign(body, secret) assert plugin.verify(body, headers, secret), "a correctly signed delivery must verify" assert not plugin.verify(body, headers, "wrong-secret"), "a bad signature must not" event = plugin.parse(headers, body) return { "qualified_type": event.qualified_type, "scope": event.scope or "", "title": event.title or "", "actor": event.actor or "", "dedupe_key": event.dedupe_key(), # Maximum delivery age, in seconds. "max_request_age": str(plugin.MAX_REQUEST_AGE_SECONDS), } # {{/docs-fragment replay}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(replay_sample_delivery) print(run.name) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/slack/slack_tasks.py* `post` returns the message's `ts`, which serves as both the thread anchor and the ID that `update` edits. To report progress, post once when work starts and edit the message as it proceeds, instead of posting a new message at each step. To limit which tasks hold the bot token, deploy the ready-made task environment in `notify` once, with `flyte.deploy(notify.env)`. Only that environment mounts the token. Other runs post by calling its `send` task, without mounting the secret. ## Reply to the person who asked When a person started the run, with a slash command, a button, or a mention, reply where they are: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.10.6", # "flyteplugins-slack[app]>=2.10.6", # ] # /// """Slack webhook receiver for Events API callbacks, interactivity, and slash commands. `SlackProvider` verifies and parses all three delivery types on one route; `on_event` selects between them. Deploy the app, then enter the payload URL from its dashboard at api.slack.com/apps under Event Subscriptions, Interactivity & Shortcuts, and each slash command: python slack_webhooks.py """ import pathlib # {{docs-fragment app}} import flyte from flyte.extras.webhooks import WebhookAppEnvironment, WebhookEvent, run_once from flyteplugins.slack import SlackProvider, approval, events, notify # SLACK_SIGNING_SECRET is mounted automatically. It's the signing secret from # Basic Information, not the bot token, which goes on the task environment. # # `scopes` lists the channel IDs to act on: where the bot is mentioned, where # /deploy is used, and where approvals are posted. Events from other channels # are acknowledged but not dispatched. app_env = WebhookAppEnvironment( name="slack-webhooks", providers=[SlackProvider()], scopes=["C0DEPLOYS"], image=flyte.Image.from_debian_base().with_pip_packages("flyteplugins-slack[app]"), resources=flyte.Resources(cpu=1, memory="512Mi"), ) # Adds a handler that resolves the condition behind each button posted by # `approval.request`. Each button's value carries the run, action, and # condition names, so no other configuration is needed. approval.register(app_env) # {{/docs-fragment app}} # {{docs-fragment handler}} @app_env.on_event(events.AppMention.ANY) async def on_mention(event: WebhookEvent) -> dict: """Launch a run for each @-mention. The dedupe key identifies one message. For one run per thread, build a key from `thread_ts` and pass it to `run_once` instead. """ import flyte.remote as remote task = remote.Task.get(name="slack-bot.answer", auto_version="latest") slack_event = event.payload["event"] result = await run_once.aio( task, key=event.dedupe_key(), channel=event.scope, text=event.title or "", thread_ts=slack_event.get("thread_ts") or slack_event["ts"], ) return {"run": result.run.name, "created": result.created} @app_env.on_event(events.Command, action="/deploy") async def on_deploy_command(event: WebhookEvent) -> dict: """Acknowledge the /deploy slash command. `respond` posts to the command's `response_url` and needs no bot token. Slack expects a reply within three seconds, so acknowledge here and do longer work in a launched run. """ await notify.respond(event.payload["response_url"], "Deploy queued.") return {"ok": True} # {{/docs-fragment handler}} # {{docs-fragment serve}} if __name__ == "__main__": flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) deployment = flyte.serve(app_env) print(f"Setup dashboard: {deployment.url}") # {{/docs-fragment serve}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/integrations/flyte-plugins/slack/slack_webhooks.py* `respond` needs no token. It posts to the `response_url` that every interaction and slash command carries, which Slack accepts for 30 minutes and up to five times. Acknowledge from the handler and let the run post the answer. Slack shows a synchronous reply only if it arrives within 3 seconds. ## Observe across runs For a single failed run, the run itself is usually enough: it records inputs, outputs, logs, and task reports. For questions that span runs and services, export telemetry. [OpenTelemetry](../../../integrations/opentelemetry/_index) sends task and agent telemetry to any OTLP backend, and [Grafana Agent](../../../integrations/grafana-agent-observability/_index) sends it to Grafana Cloud. Flyte spans then join your application's traces, so a request that calls into a Flyte run stays one trace. This is most useful for agents, where the question is often about the whole trajectory, such as why an answer took nine turns. ## Track what produced an output Every run records its inputs, outputs, code version, and image. Deploy with `--version `, as described in [CI/CD deployments](../cicd.md), to tie each run to a commit. To trace an output to the data and model behind it, register datasets and models as [artifacts](../../artifacts/_index). Artifacts record lineage across runs: which model version came from which training run, on which dataset version. [MLflow](../../../integrations/mlflow/_index) and [Weights & Biases](../../../integrations/wandb/_index) keep metric history, so you can tell whether a score is unusual compared with previous weeks. ## Investigate a failure Work through these in order, cheapest first: 1. **Read the failed run:** its inputs, outputs, logs, and report. 2. **Check the inputs.** A [Pandera](../../../integrations/pandera/_index) report shows whether the data changed. If you have no data contract yet, add one. 3. **Compare against history** to see whether the score is unusual. 4. **Re-run it.** If a [retry](../../tasks/task-configuration/retries-and-timeouts.md) succeeds, the failure was transient. 5. **Open the trace** when the question spans services. Two things set up in advance make this faster: typed task signatures, so a malformed input fails at the task boundary, and [error handling](../../tasks/task-programming/error-handling.md) that separates recoverable failures from ones that should stop the run. ## File the result in your tracker A run that finds something to act on can file it: - Open or update a ticket in [Linear](../../../integrations/software-development-tools/linear.md), [Jira](../../../integrations/software-development-tools/jira.md), or [ClickUp](../../../integrations/software-development-tools/clickup.md). - Comment on a pull request or publish a check run in [GitHub](../../../integrations/software-development-tools/github.md). Make these tasks idempotent, so a retried run doesn't file a duplicate ticket. Launch with `run_once`, and have the task check whether the ticket exists before creating it. The **Software development tools > ClickUp** shows this. ## See also - **Project patterns > Software development lifecycle > Event-driven automation** for what starts a run. - **Tasks > Run and deploy tasks > Send notifications from your code** for a notification sent from the driver task. - **Software development tools > Slack** for messages, approvals, and the receiver. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/advanced-project === An advanced guide for building an LLM reporting agent on Flyte. # Advanced project: LLM reporting agent This example demonstrates a resilient agentic report generator that showcases Flyte 2.0's advanced features for building production-grade AI workflows. ## What you'll build A batch report generator that: 1. Processes multiple topics in parallel 2. Iteratively critiques and refines each report until it meets a quality threshold 3. Produces multiple output formats (Markdown, HTML, summary) for each report 4. Serves results through an interactive UI ## Concepts covered | Feature | Description | |---------|-------------| | `ReusePolicy` | Keep containers warm for high-throughput batch processing | | `@flyte.trace` | Checkpoint LLM calls for recovery and observability | | `RetryStrategy` | Handle transient API failures gracefully | | `flyte.group` | Organize parallel batches and iterations in the UI | | `asyncio.gather` | Fan out to process multiple topics concurrently | | Pydantic models | Structured LLM outputs | | `AppEnvironment` | Deploy interactive Streamlit apps | | `RunOutput` | Connect apps to pipeline outputs | ## Architecture ```mermaid flowchart TD A[Topics List] --> B B["report_batch_pipeline
driver_env"] subgraph B1 ["refine_all (parallel)"] direction LR R1["refine_report
topic 1"] R2["refine_report
topic 2"] R3["refine_report
topic N"] end B --> B1 subgraph B2 ["format_all (parallel)"] direction LR F1["format_outputs
report 1"] F2["format_outputs
report 2"] F3["format_outputs
report N"] end B1 --> B2 B2 --> C["Output: List of Dirs"] ``` Each `refine_report` task runs in a reusable container (`llm_env`) and performs multiple LLM calls through traced functions: ```mermaid flowchart TD A[Topic] --> B["generate_initial_draft
@flyte.trace"] B --> C subgraph C ["refinement_loop"] direction TB D["critique_content
@flyte.trace"] -->|score >= threshold| E[exit loop] D -->|score < threshold| F["revise_content
@flyte.trace"] F --> D end C --> G[Refined Report] ``` ## Prerequisites - A Union.ai account with an active project - An OpenAI API key stored as a secret named `openai-api-key` To create the secret: ```bash flyte create secret openai-api-key ``` ## Parts 1. ****Project patterns > Advanced project: LLM reporting agent > Resilient generation****: Set up reusable environments, traced LLM calls, and retry strategies 2. ****Project patterns > Advanced project: LLM reporting agent > Agentic refinement****: Build the iterative critique-and-revise loop 3. ****Project patterns > Advanced project: LLM reporting agent > Parallel outputs****: Generate multiple formats concurrently 4. ****Project patterns > Advanced project: LLM reporting agent > Serving app****: Deploy an interactive UI for report generation ## Key takeaways 1. **Reusable environments for batch processing**: `ReusePolicy` keeps containers warm, enabling efficient processing of multiple topics without cold start overhead. With 5 topics ร— ~7 LLM calls each, the reusable pool handles ~35 calls efficiently. 2. **Checkpointed LLM calls**: `@flyte.trace` provides automatic checkpointing at the function level, enabling recovery without re-running expensive API calls. 3. **Agentic patterns**: The generate-critique-revise loop demonstrates how to build self-improving AI workflows with clear observability through `flyte.group`. 4. **Parallel fan-out**: `asyncio.gather` processes multiple topics concurrently, maximizing throughput by running refinement tasks in parallel across the batch. {{< subpage-cards >}} ## Subpages - **Project patterns > Advanced project: LLM reporting agent > Resilient generation** - Reusable environments, traced calls, and retry strategies for LLM-powered tasks. - **Project patterns > Advanced project: LLM reporting agent > Agentic refinement** - Build a generate, critique, revise loop that repeats until output quality clears a threshold. - **Project patterns > Advanced project: LLM reporting agent > Parallel outputs** - Produce several output formats at once with asyncio.gather. - **Project patterns > Advanced project: LLM reporting agent > Serving app** - Connect a serving app to a pipeline so it can display results and take input. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/advanced-project/resilient-generation === Reusable environments, traced calls, and retry strategies for LLM-powered tasks. # Resilient generation This section covers the foundational patterns for building resilient LLM-powered tasks: reusable environments, traced function calls, and retry strategies. ## Two environments This example uses two task environments with different characteristics: 1. **`llm_env`** (reusable): For tasks that make many LLM calls in a loop or process batches in parallel. Container reuse avoids cold starts. 2. **`driver_env`** (standard): For orchestration tasks that fan out work to other tasks but don't make LLM calls themselves. ### Reusable environment for LLM work When processing a batch of topics, each topic goes through multiple LLM calls (generate, critique, revise, repeat). With 5 topics ร— ~7 calls each, that's ~35 LLM calls. `ReusePolicy` keeps containers warm to handle this efficiently: ```python # Reusable environment for tasks that make many LLM calls in a loop. # The ReusePolicy keeps containers warm, reducing cold start latency for iterative work. llm_env = flyte.TaskEnvironment( name="llm-worker", secrets=[] if MOCK_MODE else [flyte.Secret(key="openai-api-key", as_env_var="OPENAI_API_KEY")], image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "unionai-reuse>=0.1.10", "openai>=1.0.0", "pydantic>=2.0.0", ), resources=flyte.Resources(cpu=1, memory="2Gi"), reusable=flyte.ReusePolicy( replicas=2, # Keep 2 container instances ready concurrency=4, # Allow 4 concurrent tasks per container scaledown_ttl=timedelta(minutes=5), # Wait 5 min before scaling down idle_ttl=timedelta(minutes=30), # Shut down after 30 min idle ), cache="auto", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* ### ReusePolicy parameters | Parameter | Description | |-----------|-------------| | `replicas` | Number of container instances to keep ready (or `(min, max)` tuple) | | `concurrency` | Maximum tasks per container at once | | `scaledown_ttl` | Minimum wait before scaling down a replica | | `idle_ttl` | Time after which idle containers shut down completely | The configuration above keeps 2 containers ready, allows 4 concurrent tasks per container, waits 5 minutes before scaling down, and shuts down after 30 minutes of inactivity. > **๐Ÿ“ Note** > > Both `scaledown_ttl` and `idle_ttl` must be at least 30 seconds. ### Standard environment for orchestration The driver environment doesn't need container reuse; it just coordinates work. The `depends_on` parameter declares that tasks in this environment call tasks in `llm_env`, ensuring both environments are deployed together: ```python # Standard environment for orchestration tasks that don't need container reuse. # depends_on declares that this environment's tasks call tasks in llm_env. driver_env = flyte.TaskEnvironment( name="driver", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "pydantic>=2.0.0", ), resources=flyte.Resources(cpu=1, memory="1Gi"), depends_on=[llm_env], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* ## Traced LLM calls The `@flyte.trace` decorator provides automatic checkpointing at the function level. When a traced function completes successfully, its result is cached. If the task fails and restarts, previously completed traced calls return their cached results instead of re-executing. ```python @flyte.trace async def call_llm(prompt: str, system: str, json_mode: bool = False) -> str: """ Make an LLM call with automatic checkpointing. The @flyte.trace decorator provides: - Automatic caching of results for identical inputs - Recovery from failures without re-running successful calls - Full observability in the Flyte UI Args: prompt: The user prompt to send system: The system prompt defining the LLM's role json_mode: Whether to request JSON output Returns: The LLM's response text """ # Use mock responses for testing without API keys if MOCK_MODE: import asyncio await asyncio.sleep(0.5) # Simulate API latency if "critique" in prompt.lower() or "critic" in system.lower(): # Return good score if draft has been revised (contains revision marker) if "[REVISED]" in prompt: return MOCK_CRITIQUE_GOOD return MOCK_CRITIQUE_NEEDS_WORK elif "summary" in system.lower(): return MOCK_SUMMARY elif "revis" in system.lower(): # Return revised version with marker return MOCK_REPORT.replace("## Introduction", "[REVISED]\n\n## Introduction") else: return MOCK_REPORT from openai import AsyncOpenAI client = AsyncOpenAI() kwargs = { "model": "gpt-4o-mini", "messages": [ {"role": "system", "content": system}, {"role": "user", "content": prompt}, ], "max_tokens": 2000, } if json_mode: kwargs["response_format"] = {"type": "json_object"} response = await client.chat.completions.create(**kwargs) return response.choices[0].message.content ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* ### Benefits of tracing 1. **Cost savings**: Failed tasks don't re-run expensive API calls that already succeeded 2. **Faster recovery**: Resuming from checkpoints skips completed work 3. **Observability**: Each traced call appears in the Flyte UI with timing data ### When to use @flyte.trace Use `@flyte.trace` for: - LLM API calls (OpenAI, Anthropic, etc.) - External API requests - Any expensive operation you don't want to repeat on retry Don't use `@flyte.trace` for: - Simple computations (overhead outweighs benefit) - Operations with side effects that shouldn't be skipped ## Traced helper functions The LLM-calling functions are decorated with `@flyte.trace` rather than being separate tasks. This keeps the architecture simple while still providing checkpointing: ```python @flyte.trace async def generate_initial_draft(topic: str) -> str: """ Generate the initial report draft. The @flyte.trace decorator provides checkpointing - if the task fails after this completes, it won't re-run on retry. Args: topic: The topic to write about Returns: The initial draft in markdown format """ print(f"Generating initial draft for topic: {topic}") prompt = f"Write a comprehensive report on the following topic:\n\n{topic}" draft = await call_llm(prompt, GENERATOR_SYSTEM_PROMPT) print(f"Generated initial draft ({len(draft)} characters)") return draft ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* These traced functions run inside the `refine_report` task. If the task fails and retries, completed traced calls return cached results instead of re-executing. ## Retry strategies The task that orchestrates the LLM calls uses `retries` to handle transient failures: ```python @llm_env.task(retries=3) async def refine_report(topic: str, ...) -> str: # Traced functions are called here draft = await generate_initial_draft(topic) ... ``` ### Configuring retries You can specify retries as a simple integer: ```python @llm_env.task(retries=3) async def my_task(): ... ``` Or use `RetryStrategy` for more control: ```python @llm_env.task(retries=flyte.RetryStrategy(count=3)) async def my_task(): ... ``` ### Combining tracing with retries When you combine `@flyte.trace` with task-level retries, you get the best of both: 1. Task fails after completing some traced calls 2. Flyte retries the task 3. Previously completed traced calls return cached results 4. Only the failed operation (and subsequent ones) re-execute This pattern is essential for multi-step LLM workflows where you don't want to re-run the entire chain when a single call fails. ## Structured prompts The example uses a separate `prompts.py` module for system prompts and Pydantic models: ```python GENERATOR_SYSTEM_PROMPT = """You are an expert report writer. Generate a well-structured, informative report on the given topic. The report should include: 1. An engaging introduction that sets context 2. Clear sections with descriptive headings 3. Specific facts, examples, or data points where relevant 4. A conclusion that summarizes key takeaways Write in a professional but accessible tone. Use markdown formatting for structure. Aim for approximately 500-800 words.""" CRITIC_SYSTEM_PROMPT = """You are a demanding but fair editor reviewing a report draft. Evaluate the report on these criteria: - Clarity: Is the writing clear and easy to follow? - Structure: Is it well-organized with logical flow? - Depth: Does it provide sufficient detail and insight? - Accuracy: Are claims supported and reasonable? - Engagement: Is it interesting to read? Provide your response as JSON matching this schema: { "score": <1-10 integer>, "strengths": ["strength 1", "strength 2", ...], "improvements": ["improvement 1", "improvement 2", ...], "summary": "brief overall assessment" } Be specific in your feedback. A score of 8+ means the report is ready for publication.""" REVISER_SYSTEM_PROMPT = """You are an expert editor revising a report based on feedback. Your task is to improve the report by addressing the specific improvements requested while preserving its strengths. Guidelines: - Address each improvement point specifically - Maintain the original voice and style - Keep the same overall structure unless restructuring is requested - Preserve any content that was praised as a strength - Ensure the revised version is cohesive and flows well Return only the revised report in markdown format, no preamble or explanation.""" SUMMARY_SYSTEM_PROMPT = """Create a concise executive summary (2-3 paragraphs) of the following report. Capture the key points and main takeaways. Write in a professional tone suitable for busy executives who need the essential information quickly.""" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/prompts.py* ### Pydantic models for structured output LLM responses can be unpredictable. Using Pydantic models with JSON mode ensures you get structured, validated data: ```python class Critique(BaseModel): """Structured critique response from the LLM.""" score: int = Field( ge=1, le=10, description="Quality score from 1-10, where 10 is publication-ready", ) strengths: list[str] = Field( description="List of strengths in the current draft", ) improvements: list[str] = Field( description="Specific improvements needed", ) summary: str = Field( description="Brief summary of the critique", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/prompts.py* The `Critique` model validates that: - `score` is an integer between 1 and 10 - `strengths` and `improvements` are lists of strings - All required fields are present If the LLM returns malformed JSON, Pydantic raises a validation error, which triggers a retry (if configured). ## Next steps With resilient generation in place, you're ready to build the **Project patterns > Advanced project: LLM reporting agent > Agentic refinement**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/advanced-project/agentic-refinement === Build a generate, critique, revise loop that repeats until output quality clears a threshold. # Agentic refinement The core of this example is an agentic refinement loop: generate content, critique it, revise based on feedback, and repeat until quality meets a threshold. This pattern is fundamental to building self-improving AI systems. ## The agentic pattern Traditional pipelines are linear: input โ†’ process โ†’ output. Agentic workflows are iterative: they evaluate their own output and improve it through multiple cycles. ```mermaid flowchart TD A[Generate] --> B[Critique] B -->|score >= threshold| C[Done] B -->|score < threshold| D[Revise] D --> B ``` ## Critique function The critique function evaluates the current draft and returns structured feedback. It's a traced function (not a separate task) that runs inside `refine_report`: ```python @flyte.trace async def critique_content(draft: str) -> Critique: """ Critique the current draft and return structured feedback. Uses Pydantic models to parse the LLM's JSON response into a typed object for reliable downstream processing. Args: draft: The current draft to critique Returns: Structured critique with score, strengths, and improvements """ print("Critiquing current draft...") response = await call_llm( f"Please critique the following report:\n\n{draft}", CRITIC_SYSTEM_PROMPT, json_mode=True, ) # Parse the JSON response into our Pydantic model critique_data = json.loads(response) critique = Critique(**critique_data) print(f"Critique score: {critique.score}/10") print(f"Strengths: {len(critique.strengths)}, Improvements: {len(critique.improvements)}") return critique ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* Key points: - Uses `json_mode=True` to ensure the LLM returns valid JSON - Parses the response into a Pydantic `Critique` model - Returns a typed object for reliable downstream processing - `@flyte.trace` provides checkpointing: if the task retries, completed critiques aren't re-run ## Revise function The revise function takes the current draft and specific improvements to address: ```python @flyte.trace async def revise_content(draft: str, improvements: list[str]) -> str: """ Revise the draft based on critique feedback. Args: draft: The current draft to revise improvements: List of specific improvements to address Returns: The revised draft """ print(f"Revising draft to address {len(improvements)} improvements...") improvements_text = "\n".join(f"- {imp}" for imp in improvements) prompt = f"""Please revise the following report to address these improvements: IMPROVEMENTS NEEDED: {improvements_text} CURRENT DRAFT: {draft}""" revised = await call_llm(prompt, REVISER_SYSTEM_PROMPT) print(f"Revision complete ({len(revised)} characters)") return revised ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* The prompt includes: 1. The list of improvements from the critique 2. The current draft to revise This focused approach helps the LLM make targeted changes rather than rewriting from scratch. ## The refinement loop The `refine_report` task orchestrates the iterative refinement. It runs in the reusable `llm_env` because it makes multiple LLM calls through traced functions: ```python @llm_env.task(retries=3) async def refine_report( topic: str, max_iterations: int = 3, quality_threshold: int = 8, ) -> str: """ Iteratively refine a report until it meets the quality threshold. This task runs in a reusable container because it makes multiple LLM calls in a loop. The traced helper functions provide checkpointing, so if the task fails mid-loop, completed LLM calls won't be re-run on retry. Args: topic: The topic to write about max_iterations: Maximum refinement cycles (default: 3) quality_threshold: Minimum score to accept (default: 8) Returns: The final refined report """ # Generate initial draft draft = await generate_initial_draft(topic) # Iterative refinement loop for i in range(max_iterations): with flyte.group(f"refinement_{i + 1}"): # Get critique critique = await critique_content(draft) # Check if we've met the quality threshold if critique.score >= quality_threshold: print(f"Quality threshold met at iteration {i + 1}!") print(f"Final score: {critique.score}/10") break # Revise based on feedback print(f"Score {critique.score} < {quality_threshold}, revising...") draft = await revise_content(draft, critique.improvements) else: print(f"Reached max iterations ({max_iterations})") return draft ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* ### How it works 1. **Generate initial draft**: Creates the first version of the report 2. **Enter refinement loop**: Iterates up to `max_iterations` times 3. **Critique**: Evaluates the current draft and assigns a score 4. **Check threshold**: If score meets `quality_threshold`, exit early 5. **Revise**: If below threshold, revise based on improvements 6. **Repeat**: Continue until threshold met or iterations exhausted All the LLM calls (generate, critique, revise) are traced functions inside this single task. This keeps the task graph simple while the reusable container handles the actual LLM work efficiently. ### Early exit The `if critique.score >= quality_threshold: break` pattern enables early exit when quality is sufficient. This saves compute costs and time: no need to run all iterations if the first draft is already good. ## Grouping iterations with flyte.group Each refinement iteration is wrapped in `flyte.group`: ```python for i in range(max_iterations): with flyte.group(f"refinement_{i + 1}"): critique = await critique_content(draft) # ... ``` ### Why use flyte.group? Groups provide hierarchical organization in the Flyte UI. Since critique and revise are traced functions (not separate tasks), groups help organize them: ``` refine_report โ”œโ”€โ”€ generate_initial_draft (traced) โ”œโ”€โ”€ refinement_1 โ”‚ โ”œโ”€โ”€ critique_content (traced) โ”‚ โ””โ”€โ”€ revise_content (traced) โ”œโ”€โ”€ refinement_2 โ”‚ โ”œโ”€โ”€ critique_content (traced) โ”‚ โ””โ”€โ”€ revise_content (traced) โ””โ”€โ”€ [returns refined report] ``` Benefits: - **Clarity**: See exactly how many iterations occurred - **Debugging**: Quickly find which iteration had issues - **Observability**: Track time spent in each refinement cycle ### Group context Groups are implemented as context managers. All traced calls and nested groups within the `with flyte.group(...)` block are associated with that group. ## Configuring the loop The refinement loop accepts parameters to tune its behavior: | Parameter | Default | Description | |-----------|---------|-------------| | `max_iterations` | 3 | Upper bound on refinement cycles | | `quality_threshold` | 8 | Minimum score (1-10) to accept | ### Choosing thresholds - **Higher threshold** (9-10): More refinement cycles, higher quality, more API costs - **Lower threshold** (6-7): Faster completion, may accept lower quality - **More iterations**: Safety net for difficult topics - **Fewer iterations**: Cost control, faster turnaround A good starting point is `quality_threshold=8` with `max_iterations=3`. Adjust based on your quality requirements and budget. ## Best practices for agentic loops 1. **Always set max iterations**: Prevent infinite loops if the quality threshold is never reached. 2. **Use structured critiques**: Pydantic models ensure you can reliably extract the score and improvements from LLM responses. 3. **Log iteration progress**: Print statements help debug when reviewing logs: ```python print(f"Iteration {i + 1}: score={critique.score}") ``` 4. **Consider diminishing returns**: After 3-4 iterations, improvements often become marginal. Set `max_iterations` accordingly. 5. **Use groups for observability**: `flyte.group` makes the iterative nature visible in the UI, essential for debugging and monitoring. ## Next steps With the agentic refinement loop complete, learn how to **Project patterns > Advanced project: LLM reporting agent > Parallel outputs**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/advanced-project/parallel-outputs === Produce several output formats at once with asyncio.gather. # Parallel outputs After refining the report, the pipeline generates multiple output formats in parallel. This demonstrates how to use `asyncio.gather` for concurrent execution within a task. ## The formatting functions The pipeline generates three outputs: markdown, HTML, and an executive summary. Only `generate_summary` uses `@flyte.trace` because it makes an LLM call. The markdown and HTML functions are simple, deterministic transformations that don't benefit from checkpointing: ```python async def format_as_markdown(content: str) -> str: """Format the report as clean markdown.""" # Content is already markdown, but we could add TOC, metadata, etc. return f"""--- title: Generated Report date: {__import__('datetime').datetime.now().isoformat()} --- {content} """ async def format_as_html(content: str) -> str: """Convert the report to HTML.""" # Simple markdown to HTML conversion import re html = content # Convert headers html = re.sub(r"^### (.+)$", r"

\1

", html, flags=re.MULTILINE) html = re.sub(r"^## (.+)$", r"

\1

", html, flags=re.MULTILINE) html = re.sub(r"^# (.+)$", r"

\1

", html, flags=re.MULTILINE) # Convert bold/italic html = re.sub(r"\*\*(.+?)\*\*", r"\1", html) html = re.sub(r"\*(.+?)\*", r"\1", html) # Convert paragraphs html = re.sub(r"\n\n", r"

", html) return f""" Generated Report

{html}

""" @flyte.trace async def generate_summary(content: str) -> str: """Generate an executive summary of the report.""" return await call_llm(content, SUMMARY_SYSTEM_PROMPT) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* ### When to trace and when not to Use `@flyte.trace` for operations that are expensive, non-deterministic, or call external APIs (like `generate_summary`). Skip it for cheap, deterministic transformations (like `format_as_markdown` and `format_as_html`) where re-running on retry is trivial. ## Parallel execution with asyncio.gather The `format_outputs` task runs all formatters concurrently: ```python @llm_env.task async def format_outputs(content: str) -> Dir: """ Generate multiple output formats in parallel. Uses asyncio.gather to run all formatting operations concurrently, maximizing efficiency when each operation is I/O-bound. Args: content: The final report content Returns: Directory containing all formatted outputs """ print("Generating output formats in parallel...") with flyte.group("formatting"): # Run all formatting operations in parallel markdown, html, summary = await asyncio.gather( format_as_markdown(content), format_as_html(content), generate_summary(content), ) # Write outputs to a directory output_dir = tempfile.mkdtemp() with open(os.path.join(output_dir, "report.md"), "w") as f: f.write(markdown) with open(os.path.join(output_dir, "report.html"), "w") as f: f.write(html) with open(os.path.join(output_dir, "summary.txt"), "w") as f: f.write(summary) print(f"Created outputs in {output_dir}") return await Dir.from_local(output_dir) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* ### How asyncio.gather works `asyncio.gather` takes multiple coroutines and runs them concurrently: ```python markdown, html, summary = await asyncio.gather( format_as_markdown(content), # Starts immediately format_as_html(content), # Starts immediately generate_summary(content), # Starts immediately ) # All three run concurrently, results returned in order ``` Without `gather`, these would run sequentially: ```python # Sequential (slower) markdown = await format_as_markdown(content) # Wait for completion html = await format_as_html(content) # Then start this summary = await generate_summary(content) # Then start this ``` ### When to use asyncio.gather Use `asyncio.gather` when: - Operations are independent (don't depend on each other's results) - Operations are I/O-bound (API calls, file operations) - You want to minimize total execution time Don't use `asyncio.gather` when: - Operations depend on each other - Operations are CPU-bound (use process pools instead) - Order of execution matters for side effects ## Grouping parallel operations The parallel formatting is wrapped in a group for UI clarity: ```python with flyte.group("formatting"): markdown, html, summary = await asyncio.gather(...) ``` In the Flyte UI, the traced call within the group is visible: ``` format_outputs โ””โ”€โ”€ formatting โ”œโ”€โ”€ format_as_markdown โ”œโ”€โ”€ format_as_html โ””โ”€โ”€ generate_summary (traced) ``` ## Collecting outputs in a directory The formatted outputs are written to a temporary directory and returned as a `Dir` artifact: ```python output_dir = tempfile.mkdtemp() with open(os.path.join(output_dir, "report.md"), "w") as f: f.write(markdown) with open(os.path.join(output_dir, "report.html"), "w") as f: f.write(html) with open(os.path.join(output_dir, "summary.txt"), "w") as f: f.write(summary) return await Dir.from_local(output_dir) ``` The `Dir.from_local()` call uploads the directory to Union.ai's artifact storage, making it available to downstream tasks or applications. ## The batch pipeline The batch pipeline processes multiple topics in parallel, demonstrating where `ReusePolicy` truly shines: ```python @driver_env.task async def report_batch_pipeline( topics: list[str], max_iterations: int = 3, quality_threshold: int = 8, ) -> list[Dir]: """ Generate reports for multiple topics in parallel. This is where ReusePolicy shines: with N topics, each going through up to max_iterations refinement cycles, the reusable container pool handles potentially N ร— 7 LLM calls efficiently without cold starts. Args: topics: List of topics to write about max_iterations: Maximum refinement cycles per topic quality_threshold: Minimum quality score to accept Returns: List of directories, each containing a report's formatted outputs """ print(f"Starting batch pipeline for {len(topics)} topics...") # Fan out: refine all reports in parallel # Each refine_report makes 2-7 LLM calls, all hitting the reusable pool with flyte.group("refine_all"): reports = await asyncio.gather(*[ refine_report(topic, max_iterations, quality_threshold) for topic in topics ]) print(f"All {len(reports)} reports refined, formatting outputs...") # Fan out: format all reports in parallel with flyte.group("format_all"): outputs = await asyncio.gather(*[ format_outputs(report) for report in reports ]) print(f"Batch pipeline complete! Generated {len(outputs)} reports.") return outputs ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* ### Pipeline flow 1. **Fan out refine_all**: Process all topics in parallel using `asyncio.gather` 2. **Fan out format_all**: Format all reports in parallel 3. **Return list of Dirs**: Each directory contains one report's outputs With 5 topics, each making ~7 LLM calls, the reusable container pool handles ~35 LLM calls efficiently without cold starts. ## Running the pipeline To run the batch pipeline: ```python if __name__ == "__main__": flyte.init_from_config() # Multiple topics to generate reports for topics = [ "The Impact of Large Language Models on Software Development", "Edge Computing: Bringing AI to IoT Devices", "Quantum Computing: Current State and Near-Term Applications", "The Rise of Rust in Systems Programming", "WebAssembly: The Future of Browser-Based Applications", ] print(f"Submitting batch run for {len(topics)} topics...") import sys sys.stdout.flush() # Run the batch pipeline - this will generate all reports in parallel, # with the reusable container pool handling 5 topics ร— ~7 LLM calls each run = flyte.run( report_batch_pipeline, topics=topics, max_iterations=3, quality_threshold=8, ) print(f"Batch report generation run URL: {run.url}") sys.stdout.flush() print("Waiting for pipeline to complete (Ctrl+C to skip)...") try: run.wait() print(f"Pipeline complete! Outputs: {run.outputs()}") except KeyboardInterrupt: print(f"\nSkipped waiting. Check status at: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/generate.py* ```bash uv run generate.py ``` The pipeline will: 1. Process all topics in parallel (each with iterative refinement) 2. Format all reports in parallel 3. Return a list of directories, each containing a report's outputs ## Cost optimization tips ### 1. Choose the right model The example uses `gpt-4o-mini` for cost efficiency. For higher quality (at higher cost), you could use `gpt-4o` or `gpt-4-turbo`: ```python response = await client.chat.completions.create( model="gpt-4o", # More capable, more expensive ... ) ``` ### 2. Tune iteration parameters Fewer iterations mean fewer API calls: ```python run = flyte.run( report_batch_pipeline, topics=["Topic A", "Topic B"], max_iterations=2, # Limit iterations quality_threshold=7, # Accept slightly lower quality ) ``` ### 3. Use caching effectively The `cache="auto"` setting on the environment caches task outputs. Running the same pipeline with the same inputs returns cached results instantly: ```python llm_env = flyte.TaskEnvironment( ... cache="auto", # Cache task outputs ) ``` ### 4. Scale the batch The batch pipeline already processes topics in parallel. To handle larger batches, adjust the `ReusePolicy`: ```python reusable=flyte.ReusePolicy( replicas=4, # More containers for larger batches concurrency=4, # Tasks per container ... ) ``` With 4 replicas ร— 4 concurrency = 16 slots, you can process 16 topics' refinement tasks concurrently. ## Next steps Learn how to **Project patterns > Advanced project: LLM reporting agent > Serving app** that connects to the pipeline outputs and provides an interactive UI for report generation. === PAGE: https://www.union.ai/docs/v2/union/user-guide/project-patterns/advanced-project/serving-app === Connect a serving app to a pipeline so it can display results and take input. # Serving app The final piece is a serving application that displays generated reports and provides an interactive interface. This demonstrates how to connect apps to pipeline outputs using `RunOutput`. ## App environment configuration The `AppEnvironment` defines how the Streamlit application runs and connects to the batch report pipeline: ```python # Define the app environment env = AppEnvironment( name="report-generator-app", description="Interactive report generator with AI-powered refinement", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "streamlit>=1.41.0", ), args=["streamlit", "run", "app.py", "--server.port", "8080"], port=8080, resources=flyte.Resources(cpu=1, memory="2Gi"), parameters=[ # Connect to the batch pipeline output (list of report directories) Parameter( name="reports", value=RunOutput( task_name="driver.report_batch_pipeline", type="directory", ), download=True, env_var="REPORTS_PATH", ), ], include=["app.py"], requires_auth=False, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/serve.py* ### Key configuration | Setting | Purpose | |---------|---------| | `args` | Command to run the Streamlit app | | `port` | Port the app listens on | | `parameters` | Inputs to the app, including pipeline connections | | `include` | Additional files to bundle with the app | ### Connecting to pipeline output with RunOutput The `RunOutput` parameter connects the app to the batch pipeline's output: ```python Parameter( name="reports", value=RunOutput( task_name="driver.report_batch_pipeline", type="directory", ), download=True, env_var="REPORTS_PATH", ) ``` This configuration: 1. **Finds the latest run** of `report_batch_pipeline` in the `driver` environment 2. **Downloads the output** to local storage (`download=True`) 3. **Sets an environment variable** with the path (`REPORTS_PATH`) The app can then scan this directory for all generated reports. ## The Streamlit application The app loads and displays all generated reports from the batch pipeline: ```python def load_report_from_dir(report_dir: str) -> dict | None: """Load a single report from a directory.""" if not os.path.isdir(report_dir): return None report = {"path": report_dir, "name": os.path.basename(report_dir)} md_path = os.path.join(report_dir, "report.md") if os.path.exists(md_path): with open(md_path) as f: report["markdown"] = f.read() html_path = os.path.join(report_dir, "report.html") if os.path.exists(html_path): with open(html_path) as f: report["html"] = f.read() summary_path = os.path.join(report_dir, "summary.txt") if os.path.exists(summary_path): with open(summary_path) as f: report["summary"] = f.read() # Only return if we found at least markdown content return report if "markdown" in report else None def load_all_reports() -> list[dict]: """Load all reports from the batch pipeline output.""" reports_path = os.environ.get("REPORTS_PATH") if not reports_path or not os.path.exists(reports_path): return [] reports = [] # Check if this is a single report directory (has report.md directly) if os.path.exists(os.path.join(reports_path, "report.md")): report = load_report_from_dir(reports_path) if report: report["name"] = "Report" reports.append(report) else: # Batch output: scan subdirectories for reports for entry in sorted(os.listdir(reports_path)): entry_path = os.path.join(reports_path, entry) report = load_report_from_dir(entry_path) if report: reports.append(report) return reports ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/app.py* ### Displaying multiple reports The app provides a sidebar for selecting between reports when multiple are available: ```python reports = load_all_reports() if reports: # Sidebar for report selection if multiple reports if len(reports) > 1: st.sidebar.header("Select Report") report_names = [f"Report {i+1}: {r['name']}" for i, r in enumerate(reports)] selected_idx = st.sidebar.selectbox( "Choose a report to view:", range(len(reports)), format_func=lambda i: report_names[i], ) selected_report = reports[selected_idx] st.sidebar.markdown(f"**Viewing {len(reports)} reports**") else: selected_report = reports[0] st.header(f"Generated Report: {selected_report['name']}") # Summary section if "summary" in selected_report: with st.expander("Executive Summary", expanded=True): st.write(selected_report["summary"]) # Tabbed view for different formats tab_md, tab_html = st.tabs(["Markdown", "HTML Preview"]) with tab_md: st.markdown(selected_report.get("markdown", "")) with tab_html: if "html" in selected_report: st.components.v1.html(selected_report["html"], height=600, scrolling=True) # Download options st.subheader("Download") col1, col2, col3 = st.columns(3) with col1: if "markdown" in selected_report: st.download_button( label="Download Markdown", data=selected_report["markdown"], file_name="report.md", mime="text/markdown", ) with col2: if "html" in selected_report: st.download_button( label="Download HTML", data=selected_report["html"], file_name="report.html", mime="text/html", ) with col3: if "summary" in selected_report: st.download_button( label="Download Summary", data=selected_report["summary"], file_name="summary.txt", mime="text/plain", ) else: st.info("No reports generated yet. Run the batch pipeline to create reports.") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/advanced-project/app.py* Features: - **Report selector**: Sidebar navigation when multiple reports exist - **Executive summary**: Expandable section with key takeaways - **Tabbed views**: Switch between Markdown and HTML preview - **Download buttons**: Export in any format ### Generation instructions The app includes instructions for generating new reports: ```python st.divider() st.header("Generate New Reports") st.write(""" To generate reports, run the batch pipeline: ```bash uv run generate.py ``` This generates reports for multiple topics in parallel, demonstrating how ReusePolicy efficiently handles many concurrent LLM calls. """) # Show pipeline parameters info with st.expander("Pipeline Parameters"): st.markdown(""" **Available parameters:** | Parameter | Default | Description | |-----------|---------|-------------| | `topics` | (required) | List of topics to write about | | `max_iterations` | 3 | Maximum refinement cycles per topic | | `quality_threshold` | 8 | Minimum score (1-10) to accept | **Example:** CODE5 """) CODE6python if __name__ == "__main__": flyte.init_from_config() # Deploy the report generator app print("Deploying report generator app...") deployment = flyte.serve(env) print(f"App deployed at: {deployment.url}") CODE7bash uv run serve.py CODE8bash uv run generate.py CODE9bash uv run serve.py ``` 3. **Access the app** at the provided URL and browse all generated reports The app automatically picks up the latest pipeline run, so you can generate new batches and always see the most recent results. ## Automatic updates with RunOutput The `RunOutput` connection is evaluated at app startup. Each time the app restarts or redeploys, it fetches the latest batch pipeline output. For real-time updates without redeployment, you could: 1. Poll for new runs using the Flyte API 2. Implement a webhook that triggers app refresh 3. Use a database to track run status ## Complete example structure Here's the full project structure: CODE10 ## Running the complete example 1. **Set up the secret**: CODE11 2. **Run the pipeline**: CODE12 3. **Deploy the app**: CODE13 4. **Open the app URL** and view your generated report ## Summary This example demonstrated: | Feature | What it does | |---------|--------------| | `ReusePolicy` | Keeps containers warm for high-throughput batch processing | | `@flyte.trace` | Checkpoints LLM calls for recovery and observability | | `RetryStrategy` | Handles transient API failures gracefully | | `flyte.group` | Organizes parallel batches and iterations in the UI | | `asyncio.gather` | Fans out to process multiple topics concurrently | | Pydantic models | Structured LLM outputs | | `AppEnvironment` | Deploys interactive Streamlit apps | | `RunOutput` | Connects apps to pipeline outputs | These patterns form the foundation for building production-grade AI workflows that are resilient, observable, and cost-efficient at scale. === PAGE: https://www.union.ai/docs/v2/union/user-guide/run-scaling === Tune task overhead, batching, reusable containers, and fanout to scale your workflows. # Scale your runs This guide helps you understand and optimize the performance of your Flyte workflows. Whether you're building latency-sensitive applications or high-throughput data pipelines, these docs will help you make the right architectural choices. ## Understanding Flyte execution Before optimizing performance, it's important to understand how Flyte executes your workflows: - ****Scale your runs > Data flow****: Learn how data moves between tasks, including inline vs. raw (by-reference) data, caching mechanisms, and storage configuration. - ****Scale your runs > Life of a run****: Understand what happens when you invoke `flyte.run()`, from code analysis and image building to task execution and state management. ## Performance optimization Once you understand the fundamentals, dive into performance tuning: - ****Scale your runs > Scale your workflows****: A comprehensive guide to optimizing workflow performance, covering latency vs. throughput, task overhead analysis, batching strategies, reusable containers, and more. ## Key concepts for scaling When scaling your workflows, keep these principles in mind: 1. **Task overhead matters**: The overhead of creating a task (uploading data, enqueuing, creating containers) should be much smaller than the task runtime. 2. **Batch for throughput**: For large-scale data processing, batch multiple items into single tasks to reduce overhead. 3. **Reusable containers**: Eliminate container startup overhead and enable concurrent execution with reusable containers. 4. **Traces for lightweight ops**: Use traces instead of tasks for lightweight operations that need checkpointing. 5. **Limit fanout**: Keep the total number of actions per run below 200k. 6. **Choose the right data types**: Use reference types (files, directories, DataFrames) for large data and inline types for small data. For detailed guidance on each of these topics, see **Scale your runs > Scale your workflows**. {{< subpage-cards >}} ## Subpages - **Scale your runs > Data flow** - How data moves between tasks, and where that movement costs you time. - **Scale your runs > Life of a run** - What actually happens when you call flyte.run, step by step. - **Scale your runs > Scale your workflows** - Trade off execution overhead, data transfer, and concurrency to make a workload faster. === PAGE: https://www.union.ai/docs/v2/union/user-guide/run-scaling/data-flow === How data moves between tasks, and where that movement costs you time. # Data flow Understanding how data flows between tasks is critical for optimizing workflow performance in Flyte. Tasks take inputs and produce outputs, with data flowing through your workflow using an efficient transport layer. > [!NOTE] > This page focuses on **how** data moves at runtime. For the static map of **what** lives in the control plane database versus the data plane object store (including what *metadata*, *literals*, and *raw data* mean), see **Get started > Core concepts > Where your data lives**. ## Overview Flyte tasks are run to completion. Each task takes inputs and produces exactly one output. Even if multiple instances run concurrently (such as in retries), only one output will be accepted. This deterministic data flow model provides several key benefits: 1. **Reduced boilerplate**: Automatic handling of files, DataFrames, directories, custom types, data classes, Pydantic models, and primitive types without manual serialization. 2. **Type safety**: Optional type annotations enable deeper type understanding, automatic UI form generation, and runtime type validation. 3. **Efficient transport**: Data is passed by reference (files, directories, DataFrames) or by value (primitives) based on type. 4. **Durable storage**: All data is stored durably and accessible through APIs and the UI. 5. **Caching support**: Efficient caching using shallow immutable references for referenced data. ## Data types and transport Flyte handles different data types with different transport mechanisms: ### Passed by reference These types are not copied but passed as references to storage locations. That offloaded, by-reference content is called **raw data**: - **Files**: `flyte.io.File` - **Directories**: `flyte.io.Dir` - **Dataframes**: `flyte.io.DataFrame`, `pd.DataFrame`, `pl.DataFrame`, etc. Dataframes are automatically converted to Parquet format and read using Apache Arrow for zero-copy reads. Use `flyte.io.DataFrame` for lazy materialization to any supported type like pandas or polars. **Tasks > Build tasks > DataFrames** ### Passed by value (inline I/O) Primitive and structured types are serialized and passed inline: | Type Category | Examples | Serialization | |--------------|----------|---------------| | **Primitives** | `int`, `float`, `str`, `bool`, `None` | Protobuf primitive literal (`None`: protobuf none-type scalar) | | **Time types** | `datetime.datetime`, `datetime.date`, `datetime.timedelta` | Protobuf primitive literal | | **Typed collections** | `list[T]`, `dict[str, T]` | Protobuf collection or map literal | | **Tuples** | `tuple[T1, T2]`, `typing.NamedTuple` | MessagePack | | **Untyped dicts** | `dict` | MessagePack | | **Data structures** | data classes, Pydantic `BaseModel` | MessagePack | | **Enums** | `enum.Enum` subclasses | Protobuf string literal | | **Unions** | `Union[T1, T2]`, `Optional[T]` | Protobuf union literal | | **Protobuf** | `google.protobuf.Message` | `google.protobuf.Struct` | Flyte stores primitives, time types, enums, typed collections, and unions as native protobuf literals, and uses MessagePack for typed tuples, untyped dicts, data classes, and Pydantic models. > [!NOTE] > If type annotations are not used, or if `typing.Any` or unrecognized types are used, data will be pickled. By default, pickled objects smaller than 10KB are passed inline, while larger pickled objects are automatically passed as a file. Pickling allows for progressive typing but should be used carefully. ## Task execution and data flow ### Input download When a task starts: 1. **Inline inputs download**: The task downloads inline inputs from the configured Flyte object store. 2. **Size limits**: When one task calls another, inline inputs and outputs are limited to 10 MiB by default. Change the limit with the `max_inline_io_bytes` parameter of `@env.task` or `override()`. See **Tasks > Configure tasks > Additional task settings > Inline I/O threshold**. 3. **Memory consideration**: Inline data is materialized in memory, so adjust your task resources accordingly. 4. **Raw data materialization**: Raw data (files, directories) is passed using special types in `flyte.io`. Dataframes are automatically materialized if using `pd.DataFrame`. Use `flyte.io.DataFrame` to avoid automatic materialization. ### Output upload When a task returns data: 1. **Inline data**: Uploaded to the Flyte object store configured at the organization, project, or domain level. 2. **Raw data**: Stored under the same bucket prefix by default, or routed to a different location using `flyte.with_runcontext(raw_data_path=...)`. 3. **Separate prefixes**: Each task creates one output per retry attempt in separate prefixes, making data incorruptible by design. ## Task-to-task data flow When a task invokes downstream tasks: 1. **Input recording**: The input to the downstream task is recorded to the object store. 2. **Reference upload**: All referenced objects are uploaded (if not already present). 3. **Task invocation**: The downstream task is invoked on the remote server. 4. **Parallel execution**: When multiple tasks are invoked in parallel using `flyte.map` or `asyncio`, inputs are written in parallel. 5. **Storage layer**: Data writing uses the `flyte.storage` layer, backed by the Rust-based `object-store` crate and optionally `fsspec` plugins. 6. **Output download**: Once the downstream task completes, inline outputs are downloaded and returned to the calling task. ## Caching and data hashing Understanding how Flyte caches data is essential for performance optimization. ### Cache key computation A cache hit occurs when the following components match: - **Task name**: The fully-qualified task name - **Computed input hash**: Hash of all inputs (excluding `ignored_inputs`) - **Task interface hash**: Hash of input and output types - **Cache version**: User-specified or automatically computed ### Inline data caching All inline data is cached using a consistent hashing system. The cache key is derived from the data content. ### Raw data hashing Raw data (DataFrames, files, directories) is hashed shallowly by default using the hash of the storage location, so a downstream task does not cache-hit on identical content stored at a new path. To cache on content instead, attach a content hash at production time with `flyte.io.HashFunction`. See **Tasks > Configure tasks > Caching > Content-based caching for DataFrames, files, and directories**. ### Cache control Control caching behavior using `flyte.with_runcontext`: - **Scope**: Set `cache_lookup_scope` to `"global"` or `"project-domain"`. - **Disable cache**: Set `overwrite_cache=True` to force re-execution. For more details on caching configuration, see **Tasks > Configure tasks > Caching**. ## Traces and data flow When using **Tasks > Build tasks > Traces**, the data flow behavior is different: 1. **Full execution first**: The trace is fully executed before inputs and outputs are recorded. 2. **Checkpoint behavior**: Recording happens like a checkpoint at the end of trace execution. 3. **Streaming iterators**: The entire output is buffered and recorded after the stream completes. Buffering is pass-through, allowing caller functions to consume output while buffering. 4. **Chained traces**: All traces are recorded after the last one completes consumption. 5. **Same process with `asyncio`**: Traces run within the same Python process and support `asyncio` parallelism, so failures can be retried, effectively re-running the trace. 6. **Lightweight overhead**: Traces only have the overhead of data storage (no task orchestration overhead). > [!NOTE] > Traces are not a substitute for tasks if you need caching. Tasks provide full caching capabilities, while traces provide lightweight checkpointing with storage overhead. However, traces support concurrent execution using `asyncio` patterns within a single task. ## Object stores and latency considerations By default, Flyte uses object stores like S3, GCS, Azure Storage, and R2 to persist task inputs, outputs, and offloaded raw data. These have high latency for smaller objects, so: - **Minimum task duration**: Tasks should take at least a second to run to amortize storage overhead. - **Future improvements**: High-performance key/value or relational stores like Redis and PostgreSQL may be supported in the future as alternative offload backends. Contact the Union team if you're interested. ## Configuring data storage ### Organization and project level Object stores are configured at the organization level or per project/domain. Documentation for this configuration is coming soon. ### Per-run configuration Configure raw data storage on a per-run basis using `flyte.with_runcontext`: ```python run = flyte.with_runcontext( raw_data_path="s3://my-bucket/custom-path" ).run(my_task, input_data=data) ``` This allows you to control where raw data (files, directories, DataFrames) is stored for specific runs. See **Tasks > Run and deploy tasks > Run context** for the full set of options. === PAGE: https://www.union.ai/docs/v2/union/user-guide/run-scaling/life-of-a-run === What actually happens when you call flyte.run, step by step. # Life of a run Understanding what happens when you invoke `flyte.run()` is crucial for optimizing workflow performance and debugging issues. This guide walks through each phase of task execution from submission to completion. ## Overview When you execute `flyte.run()`, the system goes through several phases: 1. **Code analysis and preparation**: Discover environments and images 2. **Image building**: Build container images if changes are detected 3. **Code bundling**: Package your Python code 4. **Upload**: Transfer the code bundle to object storage 5. **Run creation**: Submit the run to the backend 6. **Task execution**: Execute the task in the data plane 7. **State management**: Track and persist execution state > [!NOTE] > This walkthrough follows a run's *control flow*. For what the inputs and outputs actually are (**literals**, stored inline or offloaded as **raw data**) and where each lives, see **Get started > Core concepts > Where your data lives**. ## Phase 1: Code analysis and preparation When `flyte.run()` is invoked: 1. **Environment discovery**: Flyte analyzes your code and finds all relevant `flyte.TaskEnvironment` instances by walking the `depends_on` hierarchy. 2. **Image identification**: Discovers unique `flyte.Image` instances used across all environments. 3. **Image building**: Starts the image building process. Images are only built if a change is detected. > [!NOTE] > If you invoke `flyte.run()` multiple times within the same Python process without changing code (such as in a notebook or script), the code bundling and image building steps are done only once. This can dramatically speed up iteration. ## Phase 2: Image building Container images provide the runtime environment for your tasks: - **Change detection**: Images are only rebuilt if changes are detected in dependencies or configuration. - **Caching**: Previously built images are reused when possible. - **Parallel builds**: Multiple images can be built concurrently. For more details on container images, see **Tasks > Configure tasks > Container images**. ## Phase 3: Code bundling After images are built, your project files are bundled: ### Default: `copy_style="loaded_modules"` By default, all Python modules referenced by the invoked tasks through module-level import statements are automatically copied. This provides a good balance between completeness and efficiency. ### Alternative: `copy_style="none"` Skip bundling by setting `copy_style="none"` in `flyte.with_runcontext()` and adding all code into `flyte.Image`: ```python import pathlib # Add code to image image = flyte.Image.from_debian_base().with_source_folder(pathlib.Path("/path/to/code")) # Or use Dockerfile image = flyte.Image.from_dockerfile(pathlib.Path("Dockerfile"), registry="myregistry.com/my-org", name="my-image") # Skip bundling run = flyte.with_runcontext(copy_style="none", version="v1.0.0").run(my_task, input_data=data) ``` For more details on code packaging, see **Tasks > Run and deploy tasks > Code packaging for on-cluster execution**. ## Phase 4: Upload code bundle Once the code bundle is created: 1. **Request signed URL**: The SDK sends the bundle checksum and target path to the control plane. 2. **Control plane obtains URL**: The control plane calls the data plane to obtain a signed URL for that checksum and path. 3. **Direct upload**: The signed URL is returned to the SDK, which uploads the code bundle directly to the object store. ## Phase 5: Run creation and queuing 1. **Upload inputs**: The SDK uploads the run's inputs to the data plane `dataproxy` service, which writes them to the object store. The input values never pass through the control plane. 2. **Invoke `CreateRun`**: The SDK calls the `CreateRun` API with a reference (URI) to the uploaded inputs, not the input values themselves. 3. **En-queue a run**: The run is queued into the Union control plane. 4. **Hand off to executor**: The Union control plane hands the task to the Executor Service in your data plane. 5. **Create action**: The parent task action (called `a0`) is created. ## Phase 6: Task execution in data plane ### Container startup 1. **Container starts**: The task container starts in your data plane. 2. **Download code bundle**: The Flyte runtime downloads the code bundle from object storage. 3. **Inflate task**: The task is inflated from the code bundle. 4. **Download inputs**: The task's inputs are downloaded from the object store. 5. **Execute task**: The task is executed with context and inputs. ### Invoking downstream tasks If the task invokes other tasks: 1. **Controller thread**: A controller thread starts to communicate with the backend Queue Service. 2. **Monitor status**: The controller monitors the status of downstream actions. 3. **Crash recovery**: If the task crashes, the action identifier is deterministic, allowing the task to resurrect its state from Union control plane. 4. **Replay**: The controller efficiently replays state (even at large scale) to find missing completions and resume monitoring. ### Execution flow diagram ```mermaid sequenceDiagram participant Client as SDK/Client participant Control as Control plane
(Queue Service) participant Data as Data plane
(Executor) participant ObjStore as Object Store participant Container as Task Container Client->>Client: Analyze code & discover environments Client->>Client: Build images (if changed) Client->>Client: Bundle code Client->>Control: Request signed URL (checksum, path) Control->>Data: Get signed URL for bundle Data-->>Control: Signed URL Control-->>Client: Signed URL Client->>ObjStore: Upload code bundle (signed URL) Client->>Data: Upload inputs (dataproxy) Data->>ObjStore: Write inputs Client->>Control: CreateRun API (input URI) Control->>Data: Queue task (create action a0) Data->>Container: Start container Container->>Data: Request code bundle Data->>ObjStore: Read code bundle ObjStore-->>Data: Code bundle Data-->>Container: Code bundle Container->>Container: Inflate task Container->>Data: Request inputs Data->>ObjStore: Read inputs ObjStore-->>Data: Inputs Data-->>Container: Inputs Container->>Container: Execute task alt Invokes downstream tasks Container->>Container: Start controller thread Container->>Control: Submit downstream tasks Control->>Data: Queue downstream actions Container->>Control: Monitor downstream status Control-->>Container: Status updates end Container->>Data: Upload outputs Data->>ObjStore: Write outputs Container->>Control: Complete Control-->>Client: Run complete ``` ## Action identifiers and crash recovery Flyte uses deterministic action identifiers to enable robust crash recovery: - **Consistent identifiers**: Action identifiers are consistently computed based on task and invocation context. - **Re-run identical**: In any re-run, the action identifier is identical for the same invocation. - **Multiple invocations**: Multiple invocations of the same task receive unique identifiers. - **Efficient resurrection**: On crash, the `a0` action resurrects its state from Union control plane efficiently, even at large scale. - **Replay and resume**: The controller replays execution until it finds missing completions and starts watching them. ## Downstream task execution When downstream tasks are invoked: 1. **Action creation**: Downstream actions are created with unique identifiers. 2. **Queue assignment**: Actions are handed to an executor, which can be selected using a queue or from the general pool. 3. **Parallel execution**: Multiple downstream tasks can execute in parallel. 4. **Result aggregation**: Results are aggregated and returned to the parent task. ## Reusable containers When using **Tasks > Configure tasks > Reusable containers**, the execution model changes: 1. **Environment spin-up**: The container environment is first spun up with configured replicas. 2. **Task allocation**: Tasks are allocated to available replicas in the environment. 3. **Scaling**: If all replicas are busy, new replicas are spun up (up to the configured maximum), or tasks are backlogged in queues. 4. **Container reuse**: The same container handles multiple task executions, reducing startup overhead. 5. **Lifecycle management**: Containers are managed according to `ReusePolicy` settings (`idle_ttl`, `scaledown_ttl`, etc.). ### Reusable container execution flow ```mermaid sequenceDiagram participant Control as Queue Service participant Executor as Executor Service participant Pool as Container Pool participant Replica as Container Replica Control->>Executor: Submit task alt Reusable containers enabled Executor->>Pool: Request available replica alt Replica available Pool->>Replica: Allocate task Replica->>Replica: Execute task Replica->>Pool: Task complete (ready for next) else No replica available alt Can scale up Executor->>Pool: Create new replica Pool->>Replica: Spin up new container Replica->>Replica: Execute task Replica->>Pool: Task complete else At max replicas Executor->>Pool: Queue task Pool-->>Executor: Wait for available replica Pool->>Replica: Allocate when available Replica->>Replica: Execute task Replica->>Pool: Task complete end end else No reusable containers Executor->>Replica: Create new container Replica->>Replica: Execute task Replica->>Executor: Complete & terminate end Replica-->>Control: Return results ``` ## State replication and visualization ### Queue service to run service 1. **Reliable replication**: Queue Service reliably replicates execution state back to Run Service. 2. **Eventual consistency**: The Run Service may be slightly behind the actual execution state. 3. **Visualization**: Run Service paints the entire run onto the UI. ### UI limitations - **Current limit**: The UI is currently limited to displaying 200k actions per run. Past that point the run continues to execute, but later actions are no longer tracked and the UI shows a truncation notice. - **Future improvements**: This limit will be increased in future releases. Contact the Union team if you need higher limits. ## Optimization opportunities Understanding the life of a run reveals several optimization opportunities: 1. **Reuse Python process**: Run `flyte.run()` multiple times in the same process to avoid re-bundling code. 2. **Skip bundling**: Use `copy_style="none"` and bake code into images for faster startup. 3. **Reusable containers**: Use reusable containers to eliminate container startup overhead. 4. **Parallel execution**: Invoke multiple downstream tasks concurrently using `flyte.map()` or `asyncio`. 5. **Efficient data flow**: Minimize data transfer by using reference types (files, directories) instead of inline data. 6. **Caching**: Enable task caching to avoid redundant computation. For detailed performance tuning guidance, see **Scale your runs > Scale your workflows**. === PAGE: https://www.union.ai/docs/v2/union/user-guide/run-scaling/scale-your-workflows === Trade off execution overhead, data transfer, and concurrency to make a workload faster. # Scale your workflows Performance optimization in Flyte involves understanding the interplay between task execution overhead, data transfer, and concurrency. This guide helps you identify bottlenecks and choose the right patterns for your workload. ## Understanding performance dimensions Performance optimization focuses on two key dimensions: ### Latency **Goal**: Minimize end-to-end execution time for individual workflows. **Characteristics**: - Fast individual actions (milliseconds to seconds) - Total action count typically less than 1,000 - Critical for interactive applications and real-time processing - Multi-step inference, with reusing model or data in memory (use reusable containers with [@alru.cache](https://pypi.org/project/async-lru/)) **Recommended approach**: - Use tasks for orchestration and parallelism - Use **Tasks > Build tasks > Traces** for fine-grained checkpointing - Model parallelism using `asyncio` and use things methods like `asyncio.as_completed` or `asyncio.gather` to join the parallelism - Use **Tasks > Configure tasks > Reusable containers** with concurrency to eliminate startup overhead and optimize resource utilization ### Throughput **Goal**: Maximize the number of items processed per unit time. **Characteristics**: - Processing large datasets (millions of items) - High total action count (10k+ actions) - Batch processing, large-scale batch inference and ETL workflows **Recommended approach**: - Batch workloads to reduce overhead - Limit fanout to manage system load - Use reusable containers with concurrency for maximum utilization - Balance task granularity with overhead ## Task execution overhead Understanding task overhead is critical for performance optimization. When you invoke a task, several operations occur: | Operation | Symbol | Description | |-----------|--------|-------------| | **Upload data** | `u` | Time to upload input data to object store | | **Download data** | `d` | Time to download input data from object store | | **Enqueue task** | `e` | Time to enqueue task in Queue Service | | **Create instance** | `t` | Time to create task container instance | **Total overhead per task**: `2u + 2d + e + t` This overhead includes: - Uploading inputs from the parent task (`u`) - Downloading inputs in the child task (`d`) - Uploading outputs from the child task (`u`) - Downloading outputs in the parent task (`d`) - Enqueuing the task (`e`) - Creating the container instance (`t`) ### The overhead principle For efficient execution, task overhead should be much smaller than task runtime: ``` Total overhead (2u + 2d + e + t) << Task runtime ``` If task runtime is comparable to or less than overhead, consider: 1. **Batching**: Combine multiple work items into a single task 2. **Traces**: Use traces instead of tasks for lightweight operations 3. **Reusable containers**: Eliminate container creation overhead (`t`) 4. **Local execution**: Run lightweight operations within the parent task A driver task that only calls other tasks has the same overhead problem in reverse: it holds a pod for as long as its children run. An **Tasks > Build tasks > Orchestrator tasks** has no pod of its own, so it starts in milliseconds and holds nothing while it waits. ## System architecture and data flow To optimize performance, understand how tasks flow through the system: 1. **Control plane to data plane**: Tasks flow from the control plane (Run Service, Queue Service) to the data plane (Executor Service). 2. **Data movement**: Data moves between tasks through object storage. See **Scale your runs > Data flow** for details. 3. **State replication**: Queue Service reliably replicates state back to Run Service for visualization. The Run Service may be slightly behind actual execution. For a detailed walkthrough of task execution, see **Scale your runs > Life of a run**. ## Optimization strategies ### 1. Use reusable containers for concurrency **Tasks > Configure tasks > Reusable containers** eliminate the container creation overhead (`t`) and enable concurrent task execution: ```python import flyte from datetime import timedelta # Define reusable environment env = flyte.TaskEnvironment( name="high-throughput", reusable=flyte.ReusePolicy( replicas=(2, 10), # Auto-scale from 2 to 10 replicas concurrency=5, # 5 tasks per replica = 50 max concurrent scaledown_ttl=timedelta(minutes=10), idle_ttl=timedelta(hours=1) ) ) @env.task async def process_item(item: dict) -> dict: # Process individual item return {"processed": item["id"]} ``` **Benefits**: - Eliminates container startup overhead (`t โ‰ˆ 0`) - Supports concurrent execution (multiple tasks per container) - Auto-scales based on demand - Reuses Python environment and loaded dependencies **Limitations**: - Concurrency is limited by CPU and I/O resources in the container - Memory requirements scale with total working set size - Best for I/O-bound tasks or async operations ### 2. Batch workloads to reduce overhead For high-throughput processing, batch multiple items into a single task: ```python @env.task async def process_batch(items: list[dict]) -> list[dict]: """Process a batch of items in a single task.""" results = [] for item in items: result = await process_single_item(item) results.append(result) return results @env.task async def process_large_dataset(dataset: list[dict]) -> list[dict]: """Process 1M items with batching.""" batch_size = 1000 # Adjust based on overhead calculation batches = [dataset[i:i + batch_size] for i in range(0, len(dataset), batch_size)] # Process batches in parallel (1000 tasks instead of 1M) results = await asyncio.gather(*[process_batch(batch) for batch in batches]) # Flatten results return [item for batch_result in results for item in batch_result] ``` **Benefits**: - Reduces total number of tasks (e.g., 1000 tasks instead of 1M) - Amortizes overhead across multiple items - Lower load on Queue Service and object storage **Choosing batch size**: 1. Calculate overhead: `overhead = 2u + 2d + e + t` 2. Target task runtime: `runtime > 10 ร— overhead` (rule of thumb) 3. Adjust batch size to achieve target runtime 4. Consider memory constraints (larger batches require more memory) ### 3. Use traces for lightweight operations **Tasks > Build tasks > Traces** provide fine-grained checkpointing with minimal overhead: ```python @flyte.trace async def fetch_data(url: str) -> dict: """Traced function for API call.""" response = await http_client.get(url) return response.json() @flyte.trace async def transform_data(data: dict) -> dict: """Traced function for transformation.""" return {"transformed": data} @env.task async def process_workflow(urls: list[str]) -> list[dict]: """Orchestrate using traces instead of tasks.""" results = [] for url in urls: data = await fetch_data(url) transformed = await transform_data(data) results.append(transformed) return results ``` **Benefits**: - Only storage overhead (no task orchestration overhead) - Runs in the same Python process with asyncio parallelism - Provides checkpointing and resumption - Visible in execution logs and UI **Trade-offs**: - No caching (use tasks for cacheable operations) - Shares resources with the parent task (CPU, memory) - Storage writes may still be slow due to object store latency **When to use traces**: - API calls and external service interactions - Deterministic transformations that need checkpointing - Operations taking more than 1 second (to amortize storage overhead) ### 4. Limit fanout for system stability Flyte tracks a bounded number of actions per run for monitoring and visualization: - **Current limit**: 200k actions per run - **What happens past the limit**: The run keeps executing โ€” this is not an execution gate. Actions beyond the cap are not tracked by the run service, so the UI stops showing them and displays a truncation notice. Fetching a specific action directly (`flyte get action `) still returns correct data, because it reads from the run database rather than the tracked view. - **Future**: Higher limits will be supported (contact the Union team if needed) Staying under the limit keeps the whole run observable. It counts the **total** actions in the run, summed across every map and fanout. Note that per-map `concurrency` does **not** help here: it throttles how many actions run *at once*, not how many the run creates in total, so only batching reduces the count. For how the two controls compose, see **Tasks > Build tasks > Controlling parallel execution > Per-map concurrency vs. the run-level action cap**. **Example: Control fanout with batching** ```python @env.task async def process_million_items(items: list[dict]) -> list[dict]: """Process 1M items with controlled fanout.""" # Target 10k tasks, each processing 100 items batch_size = 100 max_fanout = 10000 batches = [items[i:i + batch_size] for i in range(0, len(items), batch_size)] # Use flyte.map for parallel execution results = await flyte.map(process_batch, batches) return [item for batch in results for item in batch] ``` ### 5. Optimize data transfer Minimize data transfer overhead by choosing appropriate data types: **Use reference types for large data**: ```python from flyte.io import File, Dir, DataFrame @env.task async def process_large_file(input_file: File) -> File: """Files passed by reference, not copied.""" # Download only when needed local_path = input_file.download() # Process file result_path = process(local_path) # Upload result return File.new_remote(result_path) ``` **Use inline types for small data**: ```python @env.task async def process_metadata(metadata: dict) -> dict: """Small dicts passed inline efficiently.""" return {"processed": metadata} ``` **Guideline**: - **< 10 MiB**: Use inline types (primitives, small dicts, lists) - **> 10 MiB**: Use reference types (File, Dir, DataFrame) - **Adjust**: Use the `max_inline_io_bytes` parameter of `@env.task` or `override()` to change the threshold. See **Tasks > Configure tasks > Additional task settings > Inline I/O threshold**. See **Scale your runs > Data flow** for details on data types and transport. ### 6. Use caching Enable **Tasks > Configure tasks > Caching** to avoid redundant computation: ```python @env.task(cache="auto") async def expensive_computation(input_data: dict) -> dict: """Automatically cached based on inputs.""" # Expensive operation return result ``` **Benefits**: - Skips re-execution for identical inputs - Reduces overall workflow runtime - Preserves resources for new computations **When to use**: - Deterministic tasks (same inputs โ†’ same outputs) - Expensive computations (model training, large data processing) - Stable intermediate results ### 7. Parallelize with `flyte.map` Use **Tasks > Build tasks > Fanout** for data-parallel workloads: ```python @env.task async def process_item(item: dict) -> dict: return {"processed": item} @env.task async def parallel_processing(items: list[dict]) -> list[dict]: """Process items in parallel using map.""" results = await flyte.map(process_item, items) return results ``` **Benefits**: - Automatic parallelization - Dynamic scaling based on available resources - Built-in error handling and retries **Best practices**: - Combine with batching to control fanout - Use with reusable containers for maximum throughput - Consider memory and resource limits ## Performance tuning workflow Follow this workflow to optimize your Flyte workflows: 1. **Profile**: Measure task execution times and identify bottlenecks. 2. **Calculate overhead**: Estimate `2u + 2d + e + t` for your tasks. 3. **Compare**: Check if `task runtime >> overhead`. If not, optimize. 4. **Batch**: Increase batch size to amortize overhead. 5. **Reusable containers**: Enable reusable containers to eliminate `t`. 6. **Traces**: Use traces for lightweight operations within tasks. 7. **Cache**: Enable caching for deterministic, expensive tasks. 8. **Limit fanout**: Keep total actions below 200k. 9. **Monitor**: Use the UI to monitor execution and identify issues. 10. **Iterate**: Continuously refine based on performance metrics. ## Real-world example: PyIceberg batch processing For an example of efficient data processing with Flyte, see the [PyIceberg parallel batch aggregation example](https://github.com/flyteorg/flyte-sdk/blob/main/examples/data_processing/pyiceberg_example.py). This example demonstrates: - **Zero-copy data passing**: Pass file paths instead of data between tasks - **Reusable containers with concurrency**: Maximize CPU utilization across workers - **Parallel file processing**: Use `asyncio.gather()` to process multiple files concurrently - **Efficient batching**: Distribute parquet files across worker tasks Key pattern from the example: ```python # Instead of loading entire table, get file paths file_paths = [task.file.file_path for task in table.scan().plan_files()] # Distribute files across partitions (zero-copy!) partition_files = distribute_files(file_paths, num_partitions) # Process partitions in parallel results = await asyncio.gather(*[ aggregate_partition(files, partition_id) for partition_id, files in enumerate(partition_files) ]) ``` This approach achieves true parallel file processing without loading the entire dataset into memory. ## Example: Optimizing a data pipeline ### Before optimization ```python @env.task async def process_item(item: dict) -> dict: # Very fast operation (~100ms) return {"processed": item["id"]} @env.task async def process_dataset(items: list[dict]) -> list[dict]: # Create 1M tasks results = await asyncio.gather(*[process_item(item) for item in items]) return results ``` **Issues**: - 1M tasks created (exceeds UI limit) - Task overhead >> task runtime (100ms task, seconds of overhead) - High load on Queue Service and object storage ### After optimization ```python # Use reusable containers env = flyte.TaskEnvironment( name="optimized-pipeline", reusable=flyte.ReusePolicy( replicas=(5, 20), concurrency=10, scaledown_ttl=timedelta(minutes=10), idle_ttl=timedelta(hours=1) ) ) @env.task async def process_batch(items: list[dict]) -> list[dict]: # Process batch of items return [{"processed": item["id"]} for item in items] @env.task async def process_dataset(items: list[dict]) -> list[dict]: # Create 1000 tasks (batch size 1000) batch_size = 1000 batches = [items[i:i + batch_size] for i in range(0, len(items), batch_size)] results = await flyte.map(process_batch, batches) return [item for batch in results for item in batch] ``` **Improvements**: - 1000 tasks instead of 1M (within limits) - Batch runtime ~100 seconds (100ms ร— 1000 items) - Reusable containers eliminate startup overhead - Concurrency enables high throughput (200 concurrent tasks max) ## When to contact the Union team Reach out to the Union team if you: - Need more than 200k tracked actions per run, or need full UI visibility beyond that point - Want to use high-performance metastores (Redis, PostgreSQL) instead of object stores - Have specific performance requirements or constraints - Need help profiling and optimizing your workflows === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration === Port a Flyte 1 codebase to Flyte 2, or map Airflow concepts to their Flyte 2 equivalents. # Migration Guides for migrating to Flyte 2 from other systems. ### **Migration > From Flyte 1 to 2** What's new in Flyte 2 (pure Python execution, simplified API, fine-grained reproducibility) and how to port a Flyte 1 codebase. ### **Migration > From Airflow to Flyte** Mapping from Airflow concepts (DAGs, operators, schedules, XCom, trigger rules) to their Flyte 2 equivalents. ### **Migration > From Slurm to Flyte** Mapping from Slurm concepts (sbatch scripts, modules, job arrays, dependencies, partitions, requeue, multi-node jobs) to their Flyte 2 equivalents. ## Subpages - **Migration > From Flyte 1 to 2** - What's new in Flyte 2 (pure Python execution, simplified API, fine-grained reproducibility) and how to port a Flyte 1 codebase. - **Migration > From Airflow to Flyte** - Mapping from Airflow concepts (DAGs, operators, schedules, XCom, trigger rules) to their Flyte 2 equivalents. - **Migration > From Slurm to Flyte** - Mapping from Slurm concepts (sbatch scripts, modules, job arrays, dependencies, partitions, requeue, multi-node jobs) to their Flyte 2 equivalents. === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2 === What's new in Flyte 2 (pure Python execution, simplified API, fine-grained reproducibility) and how to port a Flyte 1 codebase. # From Flyte 1 to 2 Flyte 2 represents a fundamental shift in how Flyte workflows are written and executed. ## Pure Python execution Write workflows in pure Python, enabling a more natural development experience and removing the constraints of a domain-specific language (DSL). ### Sync Python ``` import flyte env = flyte.TaskEnvironment("sync_example_env") @env.task def hello_world(name: str) -> str: return f"Hello, {name}!" @env.task def main(name: str) -> str: for i in range(10): hello_world(name) return "Done" if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main, name="World") print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/sync_example.py* ### Async Python ``` import asyncio import flyte env = flyte.TaskEnvironment("async_example_env") @env.task async def hello_world(name: str) -> str: return f"Hello, {name}!" @env.task async def main(name: str) -> str: results = [] for i in range(10): results.append(hello_world(name)) await asyncio.gather(*results) return "Done" if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main, name="World") print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/async_example.py* As you can see in the hello world example, workflows can be constructed at runtime, allowing for more flexible and adaptive behavior. Flyte 2 supports: - Python's asynchronous programming model to express parallelism. - Python's native error handling with `try-except` to overridden configurations, like resource requests. - Python's native conditional `if`/`elif`/`else` syntax and `for`/`while` loops. ## Simplified API The new API is more intuitive, with fewer abstractions to learn and a focus on simplicity. | Use case | Flyte 1 | Flyte 2 | | ----------------------------- | --------------------------- | --------------------------------------- | | Environment management | `N/A` | `TaskEnvironment` | | Perform basic computation | `@task` | `@env.task` | | Combine tasks into a workflow | `@workflow` | `@env.task` | | Create dynamic workflows | `@dynamic` | `@env.task` | | Fanout parallelism | `flytekit.map` | Python `for` loop with `asyncio.gather` | | Conditional execution | `flytekit.conditional` | Python `if-elif-else` | | Catching workflow failures | `@workflow(on_failure=...)` | Python `try-except` | There is no `@workflow` decorator. Instead, "workflows" are authored through a pattern of tasks calling tasks. Tasks are defined within environments, which encapsulate the context and resources needed for execution. ## Fine-grained reproducibility and recoverability As in Flyte 1, Flyte 2 supports caching at the task level (via `@env.task(cache=...)`), but it further enables recovery at the finer-grained, sub-task level through a feature called tracing (via `@flyte.trace`). ``` import flyte env = flyte.TaskEnvironment(name="trace_example_env") @flyte.trace async def call_llm(prompt: str) -> str: return "Initial response from LLM" @env.task async def finalize_output(output: str) -> str: return "Finalized output" @env.task(cache=flyte.Cache(behavior="auto")) async def main(prompt: str) -> str: output = await call_llm(prompt) output = await finalize_output(output) return output if __name__ == "__main__": flyte.init_from_config() r = flyte.run(main, prompt="Prompt to LLM") print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/trace.py* Here `call_llm` runs in the same container as `main` and acts as an automated checkpoint with full observability in the UI. If the task fails due to a system error (e.g., node preemption or infrastructure failure), Flyte can recover and replay from the last successful trace rather than restarting from the beginning. Note that tracing is distinct from caching: traces are recovered only if there is a system failure whereas with cached outputs are persisted for reuse across separate runs. ## Improved remote functionality Flyte 2 provides full management of the workflow lifecycle through a standardized API through the CLI and the Python SDK. | Use case | CLI | Python SDK | | ------------- | ------------------ | ------------------- | | Run a task | `flyte run ...` | `flyte.run(...)` | | Deploy a task | `flyte deploy ...` | `flyte.deploy(...)` | You can also fetch and run remote (previously deployed) tasks within the course of a running workflow. ``` import flyte from flyte import remote env_1 = flyte.TaskEnvironment(name="env_1") env_2 = flyte.TaskEnvironment(name="env_2") env_1.add_dependency(env_2) @env_2.task async def remote_task(x: str) -> str: return "Remote task processed: " + x @env_1.task async def main() -> str: remote_task_ref = remote.Task.get("env_2.remote_task", auto_version="latest") r = await remote_task_ref(x="Hello") return "main called remote and recieved: " + r if __name__ == "__main__": flyte.init_from_config() d = flyte.deploy(env_1) print(d[0].summary_repr()) r = flyte.run(main) print(r.name) print(r.url) r.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/remote.py* ## Native notebook support Author and run workflows and fetch workflow metadata (I/O and logs) directly from Jupyter notebooks. ![Native Notebook](../../../_static/images/user-guide/notebook.png) ## High performance engine When running on a Union.ai backend, Flyte 2 enables you to schedule tasks in milliseconds with reusable containers, which massively increases the throughput of containerized tasks. ``` # Currently required to enable resuable containers reusable_image = flyte.Image.from_debian_base().with_pip_packages("unionai-reuse>=0.1.10") env = flyte.TaskEnvironment( name="reusable-env", resources=flyte.Resources(memory="1Gi", cpu="500m"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1), # Specify reuse policy image=reusable_image # Use the container image augmented with the unionai-reuse library. ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/reuse.py* Coupled with multi-cluster, multi-cloud, and multi-region support, Flyte 2 on Union.ai can scale to handle even the most demanding workflows. ## Enhanced UI The Union.ai backend also offers a new UI with a streamlined and user-friendly experience for authoring and managing workflows. ![New UI](../../../_static/images/user-guide/v2ui.png) This UI improves the visualization of workflow execution and monitoring, simplifying access to logs, metadata, and other important information. {{< subpage-cards >}} ## Subpages - **Migration > From Flyte 1 to 2 > Migration overview** - The Flyte 1 workload patterns you know, and their Flyte 2 equivalents. - **Migration > From Flyte 1 to 2 > Tasks and workflows** - task, workflow, and dynamic collapse into one decorator, because everything is a task. - **Migration > From Flyte 1 to 2 > Task configuration** - Image, resources, caching, secrets, and scheduling move from the task decorator to the environment. - **Migration > From Flyte 1 to 2 > CLI and configuration** - pyflyte becomes flyte, and the config file gets much smaller. - **Migration > From Flyte 1 to 2 > Control flow** - Branching, fan-out, and failure handling become ordinary Python instead of DSL constructs. - **Migration > From Flyte 1 to 2 > Parallelism and fan-out** - map_task becomes flyte.map, and fan-out becomes async and asyncio.gather. - **Migration > From Flyte 1 to 2 > Data types and I/O** - The offloaded-data types are renamed and their I/O is async, but the mental model is unchanged. - **Migration > From Flyte 1 to 2 > ML workloads** - Everyday ML workloads as complete Flyte 1 to Flyte 2 pairs. - **Migration > From Flyte 1 to 2 > New in Flyte 2: patterns that weren't possible in Flyte 1** - What Flyte 2 adds on top of batch orchestration, starting with long-running services. - **Migration > From Flyte 1 to 2 > Migrating Union-specific features** - Where Flyte 1's Union-specific Actors and Apps landed in Flyte 2. - **Migration > From Flyte 1 to 2 > Hybrid v1 and v2 pipelines** - Run Flyte 1 and Flyte 2 workloads side by side and have them call each other. - **Migration > From Flyte 1 to 2 > Gotchas and caveats** - Where Flyte 2's flexibility can surprise you, and what to watch for. === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/overview === The Flyte 1 workload patterns you know, and their Flyte 2 equivalents. # Migration overview This section walks through the Flyte 1 workload patterns you already know โ€” data ETL, model training, hyperparameter sweeps, batch inference โ€” and their Flyte 2 equivalents. Every pattern is a complete, runnable v1โ†”v2 example pair in the [`unionai-examples`](https://github.com/unionai/unionai-examples/tree/main/v2/user-guide/migration/flyte-2) repository. Two conceptual shifts motivate almost every change โ€” **pure Python execution** and the **asynchronous model** โ€” after which most migrations come down to a couple of mechanical moves. This page covers both shifts, the terminology mapping, and a quick-reference module. ## Pure Python execution In Flyte 1, `@workflow` functions were constrained to a DSL subset of Python that compiled to a static DAG. In Flyte 2 there is **no `@workflow` decorator**: everything is a `@env.task`, and a "workflow" is simply a task that calls other tasks. Orchestration runs as real Python at runtime, so loops, conditionals, and `try`/`except` work anywhere. | Flyte 1 | Flyte 2 | | --- | --- | | `@workflow` functions are constrained to a subset of Python defining a static DAG. | **No `@workflow` decorator**: your top-level "workflow" is just a task that calls other tasks. | | `@task` functions had the full power of Python, but only within a single container execution. | `@env.task`s call other tasks and build dynamic structures with any Python construct, anywhere. | | Workflows compiled to static DAGs at registration time. | Workflows are tasks calling tasks; compile-time safety is coming via `compiled_task`. | ### Flyte 1 ```python import flytekit image = flytekit.ImageSpec( name="hello-world-image", packages=["requests"], ) @flytekit.task(container_image=image) def mean(data: list[float]) -> float: return sum(list) / len(list) @flytekit.workflow def main(data: list[float]) -> float: output = mean(data) # โŒ performing trivial operations in a workflow is not allowed # output = output / 100 # โŒ if/else is not allowed # if output < 0: # raise ValueError("Output cannot be negative") return output ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/pure-python/flyte_1.py* ### Flyte 2 ``` import flyte env = flyte.TaskEnvironment( "hello_world", image=flyte.Image.from_debian_base().with_pip_packages("requests"), ) @env.task def mean(data: list[float]) -> float: return sum(data) / len(data) @env.task def main(data: list[float]) -> float: output = mean(data) # โœ… performing trivial operations in a workflow is allowed output = output / 100 # โœ… if/else is allowed if output < 0: raise ValueError("Output cannot be negative") return output ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/pure-python/flyte_2.py* This unlocks workflows that adapt to runtime conditions, native `try`/`except` error handling, and the intuitive composition of ordinary Python functions. ## Asynchronous model Flyte 2 is built on Python's `asyncio`, with a crucial twist: **the Flyte orchestrator acts as the event loop**, scheduling awaited tasks across distributed infrastructure. This makes `async`/`await` the natural way to express parallelism. | | Flyte 1 | Flyte 2 | | --- | --- | --- | | Parallelism | The DSL auto-parallelized independent tasks; the `map` operator ran a task over many inputs. | Python's `asyncio` expresses parallelism, with the Flyte orchestrator acting as the event loop across distributed infrastructure. | The core async keywords carry Flyte-specific meaning: - **`async def`** declares a coroutine. - **`await`** signals where a task can be scheduled in parallel โ€” not just an I/O yield point. - **`asyncio.gather`** tells the orchestrator that a set of tasks are independent and can be distributed across separate compute resources. Consider this pattern for parallel data processing: ``` import asyncio import flyte env = flyte.TaskEnvironment("data_pipeline") @env.task async def process_chunk(chunk_id: int, data: str) -> str: # This could be any computational work - CPU or I/O bound await asyncio.sleep(1) # Simulating work return f"Processed chunk {chunk_id}: {data}" @env.task async def parallel_pipeline(data_chunks: list[str]) -> list[str]: # Create coroutines for all chunks tasks = [] for i, chunk in enumerate(data_chunks): tasks.append(process_chunk(i, chunk)) # Execute all chunks in parallel results = await asyncio.gather(*tasks) return results ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/async/async.py* In standard Python this mainly benefits I/O-bound work; in Flyte 2 the orchestrator schedules each `process_chunk` task on its own pod. ### True parallelism for all workloads Async syntax in Flyte 2 is **not just for I/O-bound operations**. When the orchestrator encounters `await asyncio.gather(...)`, it runs those independent tasks simultaneously across compute resources โ€” achieving true parallelism for CPU-bound work (model training, heavy math), I/O-bound work (queries, API calls), and mixed workloads alike. ### Calling sync tasks from async tasks You don't need to rewrite existing synchronous code. Flyte automatically "asyncifies" sync functions; just call them from an async context with `.aio()`: ``` @env.task def legacy_computation(x: int) -> int: # Existing synchronous function works unchanged return x * x + 2 * x + 1 @env.task async def modern_workflow(numbers: list[int]) -> list[int]: # Call sync tasks from async context using .aio() tasks = [] for num in numbers: tasks.append(legacy_computation.aio(num)) results = await asyncio.gather(*tasks) return results ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/async/async.py* ### The `flyte.map` function: Familiar patterns For code that used Flyte 1's `map`, `flyte.map` is a direct replacement that works in both sync and async contexts: ### Sync Map ``` @env.task def sync_map_example(n: int) -> list[str]: # Synchronous version for easier migration results = [] for result in flyte.map(process_item, range(n)): if isinstance(result, Exception): raise result results.append(result) return results ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/async/async.py* ### Async Map ``` @env.task async def async_map_example(n: int) -> list[str]: # Async version using flyte.map - exact pattern from SDK examples results = [] async for result in flyte.map.aio(process_item, range(n), return_exceptions=True): if isinstance(result, Exception): raise result results.append(result) return results ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/flyte-2/async/async.py* It provides dual interfaces (`flyte.map.aio()` and `flyte.map()`), `return_exceptions` for graceful failure handling (a more flexible replacement for Flyte 1's `min_success_ratio`), automatic UI grouping, and optional concurrency limits. ## Terminology and concept mapping Several Flyte 1 concepts were renamed or reshaped in Flyte 2. The table below maps the ones you'll meet most often. | Flyte 1 | Flyte 2 | Notes | |---|---|---| | `flytekit` (package) | `flyte` (package) | The Python SDK was renamed; imports change from `import flytekit` to `import flyte`. | | `pyflyte` (CLI) | `flyte` (CLI) | The command-line tool was renamed. | | `@task` / `@workflow` / `@dynamic` | `@env.task` | A single task decorator off a `flyte.TaskEnvironment`. Workflows and dynamic tasks are no longer distinct constructs: everything is a task, and orchestration is plain Python. | | `map_task()` | `flyte.map()` | Plus `asyncio.gather()` for async fan-out. | | `conditional()` | native `if` / `elif` / `else` | Branching is now ordinary Python control flow, not a DSL. | | `ImageSpec` | `flyte.Image` | Container image definition. | | `current_context()` | `flyte.ctx()` | Runtime context access. | | `FlyteFile` / `FlyteDirectory` | `flyte.io.File` / `flyte.io.Dir` | Offloaded file and directory references. | | `StructuredDataset` | `flyte.io.DataFrame` | Offloaded tabular data. | | `LaunchPlan` | `flyte.Trigger` | Scheduling and parameterized entry points. | | `CronSchedule` | `flyte.Cron` | Cron-based scheduling, used with a `flyte.Trigger`. | | Decks (`enable_deck=True`) | Reports (`report=True`) | Custom HTML rendered in the UI during/after a run. See **Tasks > Build tasks > Reports**. | ## Package imports The package is renamed from `flytekit` to `flyte`, and the workflow/dynamic/map_task imports disappear: ### Flyte 1 ```python import flytekit from flytekit import task, workflow, dynamic, map_task from flytekit import ImageSpec, Resources, Secret from flytekit import current_context, LaunchPlan, CronSchedule ``` ### Flyte 2 ```python import flyte from flyte import TaskEnvironment, Resources, Secret from flyte import Image, Trigger, Cron ``` ## The two mechanical changes behind (almost) every migration Most of a migration comes down to two moves: ### 1. Move task configuration into a `TaskEnvironment` Instead of configuring the image, resources, and caching on each task decorator, configure them once on a `flyte.TaskEnvironment` and share it across tasks: ```python env = flyte.TaskEnvironment( name="training", image=flyte.Image.from_debian_base().with_pip_packages("scikit-learn", "pandas"), resources=flyte.Resources(cpu="2", memory="4Gi"), cache="auto", ) ``` ### 2. Replace `@task` / `@workflow` / `@dynamic` with `@env.task` Every decorated function becomes an `@env.task`. There is no separate workflow or dynamic construct: a "workflow" is simply a task that calls other tasks, and orchestration is plain Python. > **๐Ÿ“ Note** > > The `env` in `@env.task` is just the variable you assigned your `TaskEnvironment` to. Name it whatever you like. ## In this section The migration patterns are grouped by theme. Start with **Tasks and workflows**, then jump to whatever your workload needs: - ****Migration > From Flyte 1 to 2 > Tasks and workflows**** โ€” the structural shift: `@task`/`@workflow` โ†’ `@env.task`, sequential ordering, nested "subworkflows", and the `@task` โ†’ `TaskEnvironment` parameter mapping. - ****Migration > From Flyte 1 to 2 > Task configuration**** โ€” moving image/resources/cache to the `TaskEnvironment`, GPUs, secrets, caching, and scheduling with triggers. - ****Migration > From Flyte 1 to 2 > CLI and configuration**** โ€” `pyflyte` โ†’ `flyte` command mapping and config-file changes. - ****Migration > From Flyte 1 to 2 > Control flow**** โ€” `conditional()` and `@dynamic` become plain Python `if`/loops, and `on_failure` becomes `try`/`except`. - ****Migration > From Flyte 1 to 2 > Parallelism and fan-out**** โ€” `map_task` โ†’ `flyte.map` / `asyncio.gather`, plus a data-backfill example. - ****Migration > From Flyte 1 to 2 > Data types and I/O**** โ€” `FlyteFile`/`FlyteDirectory` โ†’ `flyte.io.File`/`Dir`, `StructuredDataset` โ†’ `flyte.io.DataFrame`, dataclasses, and an ETL example. - ****Migration > From Flyte 1 to 2 > ML workloads**** โ€” small-model training, hyperparameter optimization, deep learning, batch inference, and an end-to-end pipeline. - ****Migration > From Flyte 1 to 2 > New in Flyte 2: patterns that weren't possible in Flyte 1**** โ€” patterns that weren't possible in Flyte 1 at all: real-time model serving, batch inference, apps, and sandboxed code execution. - ****Migration > From Flyte 1 to 2 > Migrating Union-specific features**** โ€” migrating Union-specific Actors (โ†’ reusable containers) and Apps (โ†’ the Flyte SDK). - ****Migration > From Flyte 1 to 2 > Hybrid v1 and v2 pipelines**** โ€” calling between v1 and v2 in both directions during the transition. - ****Migration > From Flyte 1 to 2 > Gotchas and caveats**** โ€” common gotchas plus the deeper caveats of the new execution model, including non-deterministic behavior and keeping orchestration lightweight. ## Quick reference A minimal Flyte 2 module, end to end: ```python import asyncio import flyte # 1. Define an image image = ( flyte.Image.from_debian_base(python_version=(3, 11)) .with_pip_packages("pandas", "numpy") ) # 2. Create a TaskEnvironment env = flyte.TaskEnvironment( name="my_env", image=image, resources=flyte.Resources(cpu="1", memory="2Gi"), ) # 3. Define tasks @env.task async def process(x: int) -> int: return x * 2 # 4. Define the entrypoint task @env.task async def main(items: list[int]) -> list[int]: results = await asyncio.gather(*[process(x) for x in items]) return list(results) # 5. Run it if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main, items=[1, 2, 3, 4, 5]) print(run.url) run.wait() ``` ```bash # CLI flyte run my_module.py main --items '[1,2,3,4,5]' # remote (default) flyte run --local my_module.py main --items '[1,2,3,4,5]' flyte deploy my_module.py my_env ``` === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/tasks-and-workflows === task, workflow, and dynamic collapse into one decorator, because everything is a task. # Tasks and workflows The biggest structural change in Flyte 2 is that **everything is a task**. The `@task`, `@workflow`, and `@dynamic` decorators all collapse into a single `@env.task` on a `flyte.TaskEnvironment`, and a "workflow" is just a task that calls other tasks. This page covers the basic structure; see **Migration > From Flyte 1 to 2 > Task configuration** for the environment settings and **Migration > From Flyte 1 to 2 > Migration overview** for the big picture. ## Hello world: tasks and workflows A `@task` plus `@workflow` becomes two `@env.task`s, where the entrypoint task calls the others. Sequential calls are naturally ordered โ€” no `>>` operator required. ### Flyte 1 ```python import flyte env = flyte.TaskEnvironment( name="hello_world", ) @env.task def say_hello(name: str) -> str: return f"Hello, {name}!" @env.task def to_upper(greeting: str) -> str: return greeting.upper() @env.task def main(name: str) -> str: greeting = say_hello(name=name) greeting = f"{greeting}, welcome to Flyte!" if len(name) < 1: return "No greeting for you!" return to_upper(greeting=greeting) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/hello_world_v1.py* ### Flyte 2 ``` import flyte env = flyte.TaskEnvironment(name="hello_world") @env.task def say_hello(name: str) -> str: return f"Hello, {name}!" @env.task def to_upper(greeting: str) -> str: return greeting.upper() # The "workflow" is now just a task that calls other tasks. @env.task def main(name: str) -> str: greeting = say_hello(name) return to_upper(greeting) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/hello_world_v2.py* ## Chaining and ordering In Flyte 1 you sometimes used `>>` to force ordering between tasks with no data dependency. In Flyte 2, sequential (synchronous) calls run in the order they're written, and `await`ing async tasks in sequence does the same. The `>>` operator is gone. ### Flyte 1 ```python from flytekit import task, workflow @task def clear_staging_table() -> None: # Side effect only: truncate the staging table. print("cleared staging table") @task def load_into_staging() -> None: # Side effect only: load fresh rows into staging. print("loaded staging table") @task def publish_to_prod() -> None: # Side effect only: swap staging into the production table. print("published to prod") @workflow def main() -> None: clear = clear_staging_table() load = load_into_staging() publish = publish_to_prod() # These tasks pass no data between them, so use the >> operator to force # ordering: clear must finish before load, which must finish before publish. clear >> load >> publish ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/chained_tasks_v1.py* ### Flyte 2 ``` import flyte env = flyte.TaskEnvironment(name="staging_publish") @env.task def clear_staging_table() -> None: print("cleared staging table") @env.task def load_into_staging() -> None: print("loaded staging table") @env.task def publish_to_prod() -> None: print("published to prod") # Sequential (synchronous) calls run in the order they're written, even when no # data flows between them. The Flyte 1 `>>` ordering operator is gone. @env.task def main() -> None: clear_staging_table() load_into_staging() publish_to_prod() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/chained_tasks_v2.py* ## Subworkflows A `@workflow` invoked by another `@workflow` (for example, a reusable preprocessing pipeline) becomes a task that calls other tasks โ€” nest them as deeply as you like. ### Flyte 1 CODE3 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/subworkflow_v1.py* ### Flyte 2 CODE4 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/subworkflow_v2.py* ## TaskEnvironment configuration The `TaskEnvironment` holds the configuration that Flyte 1 spread across the `@task` decorator. The task decorator can still override a few settings per-task. CODE5 ## Parameter mapping: `@task` โ†’ `TaskEnvironment` + `@env.task` | Flyte 1 `@task` parameter | Flyte 2 location | Notes | |---|---|---| | `container_image` | `TaskEnvironment(image=...)` | Env-level only | | `requests` | `TaskEnvironment(resources=...)` | Env-level only | | `limits` | `TaskEnvironment(resources=...)` | Combined with requests (single value) | | `environment` | `TaskEnvironment(env_vars=...)` | Env-level only | | `secret_requests` | `TaskEnvironment(secrets=...)` | Env-level only | | `cache` | Both | Can override at task level | | `cache_version` | `flyte.Cache(version_override=...)` | In a `Cache` object | | `retries` | `@env.task(retries=...)` | Task-level only | | `timeout` | `@env.task(timeout=...)` | Task-level only | | `interruptible` | Both | Can override at task level | | `pod_template` | Both | Can override at task level | | `deprecated` | N/A | Not in Flyte 2 | | `docs` | `@env.task(docs=...)` | Task-level only | For image, resource, secret, and caching detail, see **Migration > From Flyte 1 to 2 > Task configuration**. ## Next - **Migration > From Flyte 1 to 2 > Task configuration** โ€” image, resources, caching, secrets, and scheduling - **Migration > From Flyte 1 to 2 > Control flow** โ€” conditionals, dynamic behavior, and error handling - **Migration > From Flyte 1 to 2 > Parallelism and fan-out** โ€” running tasks in parallel === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/configuration === Image, resources, caching, secrets, and scheduling move from the task decorator to the environment. # Task configuration In Flyte 1, image, resources, caching, secrets, and scheduling were configured per-task on the `@task` decorator or per-workflow on a `LaunchPlan`. In Flyte 2 most of this moves to the `flyte.TaskEnvironment`, so it's declared once and shared. See **Migration > From Flyte 1 to 2 > Migration overview** for the overall approach. ## Image, resources, and caching Image, resources, and caching move from the `@task` decorator to the `TaskEnvironment`. Per-task settings like `retries` and `timeout` stay on `@env.task`. Note that `mem` is renamed to `memory`, and there are no separate `requests`/`limits` โ€” a single `Resources` value serves as both. ### Flyte 1 ```python from datetime import timedelta import flytekit from flytekit import Resources image = flytekit.ImageSpec( name="training-image", packages=["scikit-learn", "pandas"], ) @flytekit.task( container_image=image, requests=Resources(cpu="2", mem="4Gi"), limits=Resources(cpu="4", mem="8Gi"), cache=True, cache_version="1.0", retries=3, timeout=timedelta(minutes=30), ) def train_epoch(step: int) -> float: # A stand-in for a training step that returns the current loss. return 1.0 / (step + 1) @flytekit.workflow def main(step: int) -> float: return train_epoch(step=step) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/task_config_v1.py* ### Flyte 2 ``` from datetime import timedelta import flyte # Image, resources, and caching move to the TaskEnvironment, so they are declared # once and shared by every task in the environment. env = flyte.TaskEnvironment( name="training", image=flyte.Image.from_debian_base().with_pip_packages("scikit-learn", "pandas"), resources=flyte.Resources(cpu="2", memory="4Gi"), # "memory", not "mem" cache="auto", ) # retries and timeout stay on the task decorator. @env.task(retries=3, timeout=timedelta(minutes=30)) def train_epoch(step: int) -> float: # A stand-in for a training step that returns the current loss. return 1.0 / (step + 1) @env.task def main(step: int) -> float: return train_epoch(step) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/task_config_v2.py* For the full `@task` โ†’ `TaskEnvironment` + `@env.task` parameter mapping, see **Migration > From Flyte 1 to 2 > Tasks and workflows**. ## Container images Flyte 1's `ImageSpec` is replaced by Flyte 2's `flyte.Image` with a fluent builder API. ```python from flyte import Image image = ( Image.from_debian_base(name="my-image", registry="ghcr.io/myorg", python_version=(3, 11)) .with_pip_packages("pandas", "numpy") .with_apt_packages("curl", "git") .with_env_vars({"MY_VAR": "value"}) ) ``` Instead of one constructor with many arguments, you start from a base and chain builder methods: | Constructor | Use case | |---|---| | `Image.from_debian_base()` | Most common; includes the Flyte SDK | | `Image.from_base(image_uri)` | Start from any existing image | | `Image.from_dockerfile(path)` | Complex custom builds | | `Image.from_uv_script(path)` | UV-based projects | Common chainable builder methods: `.with_pip_packages(...)`, `.with_requirements(path)`, `.with_uv_project(path)`, `.with_apt_packages(...)`, `.with_commands([...])`, `.with_source_file(path, dst=...)`, `.with_source_folder(path, dst=...)`, `.with_env_vars({...})`, and `.with_workdir(...)`. | Flyte 1 `ImageSpec` | Flyte 2 `Image` | Notes | |---|---|---| | `name` | `name` (constructor) | Same | | `registry` | `registry` (constructor) | Same | | `python_version` | `python_version` (tuple) | `"3.11"` becomes `(3, 11)` | | `packages` | `.with_pip_packages()` | Method instead of param | | `apt_packages` | `.with_apt_packages()` | Method instead of param | | `requirements` | `.with_requirements()` | Supports txt, poetry.lock, uv.lock | | `env` | `.with_env_vars()` | Method instead of param | | `commands` | `.with_commands()` | Method instead of param | | `copy` / `source_root` | `.with_source_file()` / `.with_source_folder()` | More explicit methods | | `base_image` | `Image.from_base()` | Different constructor | | `builder` | Config file or `flyte.init()` | Global setting | | `platform` | `platform` (constructor) | Tuple: `("linux/amd64", "linux/arm64")` | For a private registry, create an image-pull secret and reference it: ```shell flyte create secret --type image_pull my-registry-secret --from-file ~/.docker/config.json ``` ```python image = Image.from_debian_base( registry="private.registry.com", name="my-image", registry_secret="my-registry-secret", ) ``` See **Tasks > Configure tasks > Container images** for more. ## Resources A single `flyte.Resources` value serves as both request and limit โ€” there are no separate `requests`/`limits`. Several parameters were renamed. | Flyte 1 | Flyte 2 | Notes | |---|---|---| | `cpu="1"` | `cpu="1"` | Same | | `mem="2Gi"` | `memory="2Gi"` | Renamed | | `gpu="1"` | `gpu="A100:1"` | `Type:count` format | | `ephemeral_storage="10Gi"` | `disk="10Gi"` | Renamed | | N/A | `shm="auto"` | New: shared memory | GPU type and count are combined into one string, replacing the separate Flyte 1 `accelerator=` argument: ```python env = flyte.TaskEnvironment( name="gpu_env", resources=flyte.Resources( cpu="4", memory="32Gi", gpu="A100:2", # Type:count # gpu="A100_80G:1" # 80GB variant (flyte >= 2.11.3; earlier: "A100 80G:1") # gpu=flyte.GPU("A100", quantity=1, partition="1g.5gb") # MIG partition ), ) ``` Supported GPU types include A10, A10G, A100, A100_80G, B200, H100, H200, L4, L40s, T4, V100, RTX_PRO_4500, RTX_PRO_6000, and GB10. The underscore names need `flyte` 2.11.3 or later; earlier releases use `A100 80G` and `RTX PRO 6000`. See **Tasks > Configure tasks > Resources** for more. ## Caching Caching is enabled at the env level with `cache="auto"` (or per-task on `@env.task`). The explicit `cache_version` string moves into a `flyte.Cache` object. | Behavior | Description | |---|---| | `"auto"` | Cache results and reuse if available | | `"override"` | Always execute and overwrite the cache | | `"disable"` | No caching (default for a `TaskEnvironment`) | ```python # Flyte 1: @task(cache=True, cache_version="1.0") # Flyte 2: @env.task(cache="auto") def cached_task(x: int) -> int: return x * 2 # Advanced control (replaces cache_version, serialize, ignored_inputs, ...) @env.task(cache=flyte.Cache( behavior="auto", version_override="v1.0", serialize=True, ignored_inputs=("debug",), )) def advanced(x: int, debug: bool = False) -> int: return x * 2 ``` See **Tasks > Configure tasks > Caching** for more. ## Secrets Secrets move from `secret_requests` on the task to `secrets` on the `TaskEnvironment`, and you read them from environment variables instead of `current_context().secrets` โ€” for example, an API key for a model registry or hosted LLM. ### Flyte 1 ```python from flytekit import task, workflow, Secret, current_context @task(secret_requests=[Secret(group="openai", key="api_key")]) def call_api() -> str: token = current_context().secrets.get(group="openai", key="api_key") return f"token has {len(token)} chars" @workflow def main() -> str: return call_api() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/secrets_v1.py* ### Flyte 2 ``` import os import flyte # Secrets are declared on the TaskEnvironment and injected as environment # variables (instead of read through current_context().secrets). env = flyte.TaskEnvironment( name="secrets", secrets=[flyte.Secret(key="openai_api_key", as_env_var="OPENAI_API_KEY")], ) @env.task def call_api() -> str: token = os.getenv("OPENAI_API_KEY", "") return f"token has {len(token)} chars" @env.task def main() -> str: return call_api() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/secrets_v2.py* A `flyte.Secret` can be mounted as an environment variable or as a file, and the access convention changes: ```python flyte.Secret(key="openai-key", as_env_var="OPENAI_API_KEY") # mount as env var flyte.Secret(key="access-key", group="aws") # env var: AWS_ACCESS_KEY flyte.Secret(key="ssl-cert", mount="/etc/flyte/secrets") # mount as a file ``` | Flyte 1 pattern | Flyte 2 pattern | |---|---| | `ctx.secrets.get(key="mykey", group="mygroup")` | `os.environ["MYGROUP_MYKEY"]` (auto-named) | | `ctx.secrets.get(key="mykey")` | `os.environ["MY_SECRET"]` (with `as_env_var="MY_SECRET"`) | Create and manage secrets from the CLI: ```bash flyte create secret MY_SECRET_KEY --value my_secret_value flyte create secret MY_SECRET_KEY --from-file /path/to/secret flyte get secret flyte delete secret MY_SECRET_KEY ``` See **Tasks > Configure tasks > Secrets** for more. ## Scheduling A `LaunchPlan` with a `CronSchedule` (say, a nightly retraining job) becomes a `flyte.Trigger` attached directly to the task. Use `flyte.TriggerTime` to bind the scheduled fire time to an input, and deploy the trigger with `flyte deploy`. ### Flyte 1 ```python from flytekit import task, workflow, LaunchPlan, CronSchedule @task def retrain(kickoff_time: str) -> str: return f"retrained model at {kickoff_time}" @workflow def main(kickoff_time: str) -> str: return retrain(kickoff_time=kickoff_time) # A LaunchPlan attaches a schedule (and default inputs) to a workflow. nightly_retrain = LaunchPlan.get_or_create( workflow=main, name="nightly_retrain", schedule=CronSchedule( schedule="0 2 * * *", # 2 AM daily kickoff_time_input_arg="kickoff_time", ), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/scheduling_v1.py* ### Flyte 2 ``` from datetime import datetime import flyte env = flyte.TaskEnvironment(name="scheduling") # A Trigger replaces LaunchPlan + CronSchedule. It is attached directly to the # task and deployed with it (flyte deploy). flyte.TriggerTime binds the # scheduled fire time to a task input. nightly_retrain = flyte.Trigger.minutely( name="nightly_retrain", inputs={"trigger_time": flyte.TriggerTime}, auto_activate=True, ) @env.task(triggers=nightly_retrain) def main(trigger_time: datetime = datetime(2024, 1, 1, 2, 0)) -> str: return f"retrained model at {trigger_time.isoformat()}" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/scheduling_v2.py* Triggers support `flyte.Cron("0 9 * * *", timezone="America/New_York")` and `flyte.FixedRate(60)` (an interval in minutes) as automations, plus convenience constructors like `flyte.Trigger.hourly()` and `flyte.Trigger.daily()`. See [Triggers](../../triggers/_index) for more. ## Next - **Migration > From Flyte 1 to 2 > CLI and configuration** โ€” `pyflyte` โ†’ `flyte` command and config-file mapping - **Migration > From Flyte 1 to 2 > Control flow** โ€” conditionals, dynamic behavior, and error handling - **Migration > From Flyte 1 to 2 > Data types and I/O** โ€” files, DataFrames, and dataclasses === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/cli-and-configuration === pyflyte becomes flyte, and the config file gets much smaller. # CLI and configuration The command-line tool is renamed from `pyflyte` to `flyte`, and the config file is trimmed down. See **Migration > From Flyte 1 to 2 > Migration overview** for the overall approach. ## CLI command mapping | Flyte 1 | Flyte 2 | Notes | |---|---|---| | `pyflyte run` | `flyte run` | Similar, different flags | | `pyflyte run --remote` | `flyte run` | Remote is the default in Flyte 2 | | `pyflyte run` (local) | `flyte run --local` | Local execution is now explicit | | `pyflyte register` | `flyte deploy` | Different concept | | `pyflyte package` | N/A | Not needed in Flyte 2 | | `pyflyte serialize` | N/A | Not needed in Flyte 2 | ### Running tasks ### Flyte 1 ```shell # Local pyflyte run my_module.py my_workflow --arg1 value1 # Remote pyflyte --config config.yaml run --remote my_module.py my_workflow --arg1 value1 ``` ### Flyte 2 ```shell # Remote (default) flyte run my_module.py my_task --arg1 value1 # Local flyte run --local my_module.py my_task --arg1 value1 # With an explicit config file flyte --config config.yaml run my_module.py my_task --arg1 value1 ``` ### Deploying In Flyte 1 you registered a module; in Flyte 2 you deploy task environments. ### Flyte 1 ```shell pyflyte register my_module.py -p my-project -d development ``` ### Flyte 2 ```shell # Deploy a task environment flyte deploy my_module.py my_env --project my-project --domain development # Deploy all environments in a file flyte deploy --all my_module.py # Deploy with an explicit version, or recursively flyte deploy --version v1.0.0 my_module.py my_env flyte deploy --recursive --all ./src ``` ### Key flag differences | Flyte 1 flag | Flyte 2 flag | Notes | |---|---|---| | `--remote` | (default) | Remote is the default | | `--copy-all` | `--copy-style all` | File copying | | N/A | `--copy-style loaded_modules` | Default: only imported modules | | `-p, --project` | `--project` | Same | | `-d, --domain` | `--domain` | Same | | `-i, --image` | `--image` | Same format | | N/A | `--follow, -f` | Follow execution logs | ## Configuration files The config file lives in the same place (`~/.flyte/config.yaml`) and the environment variable is still `FLYTECTL_CONFIG`, but the format is simpler. ### Flyte 1 ```yaml admin: endpoint: dns:///your-cluster.hosted.unionai.cloud insecure: false authType: Pkce ``` ### Flyte 2 ```yaml admin: endpoint: dns:///your-cluster.hosted.unionai.cloud image: builder: remote # or "local" or "local-podman" task: domain: development org: your-org project: your-project ``` | Setting | Flyte 1 | Flyte 2 | |---|---|---| | Endpoint | `admin.endpoint` | `admin.endpoint` | | Auth type | `admin.authType` | Auto-detected (PKCE default) | | Project | CLI flag `-p` | `task.project` (default) | | Domain | CLI flag `-d` | `task.domain` (default) | | Organization | CLI flag `--org` | `task.org` (default) | | Image builder | N/A | `image.builder` (`local`, `local-podman`, or `remote`) | ### Configuring in code ```python import flyte # From a config file (auto-discovers, or pass a path) flyte.init_from_config() flyte.init_from_config("path/to/config.yaml") # Programmatically flyte.init( endpoint="flyte.example.com", project="my-project", domain="development", ) ``` For API-key authentication in non-interactive environments, use `flyte.init_from_api_key()` โ€” see **Get started > Run modes > Run on a deployed cluster**. ## Next - **Migration > From Flyte 1 to 2 > Control flow** โ€” conditionals, dynamic behavior, and error handling - **Migration > From Flyte 1 to 2 > Hybrid v1 and v2 pipelines** โ€” calling between v1 and v2 during the transition === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/control-flow === Branching, fan-out, and failure handling become ordinary Python instead of DSL constructs. # Control flow Flyte 1 expressed branching, dynamic fan-out, and failure handling through DSL constructs (`conditional()`, `@dynamic`, `@workflow(on_failure=...)`). In Flyte 2 these are all ordinary Python, because orchestration runs as real Python at runtime. See **Migration > From Flyte 1 to 2 > Migration overview** for the overall approach. ## Conditional execution The `conditional()` DSL becomes ordinary Python `if` / `elif` / `else` โ€” for example, choosing a model based on dataset size. ### Flyte 1 ```python from flytekit import task, workflow, conditional @task def train_gradient_boosting(n_rows: int) -> str: return f"trained gradient boosting on {n_rows} rows" @task def train_logistic_regression(n_rows: int) -> str: return f"trained logistic regression on {n_rows} rows" @workflow def main(n_rows: int) -> str: # Pick the model based on dataset size. return ( conditional("model_choice") .if_(n_rows > 10_000) .then(train_gradient_boosting(n_rows=n_rows)) .else_() .then(train_logistic_regression(n_rows=n_rows)) ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/conditional_v1.py* ### Flyte 2 ``` import flyte env = flyte.TaskEnvironment(name="conditional") @env.task def train_gradient_boosting(n_rows: int) -> str: return f"trained gradient boosting on {n_rows} rows" @env.task def train_logistic_regression(n_rows: int) -> str: return f"trained logistic regression on {n_rows} rows" # Branching is now ordinary Python control flow -- no conditional() DSL. @env.task def main(n_rows: int) -> str: if n_rows > 10_000: return train_gradient_boosting(n_rows) return train_logistic_regression(n_rows) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/conditional_v2.py* ## Dynamic workflows `@dynamic` existed so a task could generate a variable number of subtask calls at runtime (e.g. one per data partition discovered at runtime). In Flyte 2 every task can do this natively, so `@dynamic` simply disappears โ€” loop over runtime data in an ordinary `@env.task`. ### Flyte 1 ```python from flytekit import task, workflow, dynamic @task def list_partitions(n: int) -> list[int]: return list(range(n)) @task def process_partition(partition_id: int) -> int: # Aggregate one data partition. return partition_id * 2 @dynamic def process_all(partitions: list[int]) -> list[int]: results = [] for partition_id in partitions: results.append(process_partition(partition_id=partition_id)) return results @workflow def main(n: int) -> list[int]: partitions = list_partitions(n=n) return process_all(partitions=partitions) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/dynamic_v1.py* ### Flyte 2 ``` import flyte env = flyte.TaskEnvironment(name="dynamic") @env.task def process_partition(partition_id: int) -> int: # Aggregate one data partition. return partition_id * 2 # No @dynamic decorator needed: a plain task can loop over runtime data (e.g. a # variable number of partitions discovered at runtime) and call other tasks. @env.task def main(n: int) -> list[int]: return [process_partition(partition_id) for partition_id in range(n)] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/dynamic_v2.py* ## Error handling Flyte 1's `@workflow(on_failure=...)` handler becomes ordinary Python `try` / `except` โ€” catch a failed training run, run cleanup, and recover or re-raise. ### Flyte 1 ```python import flytekit from flytekit import task, workflow @task(resources=flytekit.Resources(cpu=1, mem="250Mi")) def train_fold(max_depth: int) -> float: if max_depth <= 0: raise ValueError("max_depth must be positive") # Return validation accuracy for this hyperparameter. return 0.90 + 0.001 * max_depth @task def notify_failure() -> None: print("training run failed -- sending alert") # The on_failure handler runs if any node in the workflow fails. There is no # try/except inside a Flyte 1 workflow. @workflow(on_failure=notify_failure) def main(max_depth: int) -> float: return train_fold(max_depth=max_depth) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/error_handling_v1.py* ### Flyte 2 ``` import flyte import flyte.errors env = flyte.TaskEnvironment(name="error_handling", resources=flyte.Resources(cpu=1, memory="250Mi")) @env.task async def train_fold(max_depth: int) -> float: if max_depth <= 0: raise ValueError("max_depth must be positive") return 0.90 + 0.001 * max_depth # Failure handling is ordinary Python try/except -- no on_failure handler. @env.task async def main(max_depth: int) -> float: try: return await train_fold(max_depth) except ValueError as e: print(f"invalid hyperparameter ({e}); falling back to a safe default") # Recover with a safe default instead of failing the whole run. return await train_fold(max_depth=6) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/error_handling_v2.py* Flyte 2 also exposes typed errors, so you can catch a specific failure and retry with more resources โ€” a common need for memory-hungry training jobs: ```python try: return await train_fold(sample_size) except flyte.errors.OOMError: # Retry the same task with a larger memory request. return await train_fold.override( resources=flyte.Resources(memory="16Gi") )(sample_size) ``` See **Tasks > Build tasks > Error handling** for more. ## Next - **Migration > From Flyte 1 to 2 > Parallelism and fan-out** โ€” running many tasks in parallel - **Migration > From Flyte 1 to 2 > ML workloads** โ€” training, HPO, and inference === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/parallelism === map_task becomes flyte.map, and fan-out becomes async and asyncio.gather. # Parallelism and fan-out Flyte 1's `map_task` becomes `flyte.map`, and the idiomatic Flyte 2 approach to fan-out is Python `async`/`await` with `asyncio.gather`. See the **Migration > From Flyte 1 to 2 > Migration overview > Asynchronous model** guide for the concepts, and **Migration > From Flyte 1 to 2 > Migration overview** for the overall approach. ## Fan-out: `map_task` `map_task()` becomes `flyte.map()`, a near drop-in replacement. The one catch: `flyte.map` returns a generator, so wrap it in `list()`. For new code, the idiomatic approach is Python `async`/`await` with `asyncio.gather()`, which gives you finer control over concurrency and error handling. ### Flyte 1 ```python from functools import partial from flytekit import task, workflow, map_task @task def get_shards(n: int) -> list[int]: return list(range(n)) @task def score_shard(shard_id: int, model_version: int) -> int: # Score one shard of records with the given model version. return shard_id * model_version @workflow def main(n: int, model_version: int) -> list[int]: shards = get_shards(n=n) return map_task( partial(score_shard, model_version=model_version), concurrency=10, )(shard_id=shards) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/map_task_v1.py* ### Flyte 2 (flyte.map) ``` @env.task def score_shard(shard_id: int, model_version: int) -> int: # Score one shard of records with the given model version. return shard_id * model_version @env.task def main(n: int, model_version: int) -> list[int]: bound = partial(score_shard, model_version=model_version) # flyte.map is a drop-in for map_task, but it returns a generator, so wrap # it in list() to materialize the results. return list(flyte.map(bound, range(n), concurrency=10)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/map_task_v2.py* ### Flyte 2 (asyncio.gather) ``` @env.task async def score_shard_async(shard_id: int, model_version: int) -> int: return shard_id * model_version @env.task async def main_async(n: int, model_version: int) -> list[int]: # asyncio.gather is the idiomatic Flyte 2 way to fan out. coros = [score_shard_async(i, model_version) for i in range(n)] return list(await asyncio.gather(*coros)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/map_task_v2.py* See the **Migration > From Flyte 1 to 2 > Migration overview > Asynchronous model** guide for the concepts behind async execution. ### Choosing `flyte.map` vs `asyncio.gather` | Feature | `flyte.map` (sync) | `asyncio.gather` (async) | |---|---|---| | Syntax | `list(flyte.map(fn, items))` | `await asyncio.gather(*tasks)` | | Concurrency limit | Built-in `concurrency=N` | Use `asyncio.Semaphore` | | Streaming / as-completed | No | Yes, via `asyncio.as_completed()` | | Error handling | `return_exceptions=True` | Check return type | Use **`flyte.map`** for the smallest change from Flyte 1 `map_task`, or when you're stuck in synchronous code. Use **`asyncio.gather`** for new code where you want streaming results or fine-grained concurrency control. ### Concurrency control and error handling `map_task`'s `concurrency` and `min_success_ratio` become an `asyncio.Semaphore` and `return_exceptions=True`: ```python import asyncio @env.task async def main(items: list[int], max_concurrent: int = 5) -> list[str]: sem = asyncio.Semaphore(max_concurrent) async def process_with_limit(item: int) -> str: async with sem: return await process_item(item) tasks = [process_with_limit(i) for i in items] results = await asyncio.gather(*tasks, return_exceptions=True) return [r for r in results if not isinstance(r, Exception)] ``` ## Data backfills Reprocessing a range of dates is a textbook `@dynamic` use case in Flyte 1, because the number of days is only known at runtime. In Flyte 2 it's a plain task that builds the date range and fans the days out with `asyncio.gather`. ### Flyte 1 ```python from datetime import date, timedelta from flytekit import task, workflow, dynamic @task def process_day(day: str) -> int: # Reprocess a single day's partition; return the row count. return len(day) # @dynamic is needed because the number of days is only known at runtime. @dynamic def backfill(start: str, days: int) -> list[int]: base = date.fromisoformat(start) results = [] for i in range(days): day = (base + timedelta(days=i)).isoformat() results.append(process_day(day=day)) return results @workflow def main(start: str, days: int) -> list[int]: return backfill(start=start, days=days) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/data_backfill_v1.py* ### Flyte 2 ``` import asyncio from datetime import date, timedelta import flyte env = flyte.TaskEnvironment(name="data_backfill") @env.task async def process_day(day: str) -> int: # Reprocess a single day's partition; return the row count. return len(day) # A plain task builds the date range at runtime and fans the days out in # parallel with asyncio.gather -- no @dynamic and no map_task needed. @env.task async def main(start: str, days: int) -> list[int]: base = date.fromisoformat(start) coros = [ process_day((base + timedelta(days=i)).isoformat()) for i in range(days) ] return list(await asyncio.gather(*coros)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/data_backfill_v2.py* For fine-grained concurrency control (semaphores, `as_completed`, error handling), see **Tasks > Build tasks > Fanout**. ## Next - **Migration > From Flyte 1 to 2 > Data types and I/O** โ€” files, DataFrames, and dataclasses - **Migration > From Flyte 1 to 2 > ML workloads** โ€” training, HPO, and batch inference === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/data-io === The offloaded-data types are renamed and their I/O is async, but the mental model is unchanged. # Data types and I/O Flyte 2 renames the offloaded-data types and makes their I/O `async`, but the mental model is the same: pass lightweight references to large data between tasks. See **Migration > From Flyte 1 to 2 > Migration overview** for the overall approach. ## Files and directories `FlyteFile` and `FlyteDirectory` become `flyte.io.File` and `flyte.io.Dir` โ€” the way you pass model artifacts and datasets between tasks. The I/O is now `async`: use `await File.from_local(...)` to upload and `async with file.open(...)` to read. Like their Flyte 1 counterparts, these are lightweight references to offloaded data, not the materialized bytes. ### Flyte 1 ```python import os from flytekit import task, workflow, current_context from flytekit.types.file import FlyteFile @task def write_file(content: str) -> FlyteFile: path = os.path.join(current_context().working_directory, "out.txt") with open(path, "w") as f: f.write(content) return FlyteFile(path=path) @task def read_file(f: FlyteFile) -> str: with open(f.download()) as fh: return fh.read() @workflow def main(content: str) -> str: f = write_file(content=content) return read_file(f=f) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/files_v1.py* ### Flyte 2 ``` import flyte from flyte.io import File env = flyte.TaskEnvironment(name="files") @env.task async def write_file(content: str) -> File: with open("out.txt", "w") as f: f.write(content) # File.from_local uploads the file to blob storage and returns a reference # (a lightweight pointer, not the materialized bytes). return await File.from_local("out.txt") @env.task async def read_file(f: File) -> str: async with f.open("rb") as fh: return (await fh.read()).decode("utf-8") @env.task async def main(content: str) -> str: f = await write_file(content) return await read_file(f) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/files_v2.py* See **Tasks > Build tasks > Files and directories** for more. ## DataFrames `StructuredDataset` becomes `flyte.io.DataFrame`. Construct one with `flyte.io.DataFrame.from_df(df)` and read it back with `await df.open(pandas.DataFrame).all()`. ### Flyte 1 ```python import pandas as pd from flytekit import task, workflow from flytekit.types.structured import StructuredDataset @task def make_df() -> StructuredDataset: df = pd.DataFrame({"employee_id": [1, 2, 3], "salary": [50000, 60000, 70000]}) return StructuredDataset(dataframe=df) @task def total_payroll(sd: StructuredDataset) -> float: df = sd.open(pd.DataFrame).all() return float(df["salary"].sum()) @workflow def main() -> float: return total_payroll(sd=make_df()) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/dataframe_v1.py* ### Flyte 2 ``` import pandas as pd import flyte import flyte.io env = flyte.TaskEnvironment( name="dataframe", image=flyte.Image.from_debian_base().with_pip_packages("pandas", "pyarrow"), ) @env.task async def make_df() -> flyte.io.DataFrame: df = pd.DataFrame({"employee_id": [1, 2, 3], "salary": [50000, 60000, 70000]}) # StructuredDataset becomes flyte.io.DataFrame. return flyte.io.DataFrame.from_df(df) @env.task async def total_payroll(fdf: flyte.io.DataFrame) -> float: df = await fdf.open(pd.DataFrame).all() return float(df["salary"].sum()) @env.task async def main() -> float: return await total_payroll(await make_df()) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/dataframe_v2.py* See **Tasks > Build tasks > DataFrames** for more. ## Dataclasses and structured types Flyte 1 required a `@dataclass_json` mixin for dataclass I/O. In Flyte 2, plain dataclasses (and Pydantic `BaseModel`s) work directly as task inputs and outputs โ€” handy for passing around a training config. ### Flyte 1 ```python from dataclasses import dataclass from dataclasses_json import dataclass_json from flytekit import task, workflow @dataclass_json @dataclass class TrainingConfig: learning_rate: float n_estimators: int max_depth: int = 6 @task def make_config(learning_rate: float, n_estimators: int) -> TrainingConfig: return TrainingConfig(learning_rate=learning_rate, n_estimators=n_estimators) @task def train(config: TrainingConfig) -> str: return ( f"trained with lr={config.learning_rate}, " f"n_estimators={config.n_estimators}, max_depth={config.max_depth}" ) @workflow def main(learning_rate: float, n_estimators: int) -> str: config = make_config(learning_rate=learning_rate, n_estimators=n_estimators) return train(config=config) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/dataclasses_v1.py* ### Flyte 2 ``` from dataclasses import dataclass import flyte env = flyte.TaskEnvironment(name="dataclasses") # Plain dataclasses work directly as task I/O -- no @dataclass_json mixin needed. # Pydantic BaseModels work the same way. @dataclass class TrainingConfig: learning_rate: float n_estimators: int max_depth: int = 6 @env.task def make_config(learning_rate: float, n_estimators: int) -> TrainingConfig: return TrainingConfig(learning_rate=learning_rate, n_estimators=n_estimators) @env.task def train(config: TrainingConfig) -> str: return ( f"trained with lr={config.learning_rate}, " f"n_estimators={config.n_estimators}, max_depth={config.max_depth}" ) @env.task def main(learning_rate: float, n_estimators: int) -> str: config = make_config(learning_rate, n_estimators) return train(config) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/dataclasses_v2.py* ## Data ETL Putting the data types together: extract, clean, aggregate, and write out a feature table. `StructuredDataset` becomes `flyte.io.DataFrame`, and the tasks become `async`. ### Flyte 1 ```python import pandas as pd from flytekit import task, workflow from flytekit.types.structured import StructuredDataset @task def extract() -> pd.DataFrame: # Read raw transaction records (stand-in for a real source). return pd.DataFrame( { "user_id": [1, 1, 2, 3, 3, 3], "amount": [10.0, 5.0, 20.0, 7.5, 2.5, 1.0], } ) @task def transform(df: pd.DataFrame) -> StructuredDataset: # Clean and aggregate into a per-user feature table. df = df[df["amount"] > 0] agg = df.groupby("user_id", as_index=False)["amount"].sum() return StructuredDataset(dataframe=agg) @task def load(sd: StructuredDataset) -> int: df = sd.open(pd.DataFrame).all() return len(df) @workflow def main() -> int: raw = extract() features = transform(df=raw) return load(sd=features) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/data_etl_v1.py* ### Flyte 2 ``` import pandas as pd import flyte import flyte.io env = flyte.TaskEnvironment( name="data_etl", image=flyte.Image.from_debian_base().with_pip_packages("pandas", "pyarrow"), ) @env.task async def extract() -> pd.DataFrame: # Read raw transaction records (stand-in for a real source). return pd.DataFrame( { "user_id": [1, 1, 2, 3, 3, 3], "amount": [10.0, 5.0, 20.0, 7.5, 2.5, 1.0], } ) @env.task async def transform(df: pd.DataFrame) -> flyte.io.DataFrame: # Clean and aggregate into a per-user feature table. df = df[df["amount"] > 0] agg = df.groupby("user_id", as_index=False)["amount"].sum() # StructuredDataset becomes flyte.io.DataFrame. return flyte.io.DataFrame.from_df(agg) @env.task async def load(sd: flyte.io.DataFrame) -> int: df = await sd.open(pd.DataFrame).all() return len(df) @env.task async def main() -> int: raw = await extract() features = await transform(raw) return await load(features) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/data_etl_v2.py* ## Next - **Migration > From Flyte 1 to 2 > ML workloads** โ€” training, HPO, and batch inference - **Migration > From Flyte 1 to 2 > Parallelism and fan-out** โ€” processing partitions in parallel === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/ml-workloads === Everyday ML workloads as complete Flyte 1 to Flyte 2 pairs. # ML workloads The core patterns compose into the workloads data scientists and ML engineers run every day. Each of these is a complete v1โ†’v2 pair in the [examples repo](https://github.com/unionai/unionai-examples/tree/main/v2/user-guide/migration/flyte-2). See **Migration > From Flyte 1 to 2 > Migration overview** for the overall approach. ## Small model training (scikit-learn / XGBoost) Train a model, persist it as a `File`, and evaluate it. Image, resources, and caching move to the `TaskEnvironment`; `FlyteFile` becomes `flyte.io.File`. ### Flyte 1 ```python import os import joblib from flytekit import task, workflow, ImageSpec, Resources, current_context from flytekit.types.file import FlyteFile from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from xgboost import XGBClassifier image = ImageSpec( name="xgb-image", packages=["xgboost", "scikit-learn", "joblib"], ) @task(container_image=image, requests=Resources(cpu="2", mem="4Gi")) def train_model(n_estimators: int, max_depth: int) -> FlyteFile: data = load_breast_cancer() X_train, _, y_train, _ = train_test_split(data.data, data.target, random_state=42) model = XGBClassifier(n_estimators=n_estimators, max_depth=max_depth) model.fit(X_train, y_train) model_path = os.path.join(current_context().working_directory, "model.json") joblib.dump(model, model_path) return FlyteFile(path=model_path) @task(container_image=image) def evaluate(model_file: FlyteFile) -> float: model = joblib.load(model_file.download()) data = load_breast_cancer() _, X_test, _, y_test = train_test_split(data.data, data.target, random_state=42) return float(model.score(X_test, y_test)) @workflow def main(n_estimators: int, max_depth: int) -> float: model = train_model(n_estimators=n_estimators, max_depth=max_depth) return evaluate(model_file=model) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/train_xgboost_v1.py* ### Flyte 2 ``` import os import joblib import flyte from flyte.io import File from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from xgboost import XGBClassifier env = flyte.TaskEnvironment( name="train_xgboost", image=flyte.Image.from_debian_base().with_pip_packages( "xgboost", "scikit-learn", "joblib" ), resources=flyte.Resources(cpu="2", memory="4Gi"), ) @env.task async def train_model(n_estimators: int, max_depth: int) -> File: data = load_breast_cancer() X_train, _, y_train, _ = train_test_split(data.data, data.target, random_state=42) model = XGBClassifier(n_estimators=n_estimators, max_depth=max_depth) model.fit(X_train, y_train) model_path = os.path.join(os.getcwd(), "model.json") joblib.dump(model, model_path) return await File.from_local(model_path) @env.task async def evaluate(model_file: File) -> float: local_path = await model_file.download() model = joblib.load(local_path) data = load_breast_cancer() _, X_test, _, y_test = train_test_split(data.data, data.target, random_state=42) return float(model.score(X_test, y_test)) @env.task async def main(n_estimators: int, max_depth: int) -> float: model = await train_model(n_estimators, max_depth) return await evaluate(model) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/train_xgboost_v2.py* ## Hyperparameter optimization Fan out one training run per hyperparameter, then pick the best. In Flyte 1 the grid search runs through `map_task` and the "pick the best" step must itself be a task. In Flyte 2 you `gather` the runs and select the winner in plain Python. ### Flyte 1 ```python from flytekit import task, workflow, map_task from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score @task def get_grid() -> list[int]: return [2, 4, 8, 16] @task def train_eval(max_depth: int) -> float: data = load_iris() model = RandomForestClassifier(max_depth=max_depth, random_state=42) scores = cross_val_score(model, data.data, data.target, cv=3) return float(scores.mean()) @task def best_score(scores: list[float]) -> float: return max(scores) @workflow def main() -> float: grid = get_grid() # Fan out one training run per hyperparameter value. scores = map_task(train_eval)(max_depth=grid) return best_score(scores=scores) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/hpo_v1.py* ### Flyte 2 ``` import asyncio import flyte from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score env = flyte.TaskEnvironment( name="hpo", image=flyte.Image.from_debian_base().with_pip_packages("scikit-learn"), ) @env.task async def train_eval(max_depth: int) -> float: data = load_iris() model = RandomForestClassifier(max_depth=max_depth, random_state=42) scores = cross_val_score(model, data.data, data.target, cv=3) return float(scores.mean()) @env.task async def main() -> dict: grid = [2, 4, 8, 16] # Fan out one training run per hyperparameter value... scores = await asyncio.gather(*[train_eval(d) for d in grid]) # ...then pick the best in plain Python (impossible in a Flyte 1 workflow). best_idx = max(range(len(scores)), key=lambda i: scores[i]) return {"best_max_depth": grid[best_idx], "best_score": scores[best_idx]} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/hpo_v2.py* ## Large model training (deep learning) GPU configuration moves to the `TaskEnvironment`: the Flyte 1 `Resources(gpu="1")` plus a separate `accelerator=T4` become a single `gpu="T4:1"` string on `flyte.Resources`. ### Flyte 1 ```python from flytekit import task, workflow, ImageSpec, Resources import flytekit import torch import torch.nn as nn image = ImageSpec( name="dl-image", packages=["torch"], ) @task( container_image=image, requests=Resources(cpu="2", mem="4Gi"), enable_deck=True, ) def train(epochs: int) -> float: device = "cuda" if torch.cuda.is_available() else "cpu" model = nn.Linear(10, 1).to(device) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) loss_fn = nn.MSELoss() X = torch.randn(128, 10, device=device) y = torch.randn(128, 1, device=device) loss = torch.tensor(0.0) for _ in range(epochs): optimizer.zero_grad() loss = loss_fn(model(X), y) loss.backward() optimizer.step() flytekit.current_context().default_deck.append(f"loss: {float(loss.item())}") flytekit.Deck.publish() return float(loss.item()) @workflow def main(epochs: int) -> float: return train(epochs=epochs) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/train_deep_learning_v1.py* ### Flyte 2 ``` import flyte import flyte.report import torch import torch.nn as nn # GPU type and count go in a single "T4:1"-style string. For multi-node # distributed training, wrap the training task with the torch elastic plugin. env = flyte.TaskEnvironment( name="train_deep_learning", image=flyte.Image.from_debian_base().with_pip_packages("torch"), resources=flyte.Resources(cpu="2", memory="4Gi"), ) @env.task(report=True) async def train(epochs: int) -> float: device = "cuda" if torch.cuda.is_available() else "cpu" model = nn.Linear(10, 1).to(device) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) loss_fn = nn.MSELoss() X = torch.randn(128, 10, device=device) y = torch.randn(128, 1, device=device) loss = torch.tensor(0.0) for _ in range(epochs): optimizer.zero_grad() loss = loss_fn(model(X), y) loss.backward() optimizer.step() flyte.report.log(f"loss: {float(loss.item())}
") flyte.report.flush() return float(loss.item()) @env.task async def main(epochs: int) -> float: return await train(epochs) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/train_deep_learning_v2.py* For multi-node distributed training (PyTorch elastic, etc.), see **Tasks > Configure tasks > Resources** and the plugin integrations. ## Batch inference Load a trained model once and score many batches in parallel. `map_task` with a `partial`-bound model becomes `asyncio.gather` over the batches, reusing the same model reference. ### Flyte 1 ```python import os from functools import partial import joblib from flytekit import task, workflow, map_task, ImageSpec, current_context from flytekit.types.file import FlyteFile from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier image = ImageSpec(name="inference-image", packages=["scikit-learn", "joblib"]) @task(container_image=image) def train_model() -> FlyteFile: data = load_iris() model = RandomForestClassifier().fit(data.data, data.target) model_path = os.path.join(current_context().working_directory, "model.joblib") joblib.dump(model, model_path) return FlyteFile(path=model_path) @task(container_image=image) def get_batches() -> list[list[list[float]]]: data = load_iris() rows = data.data.tolist() # Split the rows into batches of 30. return [rows[i : i + 30] for i in range(0, len(rows), 30)] @task(container_image=image) def score_batch(model_file: FlyteFile, batch: list[list[float]]) -> list[int]: model = joblib.load(model_file.download()) return [int(p) for p in model.predict(batch)] @workflow def main() -> list[list[int]]: model = train_model() batches = get_batches() return map_task(partial(score_batch, model_file=model))(batch=batches) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/batch_inference_v1.py* ### Flyte 2 ``` import asyncio import os import joblib import flyte from flyte.io import File from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier env = flyte.TaskEnvironment( name="batch_inference", image=flyte.Image.from_debian_base().with_pip_packages("scikit-learn", "joblib"), ) @env.task async def train_model() -> File: data = load_iris() model = RandomForestClassifier().fit(data.data, data.target) model_path = os.path.join(os.getcwd(), "model.joblib") joblib.dump(model, model_path) return await File.from_local(model_path) @env.task async def score_batch(model_file: File, batch: list[list[float]]) -> list[int]: local_path = await model_file.download() model = joblib.load(local_path) return [int(p) for p in model.predict(batch)] @env.task async def main() -> list[list[int]]: model = await train_model() rows = load_iris().data.tolist() batches = [rows[i : i + 30] for i in range(0, len(rows), 30)] # Score every batch in parallel, reusing the same model reference. coros = [score_batch(model, batch) for batch in batches] return list(await asyncio.gather(*coros)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/batch_inference_v2.py* ## A complete example: end-to-end ML pipeline Putting it together โ€” a load / train / evaluate pipeline shows the image, resources, caching, file I/O, and orchestration changes in one place. ### Flyte 1 ```python import os import joblib import pandas as pd from flytekit import task, workflow, ImageSpec, Resources, current_context from flytekit.types.file import FlyteFile from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier image = ImageSpec( name="ml-image", packages=["pandas", "scikit-learn", "joblib"], ) @task( container_image=image, requests=Resources(cpu="2", mem="4Gi"), cache=True, cache_version="1.0", ) def load_data() -> pd.DataFrame: data = load_iris(as_frame=True) df = data.frame df["species"] = data.target return df @task(container_image=image) def train_model(data: pd.DataFrame) -> FlyteFile: model = RandomForestClassifier() X = data.drop("species", axis=1) y = data["species"] model.fit(X, y) model_path = os.path.join(current_context().working_directory, "model.joblib") joblib.dump(model, model_path) return FlyteFile(path=model_path) @task(container_image=image) def evaluate(model_file: FlyteFile, data: pd.DataFrame) -> float: model = joblib.load(model_file.download()) X = data.drop("species", axis=1) y = data["species"] return float(model.score(X, y)) @workflow def main() -> float: data = load_data() model = train_model(data=data) return evaluate(model_file=model, data=data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/ml_pipeline_v1.py* ### Flyte 2 ``` import os import joblib import pandas as pd import flyte from flyte.io import File from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier # Image, resources, and cache are set once on the TaskEnvironment. env = flyte.TaskEnvironment( name="ml_pipeline", image=flyte.Image.from_debian_base().with_pip_packages( "pandas", "scikit-learn", "joblib", "pyarrow", ), resources=flyte.Resources(cpu="2", memory="4Gi"), cache="auto", ) @env.task async def load_data() -> pd.DataFrame: data = load_iris(as_frame=True) df = data.frame df["species"] = data.target return df @env.task async def train_model(data: pd.DataFrame) -> File: model = RandomForestClassifier() X = data.drop("species", axis=1) y = data["species"] model.fit(X, y) model_path = os.path.join(os.getcwd(), "model.joblib") joblib.dump(model, model_path) return await File.from_local(model_path) @env.task async def evaluate(model_file: File, data: pd.DataFrame) -> float: local_path = await model_file.download() model = joblib.load(local_path) X = data.drop("species", axis=1) y = data["species"] return float(model.score(X, y)) # The "workflow" is just an orchestrating task. @env.task async def main() -> float: data = await load_data() model = await train_model(data) return await evaluate(model, data) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/migration/flyte-2/ml_pipeline_v2.py* ## Next - **Migration > From Flyte 1 to 2 > New in Flyte 2: patterns that weren't possible in Flyte 1** โ€” real-time serving, apps, and sandboxing - **Migration > From Flyte 1 to 2 > Gotchas and caveats** โ€” caveats of the new execution model === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/new-in-flyte-2 === What Flyte 2 adds on top of batch orchestration, starting with long-running services. # New in Flyte 2: patterns that weren't possible in Flyte 1 Flyte 1 was a batch orchestration system: everything ran as a finite DAG that started, did work, and finished. Flyte 2 keeps all of that and adds **long-running services**, **high-throughput batch inference**, and **sandboxed code execution** โ€” so the same project that trains your model can also serve it, host a dashboard, saturate a GPU, or safely run LLM-generated code. There is no v1 counterpart to migrate here; these are net-new capabilities. ## Real-time inference and model serving Instead of scoring a batch and exiting, you can stand up an always-on REST endpoint from a `FastAPIAppEnvironment` and deploy it with `flyte.deploy`. The app can load a model artifact produced by one of your training tasks. ``` app = FastAPI(title="ML Model API") # Define request/response models class PredictionRequest(BaseModel): feature1: float feature2: float feature3: float class PredictionResponse(BaseModel): prediction: float probability: float # Load model (you would typically load this from storage) model = None @asynccontextmanager async def lifespan(app: FastAPI): global model model_path = os.getenv("MODEL_PATH", "/app/models/model.joblib") # In production, load from your storage if os.path.exists(model_path): with open(model_path, "rb") as f: model = joblib.load(f) yield @app.post("/predict", response_model=PredictionResponse) async def predict(request: PredictionRequest): # Make prediction # prediction = model.predict([[request.feature1, request.feature2, request.feature3]]) # Dummy prediction for demo prediction = 0.85 probability = 0.92 return PredictionResponse( prediction=prediction, probability=probability, ) env = FastAPIAppEnvironment( name="ml-model-api", app=app, image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages( "fastapi", "uvicorn", "scikit-learn", "pydantic", "joblib", ), parameters=[ flyte.app.Parameter( name="model_file", value=flyte.io.File.from_existing_remote("s3://bucket/models/model.joblib"), mount="/app/models", env_var="MODEL_PATH", ), ], resources=flyte.Resources(cpu=2, memory="2Gi"), requires_auth=False, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/fastapi/ml_model_serving.py* See [Build apps](../../apps/build-apps/_index) and [Serve and deploy apps](../../apps/serve-and-deploy-apps/_index). ## LLM serving For serving large language models, the `flyteplugins-vllm` integration gives you a production-grade vLLM server (with autoscaling to zero) in a few lines. ``` vllm_app = VLLMAppEnvironment( name="my-llm-app", model_hf_path="Qwen/Qwen3-0.6B", # HuggingFace model path model_id="qwen3-0.6b", # Model ID exposed by vLLM resources=flyte.Resources( cpu="4", memory="16Gi", gpu="L40s:1", # GPU required for LLM serving disk="10Gi", ), scaling=flyte.app.Scaling( replicas=(0, 1), scaledown_after=300, # Scale down after 5 minutes of inactivity ), requires_auth=False, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/build-apps/vllm/basic_vllm.py* See **Inference > Self-hosted endpoints > vLLM** and the other [Native app integrations](../../apps/native-app-integrations/_index) (SGLang, Streamlit, FastAPI). ## App serving (dashboards and APIs) Any web app โ€” a Streamlit dashboard for exploring results, a Gradio demo, a Flask backend โ€” runs as an `AppEnvironment`. Configure the image, resources, port, autoscaling, and a custom subdomain, then `flyte.serve` it. ``` app_env = flyte.app.AppEnvironment( name="hello-world-app", image=image, args=["streamlit", "hello", "--server.port", "8080"], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, domain=flyte.app.Domain(subdomain="hello"), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/configure-apps/hello-world-app.py* See **Get started > Core concepts > Apps** and [Configure apps](../../apps/configure-apps/_index). ## Dynamic batching for GPU inference For in-process batch inference, `DynamicBatcher` from `flyte.extras` keeps an expensive GPU saturated: async producers load and preprocess data concurrently while a single consumer feeds the model in optimally-sized batches, with built-in backpressure. This replaces the Flyte 1 pattern of standing up a separate inference server just to get request batching. ```python import asyncio from flyte.extras import DynamicBatcher async with DynamicBatcher( process_fn=run_inference, # takes a batch, returns results in the same order target_batch_cost=1000, # cost budget per batch max_batch_size=64, # hard cap on records per batch batch_timeout_s=0.05, # max wait before dispatching a partial batch ) as batcher: futures = [await batcher.submit(record) for record in records] results = await asyncio.gather(*futures) ``` `submit()` is non-blocking and returns a `Future`; when the queue is full it applies backpressure automatically. See **Inference > Maximize GPU utilization for batch inference**, which also covers `TokenBatcher` for token-aware LLM batching. ## Sandboxed code execution `flyte.sandbox.create()` runs arbitrary Python code or shell commands inside an ephemeral, single-use Docker container โ€” built on demand from declared dependencies, executed once, then discarded. Only declared inputs go in and only declared outputs come back, which makes it the safe way to run **untrusted code, most importantly code generated by an LLM**. ``` # sandbox_environment provides the base runtime for code sandboxes. # Include it in depends_on so the sandbox runtime is available when tasks execute. env = flyte.TaskEnvironment( name="sandbox-demo", image=flyte.Image.from_debian_base(name="sandbox-demo"), depends_on=[sandbox_environment], ) # Auto-IO mode: pure computation. The code string runs in an isolated sandbox; # only the declared inputs go in and only the declared outputs come back. sum_sandbox = flyte.sandbox.create( name="sum-to-n", code="total = sum(range(n + 1)) if conditional else 0", inputs={"n": int, "conditional": bool}, outputs={"total": int}, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/user-guide/sandboxing/code_sandbox.py* Call it from a task with `await sum_sandbox.run.aio(n=10, conditional=True)`. See **Agents > Sandboxing > Code sandboxing**. This also powers **code mode** (programmatic tool calling), where an agent writes a whole program instead of emitting one tool call at a time โ€” see **Agents > Sandboxing > Programmatic tool calling for agents**. ## Next - **Migration > From Flyte 1 to 2 > Gotchas and caveats** โ€” caveats of the new execution model - **Migration > From Flyte 1 to 2 > Hybrid v1 and v2 pipelines** โ€” calling between v1 and v2 during the transition === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/union-features === Where Flyte 1's Union-specific Actors and Apps landed in Flyte 2. # Migrating Union-specific features A couple of constructs that were specific to Union in Flyte 1 โ€” **Actors** and **Apps** โ€” have direct equivalents in Flyte 2. Apps, in particular, are now part of the open-source Flyte SDK rather than a Union-only add-on. See **Migration > From Flyte 1 to 2 > Migration overview** for the overall approach. ## Actors โ†’ reusable containers Flyte 1 **Actors** kept a pool of warm containers alive so that many short tasks could skip the cold-start cost and share in-memory state. In Flyte 2 this is **reusable containers**: instead of a separate `ActorEnvironment`, you add a `flyte.ReusePolicy` to an ordinary `TaskEnvironment`, and its tasks are plain `@env.task`s. ### Flyte 1 (Actors) ```python import union actor = union.ActorEnvironment( name="my-actor", replica_count=2, ttl_seconds=300, requests=union.Resources(cpu="1", mem="1Gi"), ) @actor.task def compute(x: int) -> int: return x * x ``` ### Flyte 2 (reusable containers) ```python from datetime import timedelta import flyte # The reusable-container runtime library must be in the task image. image = flyte.Image.from_debian_base().with_pip_packages("unionai-reuse>=0.1.10") env = flyte.TaskEnvironment( name="my-reusable-env", image=image, resources=flyte.Resources(cpu="1", memory="1Gi"), reusable=flyte.ReusePolicy( replicas=2, # pool size (was replica_count) concurrency=1, # tasks per container (new) scaledown_ttl=timedelta(minutes=5), # idle single-container shutdown idle_ttl=timedelta(minutes=30), # idle whole-pool shutdown ), ) @env.task async def compute(x: int) -> int: return x * x ``` | Flyte 1 `ActorEnvironment` | Flyte 2 `ReusePolicy` | Notes | |---|---|---| | `replica_count` | `replicas` | Pool size | | `ttl_seconds` | `scaledown_ttl` / `idle_ttl` | Split into per-container and whole-pool timeouts | | `requests` | `TaskEnvironment(resources=...)` | Resources move to the environment | | N/A | `concurrency` | New: async tasks per container (total capacity is `replicas ร— concurrency`) | | `@actor.task` | `@env.task` | A regular task | Reusable containers require the [`unionai-reuse`](https://pypi.org/project/unionai-reuse/) package in the task image and, as in Flyte 1, run on a Union backend. See **Tasks > Configure tasks > Reusable containers** for the full parameter reference and capacity math. ## Apps โ†’ the Flyte SDK Flyte 1 **Apps** (`union.app.App`) were a Union-only way to serve long-running web apps and model endpoints. In Flyte 2 the same capability is built into the open-source **Flyte SDK** as `flyte.app.AppEnvironment`, deployed with `flyte.serve` (development) or `flyte.deploy` (production). ### Flyte 1 (union.app) ```python from union import ImageSpec, Resources from union.app import App app = App( name="my-app", container_image=ImageSpec(name="my-app", packages=["fastapi", "union-runtime"]), limits=Resources(cpu="1", mem="1Gi"), port=8080, include=["./main.py"], args="fastapi run --port 8080", requires_auth=False, ) ``` Deploy with the `union deploy apps` CLI. ### Flyte 2 (flyte.app) ```python import flyte import flyte.app app_env = flyte.app.AppEnvironment( name="my-app", image=flyte.Image.from_debian_base().with_pip_packages("fastapi", "uvicorn"), args=["fastapi", "run", "--port", "8080"], port=8080, resources=flyte.Resources(cpu="1", memory="1Gi"), requires_auth=False, ) if __name__ == "__main__": flyte.init_from_config() app = flyte.serve(app_env) # or flyte.deploy(app_env) for production print(app.url) ``` Because apps are now part of the OSS SDK, the same `flyte.app` API covers dashboards (Streamlit, Gradio), REST and webhook backends (FastAPI, Flask), and model serving. For LLM serving specifically, use the `flyteplugins-vllm` or SGLang integrations. See: - [Configure apps](../../apps/configure-apps/_index) โ€” the `AppEnvironment` configuration reference - [Build apps](../../apps/build-apps/_index) and [Serve and deploy apps](../../apps/serve-and-deploy-apps/_index) - [Native app integrations](../../apps/native-app-integrations/_index) โ€” Streamlit, FastAPI, vLLM, SGLang ## Next - **Migration > From Flyte 1 to 2 > New in Flyte 2: patterns that weren't possible in Flyte 1** โ€” real-time serving, batch inference, and sandboxing - **Migration > From Flyte 1 to 2 > Gotchas and caveats** โ€” caveats of the new execution model === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/hybrid-pipelines === Run Flyte 1 and Flyte 2 workloads side by side and have them call each other. # Hybrid v1 and v2 pipelines Migrations rarely happen all at once. For a while you'll have Flyte 1 and Flyte 2 workloads running side by side, and you'll want them to call each other: a Flyte 1 workflow that kicks off a newly ported Flyte 2 task, or a Flyte 2 task that triggers a workflow that hasn't been migrated yet. You can bridge the two in both directions. The idea is the same each way: one task installs **both** SDKs, authenticates to the **other** control plane, fetches the entity it wants to run, and launches it. > **๐Ÿ“ Note** > > The bridging task acts as a driver: it authenticates to a remote control plane and launches work there. Keep it lightweight and focused on orchestration โ€” see **Migration > From Flyte 1 to 2 > Gotchas and caveats**. ## Running a Flyte 2 task from a Flyte 1 workflow The bridge is a single Flyte 1 task โ€” call it `launch_v2_from_v1` โ€” that runs the Flyte 2 client. **High-level steps:** 1. Give the `launch_v2_from_v1` task an image with **both** `flytekit` (Flyte 1) and `flyte` (Flyte 2) installed. 2. Give it a Flyte 2 **API key** (see **Migration > From Flyte 1 to 2 > Hybrid v1 and v2 pipelines > Running a Flyte 2 task from a Flyte 1 workflow > 1. Create the API key and store it** below โ€” how you create one differs between Union and open-source Flyte). The key is the `export FLYTE_API_KEY="..."` value it produces. 3. Make the key available to the task, either by storing it as a secret it can read, or by injecting it as the `FLYTE_API_KEY` environment variable. 4. Authenticate inside the task with `flyte.init_from_api_key()`. 5. Fetch the deployed Flyte 2 task with `flyte.remote.Task.get(...)` and run it with `flyte.run(...)`. ### 1. Create the API key and store it Create a key with `flyte create api-key` (a command provided by the `flyteplugins-union` plugin) or through the Union UI, then store it as a secret: ```bash # Create a Flyte 2 API key (prints `export FLYTE_API_KEY="..."`) flyte create api-key --name v1-to-v2-bridge # Store that value as a Flyte 2 secret (you can also create it in the Union UI) flyte create secret flyte_api_key --value "" ``` You can also make the same value available to your Flyte 1 task as a secret through your existing Flyte 1 secret workflow, or set it directly as the `FLYTE_API_KEY` environment variable on the task. ### 2. Write the bridging task CODE0 The referenced Flyte 2 task (`my_v2_env.process` above) must be **deployed** before the bridge runs โ€” `flyte.remote.Task.get()` looks it up by `env_name.task_name`. See [Remote tasks](../../tasks/task-programming/remote-tasks.md) for versioning options (`auto_version="latest"`, `version="v1.2.3"`) and `flyte.run` details. > **๐Ÿ“ Note** > > `flyte.init_from_api_key()` is required here โ€” do **not** use `flyte.init_from_config()`, which reads a `config.yaml` that has no API-key field. See [Run on a deployed cluster](../../get-started/run-modes/running-remote.md) for the authentication methods. ## Running a Flyte 1 workflow from a Flyte 2 task The reverse works the same way: a Flyte 2 task installs the Flyte 1 client and uses `UnionRemote` to launch a Flyte 1 workflow. **High-level steps:** 1. Give the `launch_v1_from_v2` `TaskEnvironment` an image with the Flyte 1 client (`union`) installed. 2. Provide the task with credentials for the Flyte 1 control plane (a config file or API key, supplied as a secret). 3. Instantiate a `UnionRemote` client inside the task. 4. Fetch the Flyte 1 workflow with `fetch_workflow(...)`. 5. Launch it with `execute(...)`. CODE1 On Union, use `union.remote.UnionRemote` instead of `flytekit.remote.FlyteRemote`. It auto-detects your Union configuration, so you can construct it with no arguments: CODE2 ## Considerations - **Both SDKs in one image.** The bridging task installs `flytekit` and `flyte` together. Pin versions and watch for dependency conflicts; keep the bridge image minimal. - **Deploy the callee first.** For the v1โ†’v2 direction, the Flyte 2 task must be deployed (`flyte deploy`) before `flyte.remote.Task.get()` can resolve it. For the v2โ†’v1 direction, the Flyte 1 workflow must be registered on its cluster. - **Wait vs. fire-and-forget.** Both `run.wait()` (v2) and `execute(..., wait=True)` (v1) block until the launched run finishes. Omit them to launch and return immediately, then poll or hand off the execution URL. - **Credentials cross a boundary.** The bridge authenticates to a *different* control plane than the one it runs on. Store the API key or client credentials as a secret โ€” never hard-code them. See [Secrets](../../tasks/task-configuration/secrets.md) and [Run on a deployed cluster](../../get-started/run-modes/running-remote.md). - **Keep the bridge lightweight.** Like any orchestrating task, it should mostly launch and assemble results rather than do heavy compute โ€” see [Gotchas and caveats](gotchas-and-caveats.md). ## See also - [Remote tasks](../../tasks/task-programming/remote-tasks.md) โ€” fetching and running deployed Flyte 2 tasks - [Run on a deployed cluster](../../get-started/run-modes/running-remote.md) โ€” authentication methods, including `flyte.init_from_api_key()` - **Migration > From Flyte 1 to 2 > Hybrid v1 and v2 pipelines > Authenticating** โ€” API key authentication in depth - **Migration > From Flyte 1 to 2 > Migration overview** โ€” mapping Flyte 1 workload patterns to Flyte 2 === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/flyte-2/gotchas-and-caveats === Where Flyte 2's flexibility can surprise you, and what to watch for. # Gotchas and caveats Flyte 2 is a substantial change from Flyte 1: each Python task can act as its own engine, launching sub-tasks and assembling their outputs. That flexibility is powerful, but it warrants some caveats when authoring your tasks. This page starts with a quick list of common gotchas you'll hit during a migration, then covers the deeper execution-model considerations in detail. ## Common gotchas - **`flyte.map` returns a generator.** Wrap it in `list()` to materialize results, unlike `map_task` which returned a list directly. - **`memory`, not `mem`.** The `Resources` parameter was renamed, and there are no separate `requests`/`limits` โ€” a single value serves as both. - **GPUs use a `"T4:1"` string.** Type and count are combined; the separate `accelerator=` argument is gone. - **Image, resources, and cache live on the `TaskEnvironment`.** Set them once at the env level instead of repeating them on every task decorator. - **`current_context()` is gone.** Read secrets from environment variables and use `flyte.ctx()` for runtime context. - **The `>>` ordering operator is gone.** Sequential (sync) calls and sequential `await`s are naturally ordered. - **Retries no longer have a platform cap.** In Flyte 1 the control plane capped attempts at 3; in Flyte 2 total attempts equal `retries + 1`. Audit any large `retries` values before deploying. - **You can only `await` async tasks.** Call a sync task from an async context with `.aio()`; see the **Migration > From Flyte 1 to 2 > Migration overview > Asynchronous model**. - **Pick an entrypoint task name.** There's no `@workflow`, so the top-level task is just a task (commonly `main`); run it with `flyte run module.py main`. - **Type annotations are more lenient.** Flyte 2 will pickle untyped I/O rather than rejecting it at registration. - **Keep orchestration lightweight.** A task that calls other tasks acts as a driver pod. Avoid heavy CPU work in it โ€” see **Migration > From Flyte 1 to 2 > Gotchas and caveats > Driver pod requirements** below. ## Non-deterministic behavior When a task launches another task, a new Action ID is determined. This ID is a hash of the inputs to the task, the task definition itself, along with some other information. The fact that this ID is consistently hashed is important when it comes to things like recovery and replay. For example, assume you have the following tasks ```python @env.task async def t1(): val = get_int_input() await t2(int=val) @env.task async def t2(val: int): ... ``` If you run `t1`, and it launches the downstream `t2` task, and then the pod executing `t1` fails, when Flyte restarts `t1` it will automatically detect that `t2` is still running and will just use that. If `t2` ends up finishing in the interim, those results would just be used. However, if you introduce non-determinism into the picture, then that guarantee is no longer there. To give a contrived example: ```python @env.task async def t1(): val = get_int_input() now = datetime.now() if now.second % 2 == 0: await t2(int=val) else: await t3(int=val) ``` Here, depending on what time it is, either `t2` or `t3` may end up running. In the earlier scenario, if `t1` crashes unexpectedly, and Flyte retries the execution, a different downstream task may get kicked off instead. ### Dealing with non-determinism As a developer, the best way to manage non-deterministic behavior (if it is unavoidable) is to be able to observe it and see exactly what is happening in your code. Flyte 2 provides precisely the tool needed to enable this: Traces. With this feature you decorate the sub-task functions in your code with `@trace`, enabling checkpointing, reproducibility and recovery at a fine-grained level. See **Tasks > Build tasks > Traces** for more details. ## Type safety In Flyte 1, the top-level workflow was defined by a Python-like DSL that was compiled into a static DAG composed of tasks, each of which was, internally, defined in real Python. The system was able to guarantee type safety across task boundaries because the task definitions were static and the inputs and outputs were defined in a way that Flytekit could validate them. In Flyte 2, the top-level workflow is defined by Python code that runs at runtime (unless using a compiled task). This means that the system can no longer guarantee type safety at the workflow level. Happily, the Python ecosystem has evolved considerably since Flyte 1, and Python type hints are now a standard way to define types. Consequently, in Flyte 2, developers should use Python type hints and type checkers like `mypy` to ensure type safety at all levels, including the top-most task (i.e., the "workflow" level). ## No global state A core principle of Flyte 2 (that is also shared with Flyte 1) is that you should not try to maintain global state across your workflow. It will not be translated across tasks containers, In a single process Python program, global variables are available across functions. In the distributed execution model of Flyte, each task runs in its own container, and each container is isolated from the others. If there is some state that needs to be preserved, it must be reconstructable through repeated deterministic execution. ## Driver pod requirements Tasks don't have to kick off downstream tasks of course and may themselves represent a leaf level atomic unit of compute. However, when tasks do run other tasks, and more so if they assemble the outputs of those other tasks, then that parent task becomes a driver pod of sorts. In Flyte 1, this assembling of intermediate outputs was done by Flyte Propeller. In 2, it's done by the parent task. This means that the pod running your parent task must be appropriately sized, and should ideally not be CPU-bound, otherwise it slow down downstream evaluation and kickoff of tasks. For example, if you had this also scenario, ```python @env.task async def t_main(): await t1() local_cpu_intensive_function() await t2() ``` The pod running `t_main` will hang in between tasks `t1` and `t2`. Your parent tasks should ideally focus only on orchestration. ## OOM risk from materialized I/O Something maybe more nuanced is that if you're not using the soon-to-be-released ref mode, outputs are actually materialized. That is, if you have the following scenario, ```python @env.task async def produce_1gb_list() -> List[float]: ... @env.task async def t1(): list_floats = produce_1gb_list() t2(floats=list_floats) ``` The pod running `t1` needs to have memory to handle that 1 GB of floats. Those numbers will be materialized in that pod's memory. This can lead to out of memory issues. Note that `flyte.io.File`, `flyte.io.Dir` and `flyte.io.DataFrame` will not suffer from this because while those are materialized, they're only materialized as pointers to offloaded data, so their memory footprint is much lower. === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/from-airflow === Mapping from Airflow concepts (DAGs, operators, schedules, XCom, trigger rules) to their Flyte 2 equivalents. # From Airflow to Flyte A staged guide to migrating Airflow DAGs to Flyte 2. The migration is split by operator family. Each section maps an Airflow construct to its Flyte 2 equivalent. ### **Migration > From Airflow to Flyte > Part 1: vanilla operators** PythonOperator, TaskFlow, BashOperator, KubernetesPodOperator, plus DAG schedules, the driver task model, and orchestration patterns (parallelism, conditionals, error handling). > [!NOTE] > **Part 2** (later) covers provider operators: Beam, Dataproc, BigQuery, Databricks, Spark, and sensors. ## Subpages - **Migration > From Airflow to Flyte > Part 1: vanilla operators** - PythonOperator, TaskFlow, BashOperator, KubernetesPodOperator, plus DAG schedules, the driver task model, and orchestration patterns (parallelism, conditionals, error handling). === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/from-airflow/part-1-vanilla-operators === PythonOperator, TaskFlow, BashOperator, KubernetesPodOperator, plus DAG schedules, the driver task model, and orchestration patterns (parallelism, conditionals, error handling). # Part 1: vanilla operators This is the first part of the [Airflow โ†’ Flyte migration guide](./_index). It covers: 1. Where dependencies are specified 2. The driver task (in place of a DAG definition) 3. Triggers (in place of DAG schedules) 4. PythonOperator โ†’ `@env.task` 5. TaskFlow โ†’ `@env.task` 6. BashOperator โ†’ ContainerTask 7. KubernetesPodOperator โ†’ TaskEnvironment + PodTemplate 8. Orchestration: parallelism, conditionals, error handling **Part 2** (later) covers provider operators: Beam, Dataproc, BigQuery, Databricks, Spark, sensors. --- ## 1. Where dependencies are specified In Airflow, dependencies are specified at the platform level. A single Airflow deployment has a base image with a fixed Python environment; every DAG author writes against the same set of installed libraries. Adding a new library means modifying the deployment (Helm `extraPipPackages`, a custom base image, or a redeploy), or working around the shared env with `PythonVirtualenvOperator`, `DockerOperator`, or `KubernetesPodOperator`. In Flyte, dependencies are specified at the code level. Each task declares its `TaskEnvironment`, which includes the image and its dependencies. The image is the unit of isolation, and a single workflow can fan out across tasks running in different images. Two ways to declare the image: ```python # (a) Build with flyte.Image โ€” from a base, add pip/apt packages, env vars, etc. etl_env = flyte.TaskEnvironment( name="etl", image=flyte.Image.from_debian_base() .with_pip_packages("pandas", "pyarrow"), ) # (b) Pass a string reference to an existing image โ€” for example the same one # you already deploy with in your Airflow KubernetesExecutor / KPO setup. gpu_env = flyte.TaskEnvironment( name="gpu", image="registry.example.com/my-org/gpu-training:2026.04.01", ) ``` Docs: **Get started > Core concepts > TaskEnvironment** ยท **Tasks > Configure tasks > Container images** --- ## 2. The driver task (in place of DAGs) Airflow DAGs are static graphs. The `with DAG(...)` block runs at parse time; the scheduler compiles the node/edge structure and then traverses it. Flyte has no parse-time graph. The driver task is Python code that runs at execution time; the graph is built dynamically as the driver calls other tasks. There is no compilation step. Flyte tasks are async-native: `@env.task` functions are typically declared `async def` and tasks are invoked with `await`. Plain `def` tasks are also supported when you don't need concurrency. ```python @env.task async def driver(start: date, regions: list[str]) -> list[Summary]: data = await fetch(start) summaries = await asyncio.gather( *[summarize(data, region) for region in regions] ) return summaries ``` The driver is just a task that calls other tasks; there's no separate workflow object. --- ## 3. Triggers (in place of schedules) Airflow's `schedule=` on a DAG maps to a Flyte `Trigger` attached to a task. | Airflow | Flyte | |---|---| | `schedule="@hourly"` | `flyte.Trigger.hourly()` | | `schedule="@daily"` | `flyte.Trigger.daily()` | | `schedule="0 5 * * *"` | `flyte.Trigger("nightly", flyte.Cron("0 5 * * *"))` | | `schedule="30 9 * * 1-5"` + `timezone=...` | `flyte.Trigger("biz_hours", flyte.Cron("30 9 * * 1-5", timezone="America/New_York"))` | ```python @env.task( triggers=flyte.Trigger( "daily_report", flyte.Cron("0 6 * * *"), inputs={"trigger_time": flyte.TriggerTime}, ) ) def generate_report(trigger_time: datetime) -> str: ... ``` Multiple triggers per task and parameterized trigger inputs are supported; see the [Triggers docs](../../triggers/_index). --- ## 4. PythonOperator to `@env.task` Airflow's `PythonOperator` runs a Python callable in the worker's environment. The callable's return value becomes XCom, and inputs arrive through three channels: `op_args`/`op_kwargs` passed at operator construction, the Airflow context injected as `**kwargs` (`ti`, `ds`, `dag_run`, `logical_date`, โ€ฆ), and `ti.xcom_pull(...)` for data from upstream tasks. Flyte's equivalent is `@env.task` on a plain function. The function's parameters and return type are the interface; there is no separate context channel and no XCom step. ```python # Airflow def fetch_events(**context): ds = context["ds"] return _fetch(ds) # returned value is serialized to XCom def summarize(**context): ti = context["ti"] records = ti.xcom_pull(task_ids="fetch_events") return f"{len(records)} events on {context['ds']}" with DAG("events", schedule="@daily", ...) as dag: t1 = PythonOperator(task_id="fetch_events", python_callable=fetch_events) t2 = PythonOperator(task_id="summarize", python_callable=summarize) t1 >> t2 ``` ```python # Flyte env = flyte.TaskEnvironment(name="events", image=...) @env.task async def fetch_events(ds: str) -> list[dict]: return _fetch(ds) @env.task async def summarize(ds: str, records: list[dict]) -> str: return f"{len(records)} events on {ds}" @env.task async def driver(ds: str) -> str: records = await fetch_events(ds) return await summarize(ds, records) ``` A few things change in the move: - **Inputs are the function parameters.** No `**context`. If the task needs the run's date, declare it as a parameter (`ds: str`) and the driver passes it in. The driver itself can receive trigger time when a [Trigger](../../triggers/_index) fires it. - **Data flows through `await`, not XCom.** The value returned by `fetch_events` is the value `summarize` receives: the function call graph IS the dependency graph. No `xcom_pull` and no `t1 >> t2` to maintain separately from the data flow. - **Types are part of the signature.** Flyte uses the hints to serialize between tasks, but keep expectations calibrated: the runtime is more like typed JSON than a fully enforced contract. It is useful as documentation and for tooling, not as a strict static check. - **Async-native, sync-also-works.** Tasks are typically `async def` and invoked with `await`. Plain `def` tasks are fully supported if you'd rather stay in a sync codebase; you just give up some of the flexibility async offers. The driver above has nothing in it but task calls, for readability. It doesn't have to. A driver is just a `@env.task`, and any code that belongs in a Python function belongs in a driver: plain expressions, loops, `if`/`try`, helpers. Turn something into a `@env.task` when you want it to have its own resources, image, retries, caching, or parallelism. Otherwise leave it as regular Python and call it inline. Docs: **Get started > Core concepts > Tasks** ### File and Dir: for data that doesn't fit in a return value Primitive and JSON-serializable values (`int`, `str`, `list`, `dict`, dataclasses, Pydantic models) flow directly as return values: the SDK serializes them. Same shape as XCom, but typed. Most tasks will use these and nothing else. Flyte adds `File` and `Dir` for the cases where the payload is too big or too binary to inline. In Airflow this is where pipelines step outside the framework: XCom is a Postgres row with a soft ~48KB limit, so larger payloads are written to a shared filesystem or object storage and a path is passed as a string; the upload, the lifecycle, and the cleanup are the author's responsibility, outside Airflow's model. Flyte covers both cases with the same interface. A task that returns `File` or `Dir` is declaring that its output is an offloaded blob, and the SDK handles the upload on write and the download on read. ```python import flyte from flyte.io import File, Dir @env.task async def extract(ds: str) -> File: # Stream straight to remote storage โ€” no local temp needed. file = File.new_remote() async with file.open("wb") as f: await f.write(b"col1,col2\nfoo,bar\n") return file @env.task async def count_rows(csv: File) -> int: async with csv.open("rb") as f: data = await f.read() return data.count(b"\n") - 1 ``` The `File` object travels between tasks the same way an `int` does: as a typed argument. Underneath, it carries a remote path. Common methods: - `File.new_remote()`: new reference in the run's scratch area, for streaming writes. - `File.from_local(path)` / `from_local_sync(path)`: upload a local file, get a `File` back. - `File.from_existing_remote(uri)`: wrap an existing remote URI (for example, a path produced by an upstream system). - `async with file.open("rb")` / `async with file.open("wb")` / `with file.open_sync(...)`: stream read/write. - `await file.download()` / `file.download_sync()`: materialize to a local path and return it. `Dir` has the same surface for directories, plus `walk()` and `list_files()` to iterate entries. Docs: **Tasks > Build tasks > Files and directories** --- ## 5. TaskFlow to `@env.task` If the DAG you're porting uses Airflow's TaskFlow API (`@task`, `@dag`), the surface move is small: `@task` becomes `@env.task`, the function's return value is the data (no `ti.xcom_pull`), and function calls ARE the dependencies (no `>>`). A lot of TaskFlow code compiles to Flyte with little more than a find-and-replace on the decorator. ```python # Airflow TaskFlow from airflow.decorators import dag, task @dag(schedule="@daily", start_date=datetime(2026, 1, 1), catchup=False) def events(): @task def fetch_events() -> list[dict]: return _fetch() @task def summarize(records: list[dict]) -> str: return f"{len(records)} events" summarize(fetch_events()) events() ``` ```python # Flyte env = flyte.TaskEnvironment(name="events", image=...) @env.task async def fetch_events() -> list[dict]: return _fetch() @env.task async def summarize(records: list[dict]) -> str: return f"{len(records)} events" @env.task(triggers=flyte.Trigger.daily()) async def driver() -> str: return await summarize(await fetch_events()) ``` The thing worth internalizing, and the main place this stops being a find-and-replace, is what the outer function is doing. An Airflow `@dag` function runs at **parse time**. Calling `fetch_events()` inside it doesn't run `fetch_events`; it registers a task and an edge in the static graph. The scheduler later traverses that graph. By the time the tasks actually execute, the `@dag` function is long gone. A Flyte driver is a `@env.task` that runs at **execution time**. There is no parse-time graph-building step. Calling `await fetch_events()` actually calls `fetch_events`. That means the driver (and any task) is just Python: `if`/`else`, `try`/`except`, loops, recursion, calling other tasks from inside other tasks, nested drivers, reading a value from one task and deciding what to do next. All of it works because there is no static graph to fit into. To make the point concrete, a task can call itself: ```python @env.task async def countdown(n: int) -> int: if n == 0: return 0 return 1 + await countdown(n - 1) ``` Each `await countdown(...)` call is a real task invocation; the graph grows as the computation runs. This is impossible to express in Airflow's `@dag` model, where the graph has to be known before execution. The practical effect: patterns that Airflow encodes with its own primitives (`BranchPythonOperator`, `ShortCircuitOperator`, `trigger_rule`, `.expand()` for dynamic mapping, custom `XComArg` gymnastics) are just Python constructs in Flyte. Branching is `if`. Short-circuit is `return`. Dynamic mapping is `asyncio.gather` or `flyte.map`. Error handling is `try`/`except`/`finally`. Section 8 covers these with runnable examples. ### TaskFlow decorator variants TaskFlow ships several decorators beyond `@task`. Rough mapping: | TaskFlow | Flyte equivalent | |---|---| | `@task` | `@env.task` | | `@task.bash` | **Migration > From Airflow to Flyte > Part 1: vanilla operators > 6. BashOperator to ContainerTask** | | `@task.virtualenv` | `@env.task` on a `TaskEnvironment` with its own image | | `@task.docker` | `@env.task` on a `TaskEnvironment` with `image=...` | | `@task.kubernetes` | **Migration > From Airflow to Flyte > Part 1: vanilla operators > 7. KubernetesPodOperator to TaskEnvironment + PodTemplate** | | `@task.branch` | plain `if` in the driver | | `@task.short_circuit` | plain `return` in the driver | --- ## 6. BashOperator to ContainerTask Airflow's `BashOperator` runs a shell command in the Airflow worker's image, with inputs rendered into the command via Jinja templating and output captured as the last line of stdout. ```python BashOperator( task_id="extract", bash_command="gsutil cp gs://bucket/data-{{ ds }}.csv /tmp/data.csv " "&& wc -l /tmp/data.csv | awk '{print $1}'", do_xcom_push=True, ) ``` Flyte's equivalent is a `ContainerTask`: specify an image, a command, typed inputs, and typed outputs. Inputs are substituted via `{{.inputs.}}`; outputs are files the container writes to `output_data_dir`, which Flyte reads back with the declared types. ```python import flyte from flyte.extras import ContainerTask extract = ContainerTask( name="extract", image=flyte.Image.from_base("google/cloud-sdk:slim"), inputs={"date": str}, outputs={"row_count": int}, input_data_dir="/var/inputs", output_data_dir="/var/outputs", command=[ "/bin/sh", "-c", "gsutil cp gs://bucket/data-{{.inputs.date}}.csv /tmp/data.csv && " "wc -l /tmp/data.csv | awk '{print $1}' > /var/outputs/row_count", ], ) ``` A `ContainerTask` is invoked the same way as any other task, by calling it from a driver with `await`: ```python container_env = flyte.TaskEnvironment.from_task("extract_env", extract) env = flyte.TaskEnvironment( name="pipeline", image=flyte.Image.from_debian_base().with_uv_project(pyproject_file="pyproject.toml"), depends_on=[container_env], ) @env.task async def driver(date: str) -> int: return await extract(date=date) ``` Two things about the invocation: - `TaskEnvironment.from_task(...)` wraps the container task in an environment so it can be registered alongside the driver. - The driver's env `depends_on=[container_env]` so Flyte registers both together. The driver's own image needs Flyte installed. `flyte.Image.from_debian_base()` installs it by default, and `flyte.Image.with_uv_project()` layers your project's dependencies on top. The container task's image does *not* need Flyte; it just needs the tools its command invokes. ### When to use `ContainerTask` `ContainerTask` is the right choice when the container shouldn't or can't have Flyte installed, for example: - The tool is not Python (a Go/C CLI, a bioinformatics binary, an ML framework container) - You want to reuse an existing production image without modifying it - You want to stay out of Python entirely for the task body If you already have Python in the loop and just need to shell out for one step, a regular `@env.task` with `subprocess` is simpler: ```python @env.task async def extract(date: str) -> int: import subprocess subprocess.run(["gsutil", "cp", f"gs://bucket/data-{date}.csv", "/tmp/data.csv"], check=True) out = subprocess.check_output(["wc", "-l", "/tmp/data.csv"]) return int(out.split()[0]) ``` ### How the arguments map | BashOperator | ContainerTask | |---|---| | `bash_command` (string) | `command=[...]` (list; you choose the shell) | | (implicit worker image) | `image=` (explicit, per task) | | `env` / `append_env` | `flyte.Image.from_...().with_env_vars(...)` or the `TaskEnvironment` | | `{{ ds }}`, `{{ ti.xcom_pull(...) }}` | `{{.inputs.}}` | | `do_xcom_push=True` (last stdout line) | `outputs={...}`, written to files in `output_data_dir` | | `cwd` | `cd ... && ...` inside the command | Docs: **Tasks > Build tasks > Run a bioinformatics tool** --- ## 7. KubernetesPodOperator to TaskEnvironment + PodTemplate `KubernetesPodOperator` (KPO) gives you the full pod spec: image, commands, env, secrets, resources, volumes, node selectors, tolerations, service accounts, affinity, plus XCom via a sidecar writing to `/airflow/xcom/return.json`. In Flyte, the same knobs live in three places: 1. **`TaskEnvironment(...)`**: the common knobs. Image, resources, env vars, secrets, interruptible/spot, and an option to add a `pod_template` for every task in the env. 2. **`@env.task(...)`**: per-task overrides on top of the env: retries, timeout, cache, triggers, and a task-level `pod_template` if this one task needs to differ. 3. **`flyte.PodTemplate(...)`**: raw Kubernetes escape hatch. Wraps `kubernetes.client.V1PodSpec`, so anything in the pod spec (volumes, node selectors, tolerations, affinity, service accounts, sidecars, init containers, image pull secrets, security contexts, lifecycle hooks) is available. XCom has no equivalent; the task's typed return value is the output, and large payloads use `File`/`Dir` (Section 4). The sidecar-writing-to-`/airflow/xcom/return.json` contract doesn't exist. ### Where every KPO knob lands | KPO argument | Flyte location | |---|---| | `image` | `TaskEnvironment(image=...)` | | `cmds`, `arguments` | function body of `@env.task` | | `env_vars` (dict) | `TaskEnvironment(env_vars={...})` | | `secrets=[Secret(...)]` | `TaskEnvironment(secrets=[flyte.Secret(...)])` | | `container_resources` (requests/limits) | `TaskEnvironment(resources=flyte.Resources(cpu=(1,4), memory="2Gi", gpu="T4:1"))` | | `node_selector`, `tolerations`, `affinity` | `flyte.PodTemplate(pod_spec=V1PodSpec(node_selector=..., tolerations=..., affinity=...))` | | `service_account_name` | `PodTemplate(pod_spec=V1PodSpec(service_account_name=...))` | | `volumes`, `volume_mounts` | `PodTemplate(pod_spec=V1PodSpec(volumes=[...], containers=[V1Container(volume_mounts=[...])]))` | | `image_pull_secrets` | `PodTemplate(pod_spec=V1PodSpec(image_pull_secrets=[V1LocalObjectReference(name=...)]))` | | `security_context` | `PodTemplate(pod_spec=V1PodSpec(security_context=...))` | | `labels`, `annotations` | `PodTemplate(labels={...}, annotations={...})` | | `init_containers`, sidecars | `PodTemplate(pod_spec=V1PodSpec(init_containers=[...], containers=[primary, ...]))` | | `retries`, `retry_delay` | `@env.task(retries=...)` | | `execution_timeout` | `@env.task(timeout=timedelta(...))` | | `do_xcom_push` + sidecar contract | function return type: primitives/dataclasses inline, large payloads via `File`/`Dir` | | `on_finish_action` / pod cleanup | handled by Flyte: pods are cleaned up per run lifecycle | ### What a fully-specified task looks like ```python from datetime import timedelta from kubernetes.client import V1Container, V1PodSpec import flyte pod_template = flyte.PodTemplate( primary_container_name="primary", labels={"team": "etl"}, pod_spec=V1PodSpec( service_account_name="etl-runner", init_containers=[ V1Container( name="warm-cache", image="busybox:1.36", command=["sh", "-c", "echo warming cache && sleep 1"], ), ], ), ) etl_env = flyte.TaskEnvironment( name="etl", image="registry.example.com/etl:2026.04.01", resources=flyte.Resources(cpu=(1, 4), memory="2Gi", gpu="T4:1"), env_vars={"LOG_LEVEL": "INFO"}, secrets=[flyte.Secret(key="db-password", as_env_var="DB_PASSWORD")], pod_template=pod_template, interruptible=True, ) @etl_env.task(retries=3, timeout=timedelta(minutes=30)) async def load_warehouse(ds: str) -> int: ... ``` You don't have to list the primary container in the pod_spec; Flyte fills it in from the env's image, the function's command, and the env's resources. Add a `V1Container(name="primary", ...)` entry only when you need to put fields on it directly (volume mounts, extra env, security context). Docs: **Get started > Core concepts > TaskEnvironment** ยท **Tasks > Configure tasks > Secrets** ยท **Tasks > Configure tasks > Pod templates** --- ## 8. Orchestration: parallelism, conditionals, error handling Airflow encodes orchestration in first-class primitives: `[t1, t2, t3] >> merge` for fan-out, `.expand()` for dynamic mapping, `BranchPythonOperator` / `@task.branch` for branching, `ShortCircuitOperator` for early exit, `trigger_rule` for post-branch merges, and `on_failure_callback` / `trigger_rule=ALL_DONE` for failure paths. In Flyte these are plain Python inside a driver task, because the driver runs at execution time. There is no static graph to encode into. ### Parallelism Static fan-out in Airflow: ```python fetch >> [summarize_us, summarize_eu, summarize_apac] >> merge ``` Flyte, concurrent awaits with `asyncio.gather`: ```python @env.task async def driver(ds: str) -> Summary: raw = await fetch(ds) us, eu, apac = await asyncio.gather( summarize(raw, "us"), summarize(raw, "eu"), summarize(raw, "apac"), ) return await merge(us, eu, apac) ``` Each `summarize(...)` returns a coroutine; `asyncio.gather` runs them concurrently and awaits all of them. Tasks called concurrently run in their own pods; the concurrency is real, not just asyncio on one worker. ### Dynamic mapping Airflow uses `.expand()` to fan out over values known only at runtime: ```python process.partial(batch_size=100).expand(shard_id=list_shards()) ``` Flyte, regular comprehension over the runtime list: ```python shards = await list_shards() results = await asyncio.gather(*(process(shard) for shard in shards)) ``` To bound concurrency (for example, when the downstream is rate-limited), wrap the call in an `asyncio.Semaphore`: ```python sem = asyncio.Semaphore(20) async def process_one(shard): async with sem: return await process(shard) results = await asyncio.gather( *(process_one(s) for s in shards), return_exceptions=True, ) ``` `return_exceptions=True` collects per-item failures instead of failing the batch. The semaphore is also the pattern when different tasks in the same fan-out need different concurrency limits. If your codebase is sync, `list(flyte.map(process, shards, concurrency=20))` is the sync equivalent of the pattern above. Docs: **Tasks > Build tasks > Controlling parallel execution** ยท **Tasks > Build tasks > Fanout** ### Conditionals Airflow: `BranchPythonOperator` (or `@task.branch`) returns the task_id(s) to run next; `ShortCircuitOperator` skips the rest of the branch; a `trigger_rule=NONE_FAILED_MIN_ONE_SUCCESS` on the merge task reconciles skipped upstreams. Flyte: ```python @env.task async def driver(ds: str) -> Summary: size = await inspect(ds) if size == 0: return Summary(status="empty") if size < 1_000_000: return await fast_path(ds) return await slow_path(ds) ``` Plain `if` / `elif` / `else`, plain `return`. There is no `trigger_rule` to set because there are no skipped tasks to reconcile; the code below the branch simply doesn't run. ### Error handling Per-task retries and timeouts live on the `@env.task` decorator: ```python @env.task(retries=3, timeout=timedelta(minutes=15)) async def flaky(ds: str) -> int: ... ``` Orchestration-level error handling (Airflow's `trigger_rule=ALL_DONE` cleanup and `on_failure_callback` alerts) is `try` / `except` / `finally` in the driver: ```python @env.task async def driver(ds: str) -> Summary: try: result = await heavy_step(ds) return await publish(result) except Exception as e: await alert(f"{ds} failed: {e}") raise finally: await cleanup(ds) ``` `finally` runs on both success and failure. `except` catches task failures at the `await` site after the task's own retries are exhausted. Specific failure modes live in `flyte.errors` (`OOMError`, `TaskTimeoutError`, `RetriesExhaustedError`, `ActionAbortedError`) and can be caught by type. A common pattern is retrying an OOM with larger resources via `.override(...)`: ```python import flyte.errors env = flyte.TaskEnvironment( name="transforms", image=..., resources=flyte.Resources(cpu=1, memory="250Mi"), ) @env.task async def transform(ds: str) -> int: ... @env.task async def driver(ds: str) -> int: try: return await transform(ds) except flyte.errors.OOMError: return await transform.override( resources=flyte.Resources(cpu=1, memory="2Gi"), )(ds) ``` Docs: **Tasks > Configure tasks > Retries and timeouts** ยท **Tasks > Build tasks > Error handling** --- ## What's next Once the port is in place, a few Flyte features don't have direct Airflow counterparts and are worth knowing about. ### Caching A task can be marked cacheable; subsequent calls with the same inputs short-circuit to the previous output instead of re-running. The cache key is derived from inputs and a task version, so bumping the version invalidates. ```python @env.task(cache="auto") async def expensive(ds: str) -> Result: ... ``` Airflow has no equivalent; XCom stores outputs but doesn't short-circuit on re-execution. Docs: **Tasks > Configure tasks > Caching** ### Reusable containers By default each task call gets a fresh pod. A reuse policy keeps the container warm across calls so follow-up invocations skip pod startup and image pull. ```python warm_env = flyte.TaskEnvironment( name="warm", image=..., reusable=flyte.ReusePolicy(replicas=(1, 3), concurrency=2), ) ``` Useful when a fan-out issues many short tasks against a heavy image. Docs: **Tasks > Configure tasks > Reusable containers** ### Reports A task can emit an HTML report (tables, plots, logs) attached to the run and viewable in the UI. Written from inside the task with `flyte.report`. ```python @env.task(report=True) async def summarize(ds: str) -> Summary: tab = flyte.report.get_tab("main") tab.log(f"

{ds}

") tab.log(dataframe.to_html()) await flyte.report.flush.aio() ... ``` Docs: **Tasks > Build tasks > Reports** ### Apps A long-running HTTP server (FastAPI, Panel, Streamlit, a webhook endpoint) can be deployed alongside your tasks. The app has a URL and can call tasks via the Flyte API. This is the path for webhook-triggered runs, a UI on top of a pipeline, or a custom inference endpoint. Docs: [Serve and deploy apps](../../apps/serve-and-deploy-apps/_index) ยท [Build apps](../../apps/build-apps/_index) === PAGE: https://www.union.ai/docs/v2/union/user-guide/migration/from-slurm === Mapping from Slurm concepts (sbatch scripts, modules, job arrays, dependencies, partitions, requeue, multi-node jobs) to their Flyte 2 equivalents. # From Slurm to Flyte A guide to moving batch and ML workloads off a Slurm cluster onto Flyte 2. The compute code mostly survives the move. The training loop, the preprocessing script, and the eval harness come over unchanged. What changes is everything around them: where the environment comes from, how a job gets its inputs, how one job triggers the next, and how you ask for capacity. Three shifts account for most of the work: - **`module load` and conda environments become container images.** You declare the environment once, in Python, instead of relying on what happens to be installed on the login node. - **The shared filesystem becomes explicit inputs and outputs.** A script that assumes `/scratch` exists on every node needs to take its data as arguments instead. - **`sbatch` chains become function calls.** Dependency flags, sentinel files, and the cron entries that glue them together become ordinary Python. The rest of this guide maps Slurm constructs onto their Flyte equivalents. > [!NOTE] > The **Flyte agent plugins > Skills > Migration (Slurm โ†’ Flyte 2)** > automates the mechanical part of this translation: `#SBATCH` directives become task environment > configuration, job arrays become `flyte.map` or `asyncio.gather`, and dependency chains become > plain Python. Treat its output as a first pass to review against this guide, not a finished port. --- ## The mapping at a glance | Slurm | Flyte | |---|---| | `sbatch train.sh` | `flyte run train.py main` | | `#SBATCH --gres=gpu:a100:8` | `flyte.Resources(gpu="A100:8")` | | `#SBATCH --cpus-per-task=16 --mem=64G` | `flyte.Resources(cpu=16, memory="64Gi")` | | `#SBATCH --time=04:00:00` | `@env.task(timeout=timedelta(hours=4))` | | `#SBATCH --requeue` | `@env.task(retries=3)` | | `#SBATCH --array=0-999` | `flyte.map(step, range(1000))` | | `#SBATCH --nodes=4 --ntasks-per-node=8` | `ClusteredTaskEnvironment(replicas=4, nproc_per_node=8)` | | `#SBATCH --dependency=afterok:$JOBID` | `await` the upstream task | | `#SBATCH --begin=...`, cron on the login node | `@env.task(triggers=flyte.Trigger(...))` | | `module load cuda && source venv/bin/activate` | `flyte.Image.from_debian_base().with_pip_packages(...)` | | `$SLURM_PROCID`, `$SLURM_NNODES` | `flyte.ctx().rank`, `flyte.ctx().nnodes` | | `squeue`, `sacct` | `flyte get run`, `flyte get logs`, the UI | | `/scratch/$USER/data.parquet` | `flyte.io.File` passed between tasks | --- ## The job script becomes a task A representative Slurm job: ```bash #!/bin/bash #SBATCH --job-name=train #SBATCH --partition=gpu #SBATCH --gres=gpu:a100:8 #SBATCH --cpus-per-task=16 #SBATCH --mem=64G #SBATCH --time=04:00:00 #SBATCH --requeue module load cuda/12.1 source ~/venvs/train/bin/activate srun python train.py --lr 3e-4 ``` The same job in Flyte: ```python from datetime import timedelta import flyte env = flyte.TaskEnvironment( name="training", image=flyte.Image.from_debian_base(python_version=(3, 12)).with_pip_packages("torch"), resources=flyte.Resources(cpu=16, memory="64Gi", gpu="A100:8"), ) @env.task(retries=3, timeout=timedelta(hours=4)) async def train(lr: float = 3e-4) -> flyte.io.File: ... ``` The `#SBATCH` block splits in two. Anything that describes the *environment* (image, resources) belongs on the `flyte.TaskEnvironment`, which is shared by every task declared against it. Anything that describes *this job* (retries, timeout, caching) belongs on the `@env.task` decorator. All of these except the image can be overridden per invocation with `task.override(...)`, which has no Slurm equivalent: the same task can run with 1 GPU in one call and 8 in the next. The function signature also does more work than a job script's argv. `lr: float` and `-> flyte.io.File` are the task's interface, and Flyte records the value of every input and output of every run, so a checkpoint six months old can be traced back to the arguments that produced it. Docs: **Get started > Core concepts > TaskEnvironment** · **Tasks > Configure tasks > Resources** · **Tasks > Configure tasks > Overrides** --- ## `module load` becomes an image This is usually the slowest part of a Slurm migration, and the one worth doing carefully. On a Slurm cluster the environment is ambient: modules, a conda env on NFS, whatever the sysadmin installed. In Flyte the environment is part of the task definition. You do not need to write a Dockerfile. `flyte.Image` builds one for you from Python: ```python image = ( flyte.Image.from_debian_base(python_version=(3, 12)) .with_apt_packages("git") .with_pip_packages("torch", "transformers", "datasets") ) ``` If you already keep your dependencies in a `pyproject.toml`, point at it directly with `.with_uv_project("pyproject.toml")`. If your organization already publishes a blessed CUDA image, pass it by reference instead and skip the build entirely: ```python env = flyte.TaskEnvironment( name="training", image="registry.example.com/ml-platform/cuda-torch:2026.04.01", ) ``` Two practical notes for people coming from modules: - **Different tasks can use different images.** There is no single cluster-wide Python environment to keep everyone happy. A preprocessing task on a slim CPU image and a training task on a CUDA image are part of the same run. - **Images are content-hashed.** Rerunning with an unchanged spec reuses the previous build instead of rebuilding. Where that build runs depends on your deployment. Set `image.builder` to `remote` in your config file to build with Union's `ImageBuilder`, which runs the build on the cluster and needs no Docker and no registry credentials on your machine. Set it to `local` to build with Docker locally and push to a registry your cluster can pull from, or, with flyte 2.10.6 or later, to `local-podman` to do the same with Podman. Docs: **Tasks > Configure tasks > Container images** --- ## Job arrays become fan-out A Slurm job array indexes into work with `$SLURM_ARRAY_TASK_ID` and leaves collection of the results to you, usually as files in a shared directory plus a script that reads them back. ```bash #SBATCH --array=0-999%50 python process.py --shard $SLURM_ARRAY_TASK_ID ``` In Flyte the fan-out is a call, and the results come back as return values: ```python @env.task async def process(shard: int) -> int: ... @env.task async def main(n_shards: int = 1000) -> int: counts = flyte.map(process, range(n_shards), concurrency=50) return sum(c for c in counts if not isinstance(c, Exception)) ``` `concurrency=50` is the equivalent of the `%50` throttle: at most 50 shards run at once, and the rest wait. `flyte.map` yields results in input order and returns an exception object in place of a result for shards that failed, so a partial failure does not cost you the whole array. When the items are not uniform, or you want to fan out across different tasks, use `asyncio.gather` instead: ```python results = await asyncio.gather(*(process(s) for s in shards), return_exceptions=True) ``` Docs: **Tasks > Build tasks > Mapping over inputs** · **Tasks > Build tasks > Fanout** · **Tasks > Build tasks > Controlling parallel execution** --- ## Job dependencies become ordinary Python `--dependency=afterok:$JOBID` handles a linear chain. Anything past that (a fan-out that joins, a branch on the result of an earlier step, a retry of just one stage) tends to become a driver bash script, some sentinel files, and a wiki page describing the arrangement. In Flyte, a pipeline is a task that calls other tasks. There is no workflow DSL and no graph to compile: ```python @env.task async def main(ds: str) -> Report: raw = await ingest(ds) clean = await filter_rows(raw) shards = await asyncio.gather(*(tokenize(clean, i) for i in range(8))) model = await train(shards) return await evaluate(model) ``` Because the driver runs at execution time as normal Python, control flow is normal Python too. Branching is `if`. Early exit is `return`. Failure handling is `try`/`except`/`finally`, and specific failure modes are catchable by type: ```python import flyte.errors @env.task async def main(ds: str) -> int: try: return await transform(ds) except flyte.errors.OOMError: return await transform.override(resources=flyte.Resources(memory="64Gi"))(ds) ``` Scheduled submission moves from a cron entry on the login node to a trigger on the task itself: ```python @env.task(triggers=flyte.Trigger("nightly", flyte.Cron("0 2 * * *"))) async def nightly_eval() -> Report: ... ``` Docs: [Triggers](../triggers/_index) · **Tasks > Build tasks > Error handling** --- ## `--requeue` becomes retries, spot handling, and checkpoints `--requeue` restarts the script from the top and leaves the rest to you. Flyte splits the problem into pieces that can be configured separately. **Retries** are declarative, and count only against failures your code is responsible for: ```python @env.task(retries=3, timeout=timedelta(hours=4)) async def train(cfg: TrainConfig) -> flyte.io.File: ... ``` **Spot capacity** is a flag. `interruptible=True` schedules the task on spot or preemptible instances. Preemptions are recorded as system failures rather than task failures, so they do not consume the retry budget. **Checkpoints** make the retry cheap. `flyte.ctx().checkpoint` writes to object storage rather than a shared filesystem, so the next attempt resumes on whatever node it lands on: ```python @env.task(retries=5) async def train(steps: int) -> flyte.io.File: ckpt = flyte.ctx().checkpoint start = 0 if (prev := await ckpt.load()) is not None: start = load_state(prev) for step in range(start, steps): ... if step % 100 == 0: await ckpt.save(state_path) ``` Task-level **Tasks > Configure tasks > Caching** covers the other half of the problem. A cached task with unchanged inputs is skipped on re-execution, so rerunning a twelve-hour pipeline after fixing step nine starts at step nine instead of step one. Docs: **Tasks > Configure tasks > Retries and timeouts** · **Tasks > Configure tasks > Interruptible tasks** · **Tasks > Build tasks > Intra-task checkpoints** --- ## Multi-node jobs become clustered tasks `--nodes=4 --ntasks-per-node=8` maps onto a `ClusteredTaskEnvironment`, which launches all replicas together as a single Kubernetes JobSet. With the default `TorchRun` runtime, `torchrun` handles rendezvous: ```python import flyte from flyte.clustered import ClusteredTaskEnvironment, ClusterFailurePolicy, TorchRun env = ClusteredTaskEnvironment( name="pretrain", image=image, resources=flyte.Resources(cpu=16, memory="64Gi", gpu="H100:8", shm="auto"), replicas=4, # nodes nproc_per_node=8, # processes per node, so world size is 32 runtime=TorchRun(rdzv_backend="c10d"), failure_policy=ClusterFailurePolicy(max_restarts=2, restart_on_host_maintenance=True), ) @env.task async def pretrain(steps: int) -> flyte.io.File: import torch.distributed as dist dist.init_process_group(backend="nccl") ... ``` Training code that already runs under `srun` with torchrun needs no changes: `RANK`, `WORLD_SIZE`, `MASTER_ADDR`, and `MASTER_PORT` are populated in each worker as usual. The same values are available from `flyte.ctx()` (`rank`, `local_rank`, `node_rank`, `nnodes`, `world_size`, `master_addr`) if you would rather read them from Python. Only rank 0 uploads the task's outputs. `ClusterFailurePolicy` distinguishes between two things Slurm treats alike. `restart_on_host_maintenance=True` restarts the job when the underlying node is preempted or drained for maintenance, without spending the `max_restarts` budget you set aside for actual crashes. > [!NOTE] > Clustered tasks support `torchrun` (`TorchRun`) and JAX (`JaxRun`) workloads. There is no MPI > launcher, so `mpirun`-based applications stay on Slurm. For Ray, Spark, or Dask, use the > corresponding integration, which brings up a per-task cluster and tears it down when the task > finishes. Docs: [Clustered task environments](../../api-reference/flyte-sdk/flyte.clustered/_index) --- ## Partitions and QOS become queues A queue is a named scheduling lane bound to a cluster pool, which is the closest analogue to a Slurm partition with a QOS attached. Targeting one is a single parameter, settable on the environment, the task, the invocation, or a trigger: ```python @env.task(queue="research-h100") async def evaluate(model: flyte.io.File) -> EvalReport: ... await train.override(queue="prod-high")(cfg) ``` | Slurm | Flyte | |---|---| | `--partition=gpu` | `queue="gpu"`, bound by an admin to a cluster pool | | `--qos=high` | queue priority | | `MaxJobsPerAccount` | run concurrency on the queue | | `MaxSubmitJobs` | queue depth, which rejects past the limit rather than queueing forever | | `squeue -p gpu` | `flyte get queue gpu --watch` | Two differences from Slurm's accounting model will affect how you plan capacity. Queue priority controls *ordering*, not preemption: queue priority alone never evicts a running low-priority task when higher-priority work arrives. And when a queue hits its depth limit, new submissions are rejected immediately with `RESOURCE_EXHAUSTED` instead of sitting in `PENDING` for an unknown length of time. That rejection is a back-pressure signal for the submitting process to slow down. Docs: **Tasks > Configure tasks > Queues** · **Clusters and queues > Managing queues** --- ## The shared filesystem becomes explicit data This mapping has no one-line translation. Doing it properly is what buys you lineage, caching, and reproducible reruns; working around it costs you all three. On Slurm, your home directory and `/scratch` are visible from the login node and every compute node, so a job reads and writes paths and the filesystem does the rest. There is no equivalent guarantee in Flyte. Data moves because a task takes it as an argument or returns it. For most cases, the change is mechanical. Values that fit in a return type (numbers, strings, dataclasses, Pydantic models) travel as return values. Anything larger travels as `flyte.io.File` or `flyte.io.Dir`, which are typed references to object storage: ```python from flyte.io import Dir, File @env.task async def tokenize(raw: Dir) -> File: out = File.new_remote() async with out.open("wb") as f: ... return out @env.task async def train(tokens: File) -> File: local = await tokens.download() ... ``` A `File` passes between tasks the way an `int` does. The upload on write and the download on read are handled for you, and the object supports streaming, so reading a range out of a 500 GB file does not require pulling the whole thing to local disk first. Workloads that genuinely need a filesystem view have an escape hatch. If you already run a parallel filesystem such as FSx for Lustre or a shared NFS export, mount it into tasks with a **Tasks > Configure tasks > Pod templates**. Pod templates give you the full Kubernetes pod spec: volumes, node selectors, tolerations, service accounts, and sidecars. [Volumes](../tasks/task-programming/volumes/_index) are the other option, a durable, versioned filesystem backed by object storage that tasks mount and read like a local directory, with copy-on-write forks for parallel branches of work. Docs: **Tasks > Build tasks > Files and directories** · **Tasks > Configure tasks > Pod templates** --- ## Watching and debugging jobs `squeue` and `sacct` map onto the CLI and the UI: ```bash flyte get run # recent runs and their phases flyte get action # actions within a run flyte get logs # streaming logs ``` Runs are also visible in the UI with per-task logs, GPU and memory utilization, and inputs and outputs for every action. `srun --pty bash` and `ssh node042` both have direct equivalents. You can **Tasks > Run and deploy tasks > Debug a run > SSH into the task (Beta)**, currently in beta, which is the closest match to an interactive Slurm session. A run launched with `--debug` (or `debug=True` from the SDK) goes further and starts a browser-based VS Code session inside the task pod, where you can set breakpoints and step through the code on the same hardware, against the same data and dependencies the run uses. Any running action can also be opened from the UI with one click. What differs is where you land. An interactive session on a Slurm node puts you on a shared machine whose environment may not match the job; here you land inside the failing task's own container, with the image and paths that task actually ran with. Docs: **Tasks > Run and deploy tasks > Debug a run** · **Tasks > Run and deploy tasks > View logs** --- ## Cold start and warm pools A Slurm allocation feels instant because the nodes are already yours and already running. In Flyte, each task call gets a fresh pod by default, which means scheduling, an image pull, and interpreter startup before your code runs. On a task that runs for hours, that overhead is noise. On a fan-out of hundreds of short tasks against a heavy image, it dominates. A reuse policy keeps a pool of warm containers alive across invocations: ```python env = flyte.TaskEnvironment( name="rollouts", image=flyte.Image.from_debian_base().with_pip_packages("unionai-reuse", "vllm"), resources=flyte.Resources(gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(2, 10), concurrency=4, idle_ttl=300), ) ``` The pool autoscales between the given bounds and shuts down after `idle_ttl` seconds of inactivity. Because each replica is a long-lived Python process, a model loaded once serves many subsequent invocations, and scheduling a task onto a warm replica costs milliseconds rather than a pod startup. The trade-off is the same one you would accept in any long-running server: in-memory state survives between invocations on a replica, so global state deserves care. Docs: **Tasks > Configure tasks > Reusable containers** --- ## Staging the migration Migrations tend to go badly when the first workload moved is the most expensive one. A sequence that works: 1. **Start with pipeline-shaped work.** Data processing, evaluation, hyperparameter sweeps, batch inference. These gain the most from typed inputs and outputs, caching, and retries, and they are the workloads where the `sbatch` glue was worst. Nothing expensive is at risk while you settle the image and data-access questions. 2. **Move single-node training next.** By this point the image is validated and the data is coming in as arguments, so what you pick up is reproducible environments, spot with automatic fallback, checkpoint recovery, and run metadata. 3. **Move multi-node training last.** It is the most performance-sensitive workload in the stack, and by the time you get to it, everything underneath it has already been exercised. Existing binaries do not have to be rewritten to come along. A **Tasks > Build tasks > Run a bioinformatics tool** runs an arbitrary image with typed inputs and outputs, whatever language the tool is written in, which covers the bioinformatics binaries and vendor CLIs that tend to be wrapped in `srun` today. For the inner loop, `flyte run --local` executes the same code in your local Python process with no cluster involved, which is the closest thing to iterating on the login node before submitting. Docs: **Get started > Run modes > Run locally in Python** · **Tasks > Build tasks > Run a bioinformatics tool** --- ## Gang admission, preemption, and topology Three things Slurm's scheduler does have no equivalent in Flyte itself. If your workload depends on them, plan around them explicitly: - **Gang admission.** A clustered task's replicas are launched together and training waits for the full group before it starts (through `torchrun` rendezvous with the default `TorchRun` runtime, or `flyte.clustered.jax_initialize` with `JaxRun`), but Flyte does no all-or-nothing admission of its own. - **Preemption.** Flyte does not evict running low-priority work to make room for high-priority work the way a Slurm QOS can. If Kueue on your cluster preempts a running clustered task, the attempt ends and uses one of the task's `retries`, unless you set `resume_after_preemption` (Flyte backend v2.0.54 or later). See **Model training > Durable training > Restart a multi-node job**. - **Topology-aware placement.** Flyte has no setting to request workers on the same rack or switch. Docs: **Model training > Pre-training > Schedule all nodes together** · **Model training > Durable training > Restart a multi-node job** === PAGE: https://www.union.ai/docs/v2/union/tutorials === Worked, runnable examples organized by industry vertical and by technical topic. # Tutorials This section contains tutorials that showcase relevant use cases and provide step-by-step instructions on how to implement various features using Flyte and Union. Tutorials are organized by **industry vertical** and by **technical topic**. ## Industry verticals ### **Biotech & healthcare** Bioinformatics, medical imaging, and other life-sciences workloads. ### **Geospatial** Satellite imagery, remote sensing, and earth and atmospheric modeling workloads. ### **Financial services & fintech** Financial research, trading, and other fintech workloads. ### **Frontier AI** The everyday workloads of frontier AI labs: pretraining, data curation for text and video, evals on every checkpoint, interpretability, and AI-driven science. ## Technical topics ### **Computer vision** Image and vision-language model workloads. ### **Agents** Agentic workflows and autonomous LLM-powered systems. ### **Context engineering** Prompt engineering, prompt optimization, and context construction. ### **Model training** Training, fine-tuning, and hyperparameter optimization of models at scale. ### **Data validation** Benchmarks that measure the cost of validating training data with pandera, and the cost of not validating it. ### **Speculative decoding models** Train, benchmark, serve, and continually retrain draft models that make an LLM generate faster without changing its outputs. ### **Reinforcement learning** Reinforcement learning for LLMs, agents, robots, and games: GRPO, durable agentic RL, humanoid locomotion, model-written rewards, and self-play. ### **Data processing** Large-scale data processing and batching strategies. ### **Inference** Serving models and building inference applications as Flyte apps. ## Subpages - **Biotech & healthcare** - Bioinformatics, medical imaging, and other life-sciences workloads. - **Geospatial** - Satellite imagery, remote sensing, and earth and atmospheric modeling workloads. - **Financial services & fintech** - Financial research, trading, and other fintech workloads. - **Frontier AI** - The everyday workloads of frontier AI labs: pretraining, data curation for text and video, evals on every checkpoint, interpretability, and AI-driven science. - **Computer vision** - Image and vision-language model workloads. - **Agents** - Agentic workflows and autonomous LLM-powered systems. - **Context engineering** - Prompt engineering, prompt optimization, and context construction. - **Model training** - Training, fine-tuning, and hyperparameter optimization of models at scale. - **Data processing** - Large-scale data processing and batching strategies. - **Speculative decoding models** - Train, benchmark, serve, and continually retrain draft models that make an LLM generate faster without changing its outputs. - **Reinforcement learning** - Reinforcement learning for LLMs, agents, robots, and games: GRPO, durable agentic RL, humanoid locomotion, model-written rewards, and self-play. - **Inference** - Serving models and building inference applications as Flyte apps. - **Data validation** - Benchmarks that measure the cost of validating training data with pandera, and the cost of not validating it. === PAGE: https://www.union.ai/docs/v2/union/tutorials/biotech-healthcare === Bioinformatics, medical imaging, and other life-sciences workloads. # Biotech & healthcare Tutorials for bioinformatics, medical imaging, and other life-sciences workloads. ### **Biotech & healthcare > Genomic alignment** Align sequencing reads to a reference genome with a cached, parallel Bowtie 2 pipeline. ### **Biotech & healthcare > Cross-species gene comparison** Compare homologous genes across species with Carbon scoring, sequence alignment, and ESMFold 3D structures. ### **Biotech & healthcare > Genomic variant effect prediction** Zero-shot pathogenicity scoring with HuggingFace Carbon and interactive VEP reports. ### **Biotech & healthcare > Brain tumor MRI classification** Classify brain MRI scans with a two-phase EfficientNet-B4 pipeline featuring resumable GPU checkpointing and in-UI reports. ### **Biotech & healthcare > Drug molecule screening agent** Agentic virtual screening with RDKit stage tools, Lipinski filters, and ranked drug-likeness reports. ## Subpages - **Biotech & healthcare > Genomic alignment** - Align sequencing reads to a reference genome with a cached, parallel Bowtie 2 pipeline. - **Biotech & healthcare > Brain tumor MRI classification** - Classify brain MRI scans with a two-phase EfficientNet-B4 pipeline featuring resumable GPU checkpointing and in-UI reports. - **Biotech & healthcare > Cross-species gene comparison** - Compare homologous genes across species with Carbon scoring, sequence alignment, and ESMFold 3D structures. - **Biotech & healthcare > Genomic variant effect prediction** - Zero-shot pathogenicity scoring with HuggingFace Carbon and interactive VEP reports. - **Biotech & healthcare > Drug molecule screening agent** - Agentic virtual screening with RDKit stage tools, Lipinski filters, and ranked drug-likeness reports. === PAGE: https://www.union.ai/docs/v2/union/tutorials/biotech-healthcare/genomic-alignment === Align sequencing reads to a reference genome with a cached, parallel Bowtie 2 pipeline. # Genomic alignment > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/genomic_alignment). This tutorial builds a bioinformatics pipeline that aligns raw sequencing reads to a reference genome. The workflow downloads a reference genome and paired-end sequencing data, performs quality filtering, builds a reference index, and aligns the filtered reads with the [Bowtie 2](https://bowtie-bio.sourceforge.net/bowtie2/index.shtml) aligner, running each sample in parallel. It's a good showcase of how Flyte handles real bioinformatics workloads: - **Per-task resources** so quality filtering, indexing, and alignment each request exactly the CPU and memory they need. - **`cache="auto"`** on the download and indexing steps, so re-runs skip work that hasn't changed. - **Fan-out parallelism** across samples with `asyncio.gather`. - **System dependencies** (`fastp`, `bowtie2`) installed into the container image with `apt`. ## Define the container image Because the pipeline shells out to bioinformatics tools, we build a custom image with `flyte.Image.from_uv_script` and install `fastp` (quality filtering) and `bowtie2` (alignment) via `apt`. ``` # # Genomic Alignment # # This tutorial demonstrates how to use Flyte to build a workflow that # performs genomic alignment on sequencing data. The workflow takes as input # a reference genome and raw sequencing data, performs quality filtering and # preprocessing on the raw data, generates an index for the reference genome, # and aligns the filtered data to the reference genome using the Bowtie 2 aligner. # {{run-on-union}} # The tutorial is divided into the following sections: # 1. Define the container image # 2. Define the data classes # 3. Define the tasks # 4. Define the workflow # /// script # requires-python = "3.12" # dependencies = [ # "flyte", # "requests", # ] # main = "alignment_wf" # params = "" # /// import asyncio import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import List import requests import flyte from flyte.io import Dir, File # ## Defining a Container Image # # We define a custom container image using `flyte.Image`. Since we need bioinformatics # tools โ€” `fastp` for quality filtering and `bowtie2` for alignment โ€” we install them # via apt. This approach replaces the v1 `ImageSpec` with conda channels. # {{docs-fragment image}} main_img = ( flyte.Image.from_uv_script( __file__, name="alignment-tutorial", ) .with_apt_packages("fastp", "bowtie2") ) # {{/docs-fragment image}} # We define per-task environments with different resource requirements, then a # top-level `base_env` that declares all of them as dependencies (required because # `alignment_wf` and `bowtie2_align_samples` call tasks that live in those environments). # {{docs-fragment envs}} fetch_env = flyte.TaskEnvironment( name="alignment-tutorial-fetch", image=main_img, cache="auto", ) fastp_env = flyte.TaskEnvironment( name="alignment-tutorial-fastp", image=main_img, resources=flyte.Resources(memory="2Gi"), ) index_env = flyte.TaskEnvironment( name="alignment-tutorial-index", image=main_img, resources=flyte.Resources(memory="10Gi"), cache="auto", ) align_env = flyte.TaskEnvironment( name="alignment-tutorial-align", image=main_img, resources=flyte.Resources(cpu=2, memory="10Gi"), ) base_env = flyte.TaskEnvironment( name="alignment-tutorial", image=main_img, depends_on=[fetch_env, fastp_env, index_env, align_env], ) # {{/docs-fragment envs}} # ## Defining Data Classes # # We define three data classes to represent the reference genome, sequencing reads, # and alignment results. We'll first define a convenience function to download files, # which we'll use within the fetch task to materialize assets from their remote locations. def fetch_file(url: str, local_dir: str) -> Path: """ Downloads a file from the specified URL. Args: url (str): The URL of the file to download. local_dir (str): The directory where you would like this file saved. Returns: Path: The local path to the file. Raises: requests.HTTPError: If an HTTP error occurs while downloading the file. """ url_parts = url.split("/") fname = url_parts[-1] local_path = Path(local_dir) / fname response = requests.get(url) with open(local_path, "wb") as file: file.write(response.content) return local_path # Reference genomes are used extensively throughout bioinformatics workflows. We define a # `Reference` data class to represent a reference genome and its associated index files. # {{docs-fragment dataclasses}} @dataclass class Reference: """ Represents a reference FASTA and associated index files. Attributes: ref_name (str): Name or identifier of the reference file. ref_dir (Dir): Directory containing the reference and any index files. index_name (str): Index string to pass to tools requiring it. indexed_with (str): Name of tool used to create the index. """ ref_name: str ref_dir: Dir index_name: str | None = None indexed_with: str | None = None # Sequencing reads are the raw data generated from a sequencing experiment. @dataclass class Reads: """ Represents a sequencing reads sample via its associated FastQ files. Attributes: sample (str): The name or identifier of the raw sequencing sample. read1 (File): A File object representing the path to the raw R1 read file. read2 (File): A File object representing the path to the raw R2 read file. """ sample: str read1: File | None = None read2: File | None = None def get_read_fnames(self): return ( f"{self.sample}_1.fastq.gz", f"{self.sample}_2.fastq.gz", ) # Finally, we define an `Alignment` data class to represent an alignment file. @dataclass class Alignment: """ Represents an alignment file and its associated sample. Attributes: sample (str): The name or identifier of the sample. aligner (str): The name of the aligner used to generate the alignment file. format (str): The format of the alignment file (e.g., SAM, BAM). alignment (File): A File object representing the path to the alignment file. """ sample: str aligner: str format: str | None = None alignment: File | None = None def get_alignment_fname(self): return f"{self.sample}_{self.aligner}_aligned.{self.format}" # {{/docs-fragment dataclasses}} # ## Tasks # # We define a series of tasks to perform the following operations: # 1. Fetch assets from remote URLs # 2. Perform quality filtering and preprocessing using FastP # 3. Generate Bowtie2 index files from a reference genome # 4. Perform alignment using Bowtie2 on a filtered sample # # The first task fetches the reference genome and sequencing reads. It is cached # so that re-runs skip the download step. # {{docs-fragment fetch_assets}} @fetch_env.task async def fetch_assets( ref_url: str, read_urls: List[str] ) -> tuple[Reference, List[Reads]]: """ Fetch assets from remote URLs. """ # Download reference genome ref_dir = Path("/tmp/reference_genome") ref_dir.mkdir(exist_ok=True, parents=True) ref = fetch_file(ref_url, str(ref_dir)) ref_obj = Reference( ref_name=ref.name, ref_dir=await Dir.from_local(str(ref_dir)), ) # Download sequencing reads dl_loc = Path("/tmp/reads") dl_loc.mkdir(exist_ok=True, parents=True) samples: dict[str, Reads] = {} for url in read_urls: fp = fetch_file(url, str(dl_loc)) sample = fp.stem.split("_")[0] if sample not in samples: samples[sample] = Reads(sample=sample) if ".fastq.gz" in fp.name or "fasta" in fp.name: mate = fp.name.strip(".fastq.gz").strip(".filt").split("_")[-1] if "1" in mate: samples[sample].read1 = await File.from_local(str(fp)) elif "2" in mate: samples[sample].read2 = await File.from_local(str(fp)) return ref_obj, list(samples.values()) # {{/docs-fragment fetch_assets}} # The second task performs quality filtering and preprocessing using FastP on a Reads object. # FastP is a performant tool for removing duplicate or low-quality reads. We increase # the memory request for this task so FastP can efficiently process reads from larger files. # {{docs-fragment pyfastp}} @fastp_env.task async def pyfastp(rs: Reads) -> Reads: """ Perform quality filtering and preprocessing using Fastp on a Reads object. Args: rs (Reads): A Reads object containing raw sequencing data to be processed. Returns: Reads: A Reads object representing the filtered and preprocessed data. """ ldir = Path(tempfile.mkdtemp()) samp = Reads(rs.sample) o1, o2 = samp.get_read_fnames() o1p = ldir / o1 o2p = ldir / o2 assert rs.read1 is not None and rs.read2 is not None r1 = await rs.read1.download() r2 = await rs.read2.download() cmd = [ "fastp", "-i", str(r1), "-I", str(r2), "-o", str(o1p), "-O", str(o2p), ] subprocess.run(cmd, check=True) samp.read1 = await File.from_local(str(o1p)) samp.read2 = await File.from_local(str(o2p)) return samp # {{/docs-fragment pyfastp}} # Next, we define a task to generate Bowtie2 index files from a reference genome. As the index # for a given tool and reference seldom changes, we cache this task. # {{docs-fragment bowtie2_index}} @index_env.task async def bowtie2_index(ref: Reference) -> Reference: """ Generate Bowtie2 index files from a reference genome. Args: ref (Reference): A Reference object representing the reference genome. Returns: Reference: The same reference object with the index_name and indexed_with attributes set. """ ref_dir = await ref.ref_dir.download() idx_name = "bt2_idx" cmd = [ "bowtie2-build", str(Path(str(ref_dir)) / ref.ref_name), str(Path(str(ref_dir)) / idx_name), ] subprocess.run(cmd, check=True) return Reference( ref.ref_name, await Dir.from_local(str(ref_dir)), idx_name, "bowtie2", ) # {{/docs-fragment bowtie2_index}} # The next task performs paired-end alignment using Bowtie 2 on a single sample. # {{docs-fragment bowtie2_align}} @align_env.task async def bowtie2_align_paired_reads(idx: Reference, fs: Reads) -> Alignment: """ Perform paired-end alignment using Bowtie 2 on a filtered sample. Args: idx (Reference): A Reference object containing the Bowtie 2 index. fs (Reads): A filtered Reads object containing sample data to be aligned. Returns: Alignment: An Alignment object representing the alignment result. """ assert idx.indexed_with == "bowtie2", "Reference index must be generated with bowtie2" assert idx.index_name is not None assert fs.read1 is not None and fs.read2 is not None ref_dir = await idx.ref_dir.download() r1 = await fs.read1.download() r2 = await fs.read2.download() ldir = Path(tempfile.mkdtemp()) alignment = Alignment(fs.sample, "bowtie2", "sam") al = ldir / alignment.get_alignment_fname() cmd = [ "bowtie2", "-x", str(Path(str(ref_dir)) / idx.index_name), "-1", str(r1), "-2", str(r2), "-S", str(al), ] subprocess.run(cmd, check=True) alignment.alignment = await File.from_local(str(al)) return alignment # {{/docs-fragment bowtie2_align}} # In place of the v1 `@dynamic` workflow, we use a plain async task with `asyncio.gather` # to run alignments for all samples in parallel. @base_env.task async def bowtie2_align_samples( idx: Reference, samples: List[Reads] ) -> List[Alignment]: """ Process samples through bowtie2 in parallel. Args: idx (Reference): A Reference object containing the Bowtie 2 index. samples (List[Reads]): A list of Reads objects to be aligned. Returns: List[Alignment]: A list of Alignment objects representing the alignment results. """ tasks = [bowtie2_align_paired_reads(idx=idx, fs=sample) for sample in samples] return list(await asyncio.gather(*tasks)) # ## End-to-End Workflow # # We tie everything together in a final task that fetches assets, filters them, generates # an index, and aligns the samples. In place of the v1 `@workflow`, we use a top-level # `@base_env.task`. Parallelism across samples is achieved with `asyncio.gather`. # {{docs-fragment workflow}} @base_env.task async def alignment_wf() -> List[Alignment]: # Prepare raw samples from remote URLs ref, samples = await fetch_assets( ref_url="https://github.com/unionai-oss/unionbio/raw/main/tests/assets/references/GRCh38_short.fasta", read_urls=[ "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_1.fastq.gz", "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_2.fastq.gz", ], ) # Filter all samples in parallel filtered_samples = list( await asyncio.gather(*[pyfastp(rs=s) for s in samples]) ) # Generate a bowtie2 index or load it from cache bowtie2_idx = await bowtie2_index(ref=ref) # Generate alignments using bowtie2 sams = await bowtie2_align_samples(idx=bowtie2_idx, samples=filtered_samples) return sams # {{/docs-fragment workflow}} # You can now run the workflow using the command in the dropdown at the top of the page! if __name__ == "__main__": flyte.init_from_config() run = flyte.run(alignment_wf) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_alignment/genomic_alignment.py* The Python dependencies are declared at the top of the file using the `uv` script style: CODE0 ## Define the task environments Each stage runs in its own `TaskEnvironment` with tailored resources. The top-level `base_env` declares the others as `depends_on` so the tasks it calls are available at run time. ``` # # Genomic Alignment # # This tutorial demonstrates how to use Flyte to build a workflow that # performs genomic alignment on sequencing data. The workflow takes as input # a reference genome and raw sequencing data, performs quality filtering and # preprocessing on the raw data, generates an index for the reference genome, # and aligns the filtered data to the reference genome using the Bowtie 2 aligner. # {{run-on-union}} # The tutorial is divided into the following sections: # 1. Define the container image # 2. Define the data classes # 3. Define the tasks # 4. Define the workflow # /// script # requires-python = "3.12" # dependencies = [ # "flyte", # "requests", # ] # main = "alignment_wf" # params = "" # /// import asyncio import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import List import requests import flyte from flyte.io import Dir, File # ## Defining a Container Image # # We define a custom container image using `flyte.Image`. Since we need bioinformatics # tools โ€” `fastp` for quality filtering and `bowtie2` for alignment โ€” we install them # via apt. This approach replaces the v1 `ImageSpec` with conda channels. # {{docs-fragment image}} main_img = ( flyte.Image.from_uv_script( __file__, name="alignment-tutorial", ) .with_apt_packages("fastp", "bowtie2") ) # {{/docs-fragment image}} # We define per-task environments with different resource requirements, then a # top-level `base_env` that declares all of them as dependencies (required because # `alignment_wf` and `bowtie2_align_samples` call tasks that live in those environments). # {{docs-fragment envs}} fetch_env = flyte.TaskEnvironment( name="alignment-tutorial-fetch", image=main_img, cache="auto", ) fastp_env = flyte.TaskEnvironment( name="alignment-tutorial-fastp", image=main_img, resources=flyte.Resources(memory="2Gi"), ) index_env = flyte.TaskEnvironment( name="alignment-tutorial-index", image=main_img, resources=flyte.Resources(memory="10Gi"), cache="auto", ) align_env = flyte.TaskEnvironment( name="alignment-tutorial-align", image=main_img, resources=flyte.Resources(cpu=2, memory="10Gi"), ) base_env = flyte.TaskEnvironment( name="alignment-tutorial", image=main_img, depends_on=[fetch_env, fastp_env, index_env, align_env], ) # {{/docs-fragment envs}} # ## Defining Data Classes # # We define three data classes to represent the reference genome, sequencing reads, # and alignment results. We'll first define a convenience function to download files, # which we'll use within the fetch task to materialize assets from their remote locations. def fetch_file(url: str, local_dir: str) -> Path: """ Downloads a file from the specified URL. Args: url (str): The URL of the file to download. local_dir (str): The directory where you would like this file saved. Returns: Path: The local path to the file. Raises: requests.HTTPError: If an HTTP error occurs while downloading the file. """ url_parts = url.split("/") fname = url_parts[-1] local_path = Path(local_dir) / fname response = requests.get(url) with open(local_path, "wb") as file: file.write(response.content) return local_path # Reference genomes are used extensively throughout bioinformatics workflows. We define a # `Reference` data class to represent a reference genome and its associated index files. # {{docs-fragment dataclasses}} @dataclass class Reference: """ Represents a reference FASTA and associated index files. Attributes: ref_name (str): Name or identifier of the reference file. ref_dir (Dir): Directory containing the reference and any index files. index_name (str): Index string to pass to tools requiring it. indexed_with (str): Name of tool used to create the index. """ ref_name: str ref_dir: Dir index_name: str | None = None indexed_with: str | None = None # Sequencing reads are the raw data generated from a sequencing experiment. @dataclass class Reads: """ Represents a sequencing reads sample via its associated FastQ files. Attributes: sample (str): The name or identifier of the raw sequencing sample. read1 (File): A File object representing the path to the raw R1 read file. read2 (File): A File object representing the path to the raw R2 read file. """ sample: str read1: File | None = None read2: File | None = None def get_read_fnames(self): return ( f"{self.sample}_1.fastq.gz", f"{self.sample}_2.fastq.gz", ) # Finally, we define an `Alignment` data class to represent an alignment file. @dataclass class Alignment: """ Represents an alignment file and its associated sample. Attributes: sample (str): The name or identifier of the sample. aligner (str): The name of the aligner used to generate the alignment file. format (str): The format of the alignment file (e.g., SAM, BAM). alignment (File): A File object representing the path to the alignment file. """ sample: str aligner: str format: str | None = None alignment: File | None = None def get_alignment_fname(self): return f"{self.sample}_{self.aligner}_aligned.{self.format}" # {{/docs-fragment dataclasses}} # ## Tasks # # We define a series of tasks to perform the following operations: # 1. Fetch assets from remote URLs # 2. Perform quality filtering and preprocessing using FastP # 3. Generate Bowtie2 index files from a reference genome # 4. Perform alignment using Bowtie2 on a filtered sample # # The first task fetches the reference genome and sequencing reads. It is cached # so that re-runs skip the download step. # {{docs-fragment fetch_assets}} @fetch_env.task async def fetch_assets( ref_url: str, read_urls: List[str] ) -> tuple[Reference, List[Reads]]: """ Fetch assets from remote URLs. """ # Download reference genome ref_dir = Path("/tmp/reference_genome") ref_dir.mkdir(exist_ok=True, parents=True) ref = fetch_file(ref_url, str(ref_dir)) ref_obj = Reference( ref_name=ref.name, ref_dir=await Dir.from_local(str(ref_dir)), ) # Download sequencing reads dl_loc = Path("/tmp/reads") dl_loc.mkdir(exist_ok=True, parents=True) samples: dict[str, Reads] = {} for url in read_urls: fp = fetch_file(url, str(dl_loc)) sample = fp.stem.split("_")[0] if sample not in samples: samples[sample] = Reads(sample=sample) if ".fastq.gz" in fp.name or "fasta" in fp.name: mate = fp.name.strip(".fastq.gz").strip(".filt").split("_")[-1] if "1" in mate: samples[sample].read1 = await File.from_local(str(fp)) elif "2" in mate: samples[sample].read2 = await File.from_local(str(fp)) return ref_obj, list(samples.values()) # {{/docs-fragment fetch_assets}} # The second task performs quality filtering and preprocessing using FastP on a Reads object. # FastP is a performant tool for removing duplicate or low-quality reads. We increase # the memory request for this task so FastP can efficiently process reads from larger files. # {{docs-fragment pyfastp}} @fastp_env.task async def pyfastp(rs: Reads) -> Reads: """ Perform quality filtering and preprocessing using Fastp on a Reads object. Args: rs (Reads): A Reads object containing raw sequencing data to be processed. Returns: Reads: A Reads object representing the filtered and preprocessed data. """ ldir = Path(tempfile.mkdtemp()) samp = Reads(rs.sample) o1, o2 = samp.get_read_fnames() o1p = ldir / o1 o2p = ldir / o2 assert rs.read1 is not None and rs.read2 is not None r1 = await rs.read1.download() r2 = await rs.read2.download() cmd = [ "fastp", "-i", str(r1), "-I", str(r2), "-o", str(o1p), "-O", str(o2p), ] subprocess.run(cmd, check=True) samp.read1 = await File.from_local(str(o1p)) samp.read2 = await File.from_local(str(o2p)) return samp # {{/docs-fragment pyfastp}} # Next, we define a task to generate Bowtie2 index files from a reference genome. As the index # for a given tool and reference seldom changes, we cache this task. # {{docs-fragment bowtie2_index}} @index_env.task async def bowtie2_index(ref: Reference) -> Reference: """ Generate Bowtie2 index files from a reference genome. Args: ref (Reference): A Reference object representing the reference genome. Returns: Reference: The same reference object with the index_name and indexed_with attributes set. """ ref_dir = await ref.ref_dir.download() idx_name = "bt2_idx" cmd = [ "bowtie2-build", str(Path(str(ref_dir)) / ref.ref_name), str(Path(str(ref_dir)) / idx_name), ] subprocess.run(cmd, check=True) return Reference( ref.ref_name, await Dir.from_local(str(ref_dir)), idx_name, "bowtie2", ) # {{/docs-fragment bowtie2_index}} # The next task performs paired-end alignment using Bowtie 2 on a single sample. # {{docs-fragment bowtie2_align}} @align_env.task async def bowtie2_align_paired_reads(idx: Reference, fs: Reads) -> Alignment: """ Perform paired-end alignment using Bowtie 2 on a filtered sample. Args: idx (Reference): A Reference object containing the Bowtie 2 index. fs (Reads): A filtered Reads object containing sample data to be aligned. Returns: Alignment: An Alignment object representing the alignment result. """ assert idx.indexed_with == "bowtie2", "Reference index must be generated with bowtie2" assert idx.index_name is not None assert fs.read1 is not None and fs.read2 is not None ref_dir = await idx.ref_dir.download() r1 = await fs.read1.download() r2 = await fs.read2.download() ldir = Path(tempfile.mkdtemp()) alignment = Alignment(fs.sample, "bowtie2", "sam") al = ldir / alignment.get_alignment_fname() cmd = [ "bowtie2", "-x", str(Path(str(ref_dir)) / idx.index_name), "-1", str(r1), "-2", str(r2), "-S", str(al), ] subprocess.run(cmd, check=True) alignment.alignment = await File.from_local(str(al)) return alignment # {{/docs-fragment bowtie2_align}} # In place of the v1 `@dynamic` workflow, we use a plain async task with `asyncio.gather` # to run alignments for all samples in parallel. @base_env.task async def bowtie2_align_samples( idx: Reference, samples: List[Reads] ) -> List[Alignment]: """ Process samples through bowtie2 in parallel. Args: idx (Reference): A Reference object containing the Bowtie 2 index. samples (List[Reads]): A list of Reads objects to be aligned. Returns: List[Alignment]: A list of Alignment objects representing the alignment results. """ tasks = [bowtie2_align_paired_reads(idx=idx, fs=sample) for sample in samples] return list(await asyncio.gather(*tasks)) # ## End-to-End Workflow # # We tie everything together in a final task that fetches assets, filters them, generates # an index, and aligns the samples. In place of the v1 `@workflow`, we use a top-level # `@base_env.task`. Parallelism across samples is achieved with `asyncio.gather`. # {{docs-fragment workflow}} @base_env.task async def alignment_wf() -> List[Alignment]: # Prepare raw samples from remote URLs ref, samples = await fetch_assets( ref_url="https://github.com/unionai-oss/unionbio/raw/main/tests/assets/references/GRCh38_short.fasta", read_urls=[ "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_1.fastq.gz", "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_2.fastq.gz", ], ) # Filter all samples in parallel filtered_samples = list( await asyncio.gather(*[pyfastp(rs=s) for s in samples]) ) # Generate a bowtie2 index or load it from cache bowtie2_idx = await bowtie2_index(ref=ref) # Generate alignments using bowtie2 sams = await bowtie2_align_samples(idx=bowtie2_idx, samples=filtered_samples) return sams # {{/docs-fragment workflow}} # You can now run the workflow using the command in the dropdown at the top of the page! if __name__ == "__main__": flyte.init_from_config() run = flyte.run(alignment_wf) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_alignment/genomic_alignment.py* ## Define the data classes We model the reference genome, sequencing reads, and alignment results as dataclasses. `flyte.io.File` and `flyte.io.Dir` reference offloaded data in blob storage, so large genomic files are passed between tasks by reference rather than copied through the orchestrator. ``` # # Genomic Alignment # # This tutorial demonstrates how to use Flyte to build a workflow that # performs genomic alignment on sequencing data. The workflow takes as input # a reference genome and raw sequencing data, performs quality filtering and # preprocessing on the raw data, generates an index for the reference genome, # and aligns the filtered data to the reference genome using the Bowtie 2 aligner. # {{run-on-union}} # The tutorial is divided into the following sections: # 1. Define the container image # 2. Define the data classes # 3. Define the tasks # 4. Define the workflow # /// script # requires-python = "3.12" # dependencies = [ # "flyte", # "requests", # ] # main = "alignment_wf" # params = "" # /// import asyncio import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import List import requests import flyte from flyte.io import Dir, File # ## Defining a Container Image # # We define a custom container image using `flyte.Image`. Since we need bioinformatics # tools โ€” `fastp` for quality filtering and `bowtie2` for alignment โ€” we install them # via apt. This approach replaces the v1 `ImageSpec` with conda channels. # {{docs-fragment image}} main_img = ( flyte.Image.from_uv_script( __file__, name="alignment-tutorial", ) .with_apt_packages("fastp", "bowtie2") ) # {{/docs-fragment image}} # We define per-task environments with different resource requirements, then a # top-level `base_env` that declares all of them as dependencies (required because # `alignment_wf` and `bowtie2_align_samples` call tasks that live in those environments). # {{docs-fragment envs}} fetch_env = flyte.TaskEnvironment( name="alignment-tutorial-fetch", image=main_img, cache="auto", ) fastp_env = flyte.TaskEnvironment( name="alignment-tutorial-fastp", image=main_img, resources=flyte.Resources(memory="2Gi"), ) index_env = flyte.TaskEnvironment( name="alignment-tutorial-index", image=main_img, resources=flyte.Resources(memory="10Gi"), cache="auto", ) align_env = flyte.TaskEnvironment( name="alignment-tutorial-align", image=main_img, resources=flyte.Resources(cpu=2, memory="10Gi"), ) base_env = flyte.TaskEnvironment( name="alignment-tutorial", image=main_img, depends_on=[fetch_env, fastp_env, index_env, align_env], ) # {{/docs-fragment envs}} # ## Defining Data Classes # # We define three data classes to represent the reference genome, sequencing reads, # and alignment results. We'll first define a convenience function to download files, # which we'll use within the fetch task to materialize assets from their remote locations. def fetch_file(url: str, local_dir: str) -> Path: """ Downloads a file from the specified URL. Args: url (str): The URL of the file to download. local_dir (str): The directory where you would like this file saved. Returns: Path: The local path to the file. Raises: requests.HTTPError: If an HTTP error occurs while downloading the file. """ url_parts = url.split("/") fname = url_parts[-1] local_path = Path(local_dir) / fname response = requests.get(url) with open(local_path, "wb") as file: file.write(response.content) return local_path # Reference genomes are used extensively throughout bioinformatics workflows. We define a # `Reference` data class to represent a reference genome and its associated index files. # {{docs-fragment dataclasses}} @dataclass class Reference: """ Represents a reference FASTA and associated index files. Attributes: ref_name (str): Name or identifier of the reference file. ref_dir (Dir): Directory containing the reference and any index files. index_name (str): Index string to pass to tools requiring it. indexed_with (str): Name of tool used to create the index. """ ref_name: str ref_dir: Dir index_name: str | None = None indexed_with: str | None = None # Sequencing reads are the raw data generated from a sequencing experiment. @dataclass class Reads: """ Represents a sequencing reads sample via its associated FastQ files. Attributes: sample (str): The name or identifier of the raw sequencing sample. read1 (File): A File object representing the path to the raw R1 read file. read2 (File): A File object representing the path to the raw R2 read file. """ sample: str read1: File | None = None read2: File | None = None def get_read_fnames(self): return ( f"{self.sample}_1.fastq.gz", f"{self.sample}_2.fastq.gz", ) # Finally, we define an `Alignment` data class to represent an alignment file. @dataclass class Alignment: """ Represents an alignment file and its associated sample. Attributes: sample (str): The name or identifier of the sample. aligner (str): The name of the aligner used to generate the alignment file. format (str): The format of the alignment file (e.g., SAM, BAM). alignment (File): A File object representing the path to the alignment file. """ sample: str aligner: str format: str | None = None alignment: File | None = None def get_alignment_fname(self): return f"{self.sample}_{self.aligner}_aligned.{self.format}" # {{/docs-fragment dataclasses}} # ## Tasks # # We define a series of tasks to perform the following operations: # 1. Fetch assets from remote URLs # 2. Perform quality filtering and preprocessing using FastP # 3. Generate Bowtie2 index files from a reference genome # 4. Perform alignment using Bowtie2 on a filtered sample # # The first task fetches the reference genome and sequencing reads. It is cached # so that re-runs skip the download step. # {{docs-fragment fetch_assets}} @fetch_env.task async def fetch_assets( ref_url: str, read_urls: List[str] ) -> tuple[Reference, List[Reads]]: """ Fetch assets from remote URLs. """ # Download reference genome ref_dir = Path("/tmp/reference_genome") ref_dir.mkdir(exist_ok=True, parents=True) ref = fetch_file(ref_url, str(ref_dir)) ref_obj = Reference( ref_name=ref.name, ref_dir=await Dir.from_local(str(ref_dir)), ) # Download sequencing reads dl_loc = Path("/tmp/reads") dl_loc.mkdir(exist_ok=True, parents=True) samples: dict[str, Reads] = {} for url in read_urls: fp = fetch_file(url, str(dl_loc)) sample = fp.stem.split("_")[0] if sample not in samples: samples[sample] = Reads(sample=sample) if ".fastq.gz" in fp.name or "fasta" in fp.name: mate = fp.name.strip(".fastq.gz").strip(".filt").split("_")[-1] if "1" in mate: samples[sample].read1 = await File.from_local(str(fp)) elif "2" in mate: samples[sample].read2 = await File.from_local(str(fp)) return ref_obj, list(samples.values()) # {{/docs-fragment fetch_assets}} # The second task performs quality filtering and preprocessing using FastP on a Reads object. # FastP is a performant tool for removing duplicate or low-quality reads. We increase # the memory request for this task so FastP can efficiently process reads from larger files. # {{docs-fragment pyfastp}} @fastp_env.task async def pyfastp(rs: Reads) -> Reads: """ Perform quality filtering and preprocessing using Fastp on a Reads object. Args: rs (Reads): A Reads object containing raw sequencing data to be processed. Returns: Reads: A Reads object representing the filtered and preprocessed data. """ ldir = Path(tempfile.mkdtemp()) samp = Reads(rs.sample) o1, o2 = samp.get_read_fnames() o1p = ldir / o1 o2p = ldir / o2 assert rs.read1 is not None and rs.read2 is not None r1 = await rs.read1.download() r2 = await rs.read2.download() cmd = [ "fastp", "-i", str(r1), "-I", str(r2), "-o", str(o1p), "-O", str(o2p), ] subprocess.run(cmd, check=True) samp.read1 = await File.from_local(str(o1p)) samp.read2 = await File.from_local(str(o2p)) return samp # {{/docs-fragment pyfastp}} # Next, we define a task to generate Bowtie2 index files from a reference genome. As the index # for a given tool and reference seldom changes, we cache this task. # {{docs-fragment bowtie2_index}} @index_env.task async def bowtie2_index(ref: Reference) -> Reference: """ Generate Bowtie2 index files from a reference genome. Args: ref (Reference): A Reference object representing the reference genome. Returns: Reference: The same reference object with the index_name and indexed_with attributes set. """ ref_dir = await ref.ref_dir.download() idx_name = "bt2_idx" cmd = [ "bowtie2-build", str(Path(str(ref_dir)) / ref.ref_name), str(Path(str(ref_dir)) / idx_name), ] subprocess.run(cmd, check=True) return Reference( ref.ref_name, await Dir.from_local(str(ref_dir)), idx_name, "bowtie2", ) # {{/docs-fragment bowtie2_index}} # The next task performs paired-end alignment using Bowtie 2 on a single sample. # {{docs-fragment bowtie2_align}} @align_env.task async def bowtie2_align_paired_reads(idx: Reference, fs: Reads) -> Alignment: """ Perform paired-end alignment using Bowtie 2 on a filtered sample. Args: idx (Reference): A Reference object containing the Bowtie 2 index. fs (Reads): A filtered Reads object containing sample data to be aligned. Returns: Alignment: An Alignment object representing the alignment result. """ assert idx.indexed_with == "bowtie2", "Reference index must be generated with bowtie2" assert idx.index_name is not None assert fs.read1 is not None and fs.read2 is not None ref_dir = await idx.ref_dir.download() r1 = await fs.read1.download() r2 = await fs.read2.download() ldir = Path(tempfile.mkdtemp()) alignment = Alignment(fs.sample, "bowtie2", "sam") al = ldir / alignment.get_alignment_fname() cmd = [ "bowtie2", "-x", str(Path(str(ref_dir)) / idx.index_name), "-1", str(r1), "-2", str(r2), "-S", str(al), ] subprocess.run(cmd, check=True) alignment.alignment = await File.from_local(str(al)) return alignment # {{/docs-fragment bowtie2_align}} # In place of the v1 `@dynamic` workflow, we use a plain async task with `asyncio.gather` # to run alignments for all samples in parallel. @base_env.task async def bowtie2_align_samples( idx: Reference, samples: List[Reads] ) -> List[Alignment]: """ Process samples through bowtie2 in parallel. Args: idx (Reference): A Reference object containing the Bowtie 2 index. samples (List[Reads]): A list of Reads objects to be aligned. Returns: List[Alignment]: A list of Alignment objects representing the alignment results. """ tasks = [bowtie2_align_paired_reads(idx=idx, fs=sample) for sample in samples] return list(await asyncio.gather(*tasks)) # ## End-to-End Workflow # # We tie everything together in a final task that fetches assets, filters them, generates # an index, and aligns the samples. In place of the v1 `@workflow`, we use a top-level # `@base_env.task`. Parallelism across samples is achieved with `asyncio.gather`. # {{docs-fragment workflow}} @base_env.task async def alignment_wf() -> List[Alignment]: # Prepare raw samples from remote URLs ref, samples = await fetch_assets( ref_url="https://github.com/unionai-oss/unionbio/raw/main/tests/assets/references/GRCh38_short.fasta", read_urls=[ "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_1.fastq.gz", "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_2.fastq.gz", ], ) # Filter all samples in parallel filtered_samples = list( await asyncio.gather(*[pyfastp(rs=s) for s in samples]) ) # Generate a bowtie2 index or load it from cache bowtie2_idx = await bowtie2_index(ref=ref) # Generate alignments using bowtie2 sams = await bowtie2_align_samples(idx=bowtie2_idx, samples=filtered_samples) return sams # {{/docs-fragment workflow}} # You can now run the workflow using the command in the dropdown at the top of the page! if __name__ == "__main__": flyte.init_from_config() run = flyte.run(alignment_wf) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_alignment/genomic_alignment.py* ## Fetch assets The first task downloads the reference genome and paired-end reads from remote URLs and materializes them as `File`/`Dir` objects. It's cached, so repeat runs skip the download. ``` # # Genomic Alignment # # This tutorial demonstrates how to use Flyte to build a workflow that # performs genomic alignment on sequencing data. The workflow takes as input # a reference genome and raw sequencing data, performs quality filtering and # preprocessing on the raw data, generates an index for the reference genome, # and aligns the filtered data to the reference genome using the Bowtie 2 aligner. # {{run-on-union}} # The tutorial is divided into the following sections: # 1. Define the container image # 2. Define the data classes # 3. Define the tasks # 4. Define the workflow # /// script # requires-python = "3.12" # dependencies = [ # "flyte", # "requests", # ] # main = "alignment_wf" # params = "" # /// import asyncio import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import List import requests import flyte from flyte.io import Dir, File # ## Defining a Container Image # # We define a custom container image using `flyte.Image`. Since we need bioinformatics # tools โ€” `fastp` for quality filtering and `bowtie2` for alignment โ€” we install them # via apt. This approach replaces the v1 `ImageSpec` with conda channels. # {{docs-fragment image}} main_img = ( flyte.Image.from_uv_script( __file__, name="alignment-tutorial", ) .with_apt_packages("fastp", "bowtie2") ) # {{/docs-fragment image}} # We define per-task environments with different resource requirements, then a # top-level `base_env` that declares all of them as dependencies (required because # `alignment_wf` and `bowtie2_align_samples` call tasks that live in those environments). # {{docs-fragment envs}} fetch_env = flyte.TaskEnvironment( name="alignment-tutorial-fetch", image=main_img, cache="auto", ) fastp_env = flyte.TaskEnvironment( name="alignment-tutorial-fastp", image=main_img, resources=flyte.Resources(memory="2Gi"), ) index_env = flyte.TaskEnvironment( name="alignment-tutorial-index", image=main_img, resources=flyte.Resources(memory="10Gi"), cache="auto", ) align_env = flyte.TaskEnvironment( name="alignment-tutorial-align", image=main_img, resources=flyte.Resources(cpu=2, memory="10Gi"), ) base_env = flyte.TaskEnvironment( name="alignment-tutorial", image=main_img, depends_on=[fetch_env, fastp_env, index_env, align_env], ) # {{/docs-fragment envs}} # ## Defining Data Classes # # We define three data classes to represent the reference genome, sequencing reads, # and alignment results. We'll first define a convenience function to download files, # which we'll use within the fetch task to materialize assets from their remote locations. def fetch_file(url: str, local_dir: str) -> Path: """ Downloads a file from the specified URL. Args: url (str): The URL of the file to download. local_dir (str): The directory where you would like this file saved. Returns: Path: The local path to the file. Raises: requests.HTTPError: If an HTTP error occurs while downloading the file. """ url_parts = url.split("/") fname = url_parts[-1] local_path = Path(local_dir) / fname response = requests.get(url) with open(local_path, "wb") as file: file.write(response.content) return local_path # Reference genomes are used extensively throughout bioinformatics workflows. We define a # `Reference` data class to represent a reference genome and its associated index files. # {{docs-fragment dataclasses}} @dataclass class Reference: """ Represents a reference FASTA and associated index files. Attributes: ref_name (str): Name or identifier of the reference file. ref_dir (Dir): Directory containing the reference and any index files. index_name (str): Index string to pass to tools requiring it. indexed_with (str): Name of tool used to create the index. """ ref_name: str ref_dir: Dir index_name: str | None = None indexed_with: str | None = None # Sequencing reads are the raw data generated from a sequencing experiment. @dataclass class Reads: """ Represents a sequencing reads sample via its associated FastQ files. Attributes: sample (str): The name or identifier of the raw sequencing sample. read1 (File): A File object representing the path to the raw R1 read file. read2 (File): A File object representing the path to the raw R2 read file. """ sample: str read1: File | None = None read2: File | None = None def get_read_fnames(self): return ( f"{self.sample}_1.fastq.gz", f"{self.sample}_2.fastq.gz", ) # Finally, we define an `Alignment` data class to represent an alignment file. @dataclass class Alignment: """ Represents an alignment file and its associated sample. Attributes: sample (str): The name or identifier of the sample. aligner (str): The name of the aligner used to generate the alignment file. format (str): The format of the alignment file (e.g., SAM, BAM). alignment (File): A File object representing the path to the alignment file. """ sample: str aligner: str format: str | None = None alignment: File | None = None def get_alignment_fname(self): return f"{self.sample}_{self.aligner}_aligned.{self.format}" # {{/docs-fragment dataclasses}} # ## Tasks # # We define a series of tasks to perform the following operations: # 1. Fetch assets from remote URLs # 2. Perform quality filtering and preprocessing using FastP # 3. Generate Bowtie2 index files from a reference genome # 4. Perform alignment using Bowtie2 on a filtered sample # # The first task fetches the reference genome and sequencing reads. It is cached # so that re-runs skip the download step. # {{docs-fragment fetch_assets}} @fetch_env.task async def fetch_assets( ref_url: str, read_urls: List[str] ) -> tuple[Reference, List[Reads]]: """ Fetch assets from remote URLs. """ # Download reference genome ref_dir = Path("/tmp/reference_genome") ref_dir.mkdir(exist_ok=True, parents=True) ref = fetch_file(ref_url, str(ref_dir)) ref_obj = Reference( ref_name=ref.name, ref_dir=await Dir.from_local(str(ref_dir)), ) # Download sequencing reads dl_loc = Path("/tmp/reads") dl_loc.mkdir(exist_ok=True, parents=True) samples: dict[str, Reads] = {} for url in read_urls: fp = fetch_file(url, str(dl_loc)) sample = fp.stem.split("_")[0] if sample not in samples: samples[sample] = Reads(sample=sample) if ".fastq.gz" in fp.name or "fasta" in fp.name: mate = fp.name.strip(".fastq.gz").strip(".filt").split("_")[-1] if "1" in mate: samples[sample].read1 = await File.from_local(str(fp)) elif "2" in mate: samples[sample].read2 = await File.from_local(str(fp)) return ref_obj, list(samples.values()) # {{/docs-fragment fetch_assets}} # The second task performs quality filtering and preprocessing using FastP on a Reads object. # FastP is a performant tool for removing duplicate or low-quality reads. We increase # the memory request for this task so FastP can efficiently process reads from larger files. # {{docs-fragment pyfastp}} @fastp_env.task async def pyfastp(rs: Reads) -> Reads: """ Perform quality filtering and preprocessing using Fastp on a Reads object. Args: rs (Reads): A Reads object containing raw sequencing data to be processed. Returns: Reads: A Reads object representing the filtered and preprocessed data. """ ldir = Path(tempfile.mkdtemp()) samp = Reads(rs.sample) o1, o2 = samp.get_read_fnames() o1p = ldir / o1 o2p = ldir / o2 assert rs.read1 is not None and rs.read2 is not None r1 = await rs.read1.download() r2 = await rs.read2.download() cmd = [ "fastp", "-i", str(r1), "-I", str(r2), "-o", str(o1p), "-O", str(o2p), ] subprocess.run(cmd, check=True) samp.read1 = await File.from_local(str(o1p)) samp.read2 = await File.from_local(str(o2p)) return samp # {{/docs-fragment pyfastp}} # Next, we define a task to generate Bowtie2 index files from a reference genome. As the index # for a given tool and reference seldom changes, we cache this task. # {{docs-fragment bowtie2_index}} @index_env.task async def bowtie2_index(ref: Reference) -> Reference: """ Generate Bowtie2 index files from a reference genome. Args: ref (Reference): A Reference object representing the reference genome. Returns: Reference: The same reference object with the index_name and indexed_with attributes set. """ ref_dir = await ref.ref_dir.download() idx_name = "bt2_idx" cmd = [ "bowtie2-build", str(Path(str(ref_dir)) / ref.ref_name), str(Path(str(ref_dir)) / idx_name), ] subprocess.run(cmd, check=True) return Reference( ref.ref_name, await Dir.from_local(str(ref_dir)), idx_name, "bowtie2", ) # {{/docs-fragment bowtie2_index}} # The next task performs paired-end alignment using Bowtie 2 on a single sample. # {{docs-fragment bowtie2_align}} @align_env.task async def bowtie2_align_paired_reads(idx: Reference, fs: Reads) -> Alignment: """ Perform paired-end alignment using Bowtie 2 on a filtered sample. Args: idx (Reference): A Reference object containing the Bowtie 2 index. fs (Reads): A filtered Reads object containing sample data to be aligned. Returns: Alignment: An Alignment object representing the alignment result. """ assert idx.indexed_with == "bowtie2", "Reference index must be generated with bowtie2" assert idx.index_name is not None assert fs.read1 is not None and fs.read2 is not None ref_dir = await idx.ref_dir.download() r1 = await fs.read1.download() r2 = await fs.read2.download() ldir = Path(tempfile.mkdtemp()) alignment = Alignment(fs.sample, "bowtie2", "sam") al = ldir / alignment.get_alignment_fname() cmd = [ "bowtie2", "-x", str(Path(str(ref_dir)) / idx.index_name), "-1", str(r1), "-2", str(r2), "-S", str(al), ] subprocess.run(cmd, check=True) alignment.alignment = await File.from_local(str(al)) return alignment # {{/docs-fragment bowtie2_align}} # In place of the v1 `@dynamic` workflow, we use a plain async task with `asyncio.gather` # to run alignments for all samples in parallel. @base_env.task async def bowtie2_align_samples( idx: Reference, samples: List[Reads] ) -> List[Alignment]: """ Process samples through bowtie2 in parallel. Args: idx (Reference): A Reference object containing the Bowtie 2 index. samples (List[Reads]): A list of Reads objects to be aligned. Returns: List[Alignment]: A list of Alignment objects representing the alignment results. """ tasks = [bowtie2_align_paired_reads(idx=idx, fs=sample) for sample in samples] return list(await asyncio.gather(*tasks)) # ## End-to-End Workflow # # We tie everything together in a final task that fetches assets, filters them, generates # an index, and aligns the samples. In place of the v1 `@workflow`, we use a top-level # `@base_env.task`. Parallelism across samples is achieved with `asyncio.gather`. # {{docs-fragment workflow}} @base_env.task async def alignment_wf() -> List[Alignment]: # Prepare raw samples from remote URLs ref, samples = await fetch_assets( ref_url="https://github.com/unionai-oss/unionbio/raw/main/tests/assets/references/GRCh38_short.fasta", read_urls=[ "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_1.fastq.gz", "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_2.fastq.gz", ], ) # Filter all samples in parallel filtered_samples = list( await asyncio.gather(*[pyfastp(rs=s) for s in samples]) ) # Generate a bowtie2 index or load it from cache bowtie2_idx = await bowtie2_index(ref=ref) # Generate alignments using bowtie2 sams = await bowtie2_align_samples(idx=bowtie2_idx, samples=filtered_samples) return sams # {{/docs-fragment workflow}} # You can now run the workflow using the command in the dropdown at the top of the page! if __name__ == "__main__": flyte.init_from_config() run = flyte.run(alignment_wf) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_alignment/genomic_alignment.py* ## Quality filtering with fastp `pyfastp` removes duplicate and low-quality reads. It requests extra memory so it can process larger read files efficiently. ``` # # Genomic Alignment # # This tutorial demonstrates how to use Flyte to build a workflow that # performs genomic alignment on sequencing data. The workflow takes as input # a reference genome and raw sequencing data, performs quality filtering and # preprocessing on the raw data, generates an index for the reference genome, # and aligns the filtered data to the reference genome using the Bowtie 2 aligner. # {{run-on-union}} # The tutorial is divided into the following sections: # 1. Define the container image # 2. Define the data classes # 3. Define the tasks # 4. Define the workflow # /// script # requires-python = "3.12" # dependencies = [ # "flyte", # "requests", # ] # main = "alignment_wf" # params = "" # /// import asyncio import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import List import requests import flyte from flyte.io import Dir, File # ## Defining a Container Image # # We define a custom container image using `flyte.Image`. Since we need bioinformatics # tools โ€” `fastp` for quality filtering and `bowtie2` for alignment โ€” we install them # via apt. This approach replaces the v1 `ImageSpec` with conda channels. # {{docs-fragment image}} main_img = ( flyte.Image.from_uv_script( __file__, name="alignment-tutorial", ) .with_apt_packages("fastp", "bowtie2") ) # {{/docs-fragment image}} # We define per-task environments with different resource requirements, then a # top-level `base_env` that declares all of them as dependencies (required because # `alignment_wf` and `bowtie2_align_samples` call tasks that live in those environments). # {{docs-fragment envs}} fetch_env = flyte.TaskEnvironment( name="alignment-tutorial-fetch", image=main_img, cache="auto", ) fastp_env = flyte.TaskEnvironment( name="alignment-tutorial-fastp", image=main_img, resources=flyte.Resources(memory="2Gi"), ) index_env = flyte.TaskEnvironment( name="alignment-tutorial-index", image=main_img, resources=flyte.Resources(memory="10Gi"), cache="auto", ) align_env = flyte.TaskEnvironment( name="alignment-tutorial-align", image=main_img, resources=flyte.Resources(cpu=2, memory="10Gi"), ) base_env = flyte.TaskEnvironment( name="alignment-tutorial", image=main_img, depends_on=[fetch_env, fastp_env, index_env, align_env], ) # {{/docs-fragment envs}} # ## Defining Data Classes # # We define three data classes to represent the reference genome, sequencing reads, # and alignment results. We'll first define a convenience function to download files, # which we'll use within the fetch task to materialize assets from their remote locations. def fetch_file(url: str, local_dir: str) -> Path: """ Downloads a file from the specified URL. Args: url (str): The URL of the file to download. local_dir (str): The directory where you would like this file saved. Returns: Path: The local path to the file. Raises: requests.HTTPError: If an HTTP error occurs while downloading the file. """ url_parts = url.split("/") fname = url_parts[-1] local_path = Path(local_dir) / fname response = requests.get(url) with open(local_path, "wb") as file: file.write(response.content) return local_path # Reference genomes are used extensively throughout bioinformatics workflows. We define a # `Reference` data class to represent a reference genome and its associated index files. # {{docs-fragment dataclasses}} @dataclass class Reference: """ Represents a reference FASTA and associated index files. Attributes: ref_name (str): Name or identifier of the reference file. ref_dir (Dir): Directory containing the reference and any index files. index_name (str): Index string to pass to tools requiring it. indexed_with (str): Name of tool used to create the index. """ ref_name: str ref_dir: Dir index_name: str | None = None indexed_with: str | None = None # Sequencing reads are the raw data generated from a sequencing experiment. @dataclass class Reads: """ Represents a sequencing reads sample via its associated FastQ files. Attributes: sample (str): The name or identifier of the raw sequencing sample. read1 (File): A File object representing the path to the raw R1 read file. read2 (File): A File object representing the path to the raw R2 read file. """ sample: str read1: File | None = None read2: File | None = None def get_read_fnames(self): return ( f"{self.sample}_1.fastq.gz", f"{self.sample}_2.fastq.gz", ) # Finally, we define an `Alignment` data class to represent an alignment file. @dataclass class Alignment: """ Represents an alignment file and its associated sample. Attributes: sample (str): The name or identifier of the sample. aligner (str): The name of the aligner used to generate the alignment file. format (str): The format of the alignment file (e.g., SAM, BAM). alignment (File): A File object representing the path to the alignment file. """ sample: str aligner: str format: str | None = None alignment: File | None = None def get_alignment_fname(self): return f"{self.sample}_{self.aligner}_aligned.{self.format}" # {{/docs-fragment dataclasses}} # ## Tasks # # We define a series of tasks to perform the following operations: # 1. Fetch assets from remote URLs # 2. Perform quality filtering and preprocessing using FastP # 3. Generate Bowtie2 index files from a reference genome # 4. Perform alignment using Bowtie2 on a filtered sample # # The first task fetches the reference genome and sequencing reads. It is cached # so that re-runs skip the download step. # {{docs-fragment fetch_assets}} @fetch_env.task async def fetch_assets( ref_url: str, read_urls: List[str] ) -> tuple[Reference, List[Reads]]: """ Fetch assets from remote URLs. """ # Download reference genome ref_dir = Path("/tmp/reference_genome") ref_dir.mkdir(exist_ok=True, parents=True) ref = fetch_file(ref_url, str(ref_dir)) ref_obj = Reference( ref_name=ref.name, ref_dir=await Dir.from_local(str(ref_dir)), ) # Download sequencing reads dl_loc = Path("/tmp/reads") dl_loc.mkdir(exist_ok=True, parents=True) samples: dict[str, Reads] = {} for url in read_urls: fp = fetch_file(url, str(dl_loc)) sample = fp.stem.split("_")[0] if sample not in samples: samples[sample] = Reads(sample=sample) if ".fastq.gz" in fp.name or "fasta" in fp.name: mate = fp.name.strip(".fastq.gz").strip(".filt").split("_")[-1] if "1" in mate: samples[sample].read1 = await File.from_local(str(fp)) elif "2" in mate: samples[sample].read2 = await File.from_local(str(fp)) return ref_obj, list(samples.values()) # {{/docs-fragment fetch_assets}} # The second task performs quality filtering and preprocessing using FastP on a Reads object. # FastP is a performant tool for removing duplicate or low-quality reads. We increase # the memory request for this task so FastP can efficiently process reads from larger files. # {{docs-fragment pyfastp}} @fastp_env.task async def pyfastp(rs: Reads) -> Reads: """ Perform quality filtering and preprocessing using Fastp on a Reads object. Args: rs (Reads): A Reads object containing raw sequencing data to be processed. Returns: Reads: A Reads object representing the filtered and preprocessed data. """ ldir = Path(tempfile.mkdtemp()) samp = Reads(rs.sample) o1, o2 = samp.get_read_fnames() o1p = ldir / o1 o2p = ldir / o2 assert rs.read1 is not None and rs.read2 is not None r1 = await rs.read1.download() r2 = await rs.read2.download() cmd = [ "fastp", "-i", str(r1), "-I", str(r2), "-o", str(o1p), "-O", str(o2p), ] subprocess.run(cmd, check=True) samp.read1 = await File.from_local(str(o1p)) samp.read2 = await File.from_local(str(o2p)) return samp # {{/docs-fragment pyfastp}} # Next, we define a task to generate Bowtie2 index files from a reference genome. As the index # for a given tool and reference seldom changes, we cache this task. # {{docs-fragment bowtie2_index}} @index_env.task async def bowtie2_index(ref: Reference) -> Reference: """ Generate Bowtie2 index files from a reference genome. Args: ref (Reference): A Reference object representing the reference genome. Returns: Reference: The same reference object with the index_name and indexed_with attributes set. """ ref_dir = await ref.ref_dir.download() idx_name = "bt2_idx" cmd = [ "bowtie2-build", str(Path(str(ref_dir)) / ref.ref_name), str(Path(str(ref_dir)) / idx_name), ] subprocess.run(cmd, check=True) return Reference( ref.ref_name, await Dir.from_local(str(ref_dir)), idx_name, "bowtie2", ) # {{/docs-fragment bowtie2_index}} # The next task performs paired-end alignment using Bowtie 2 on a single sample. # {{docs-fragment bowtie2_align}} @align_env.task async def bowtie2_align_paired_reads(idx: Reference, fs: Reads) -> Alignment: """ Perform paired-end alignment using Bowtie 2 on a filtered sample. Args: idx (Reference): A Reference object containing the Bowtie 2 index. fs (Reads): A filtered Reads object containing sample data to be aligned. Returns: Alignment: An Alignment object representing the alignment result. """ assert idx.indexed_with == "bowtie2", "Reference index must be generated with bowtie2" assert idx.index_name is not None assert fs.read1 is not None and fs.read2 is not None ref_dir = await idx.ref_dir.download() r1 = await fs.read1.download() r2 = await fs.read2.download() ldir = Path(tempfile.mkdtemp()) alignment = Alignment(fs.sample, "bowtie2", "sam") al = ldir / alignment.get_alignment_fname() cmd = [ "bowtie2", "-x", str(Path(str(ref_dir)) / idx.index_name), "-1", str(r1), "-2", str(r2), "-S", str(al), ] subprocess.run(cmd, check=True) alignment.alignment = await File.from_local(str(al)) return alignment # {{/docs-fragment bowtie2_align}} # In place of the v1 `@dynamic` workflow, we use a plain async task with `asyncio.gather` # to run alignments for all samples in parallel. @base_env.task async def bowtie2_align_samples( idx: Reference, samples: List[Reads] ) -> List[Alignment]: """ Process samples through bowtie2 in parallel. Args: idx (Reference): A Reference object containing the Bowtie 2 index. samples (List[Reads]): A list of Reads objects to be aligned. Returns: List[Alignment]: A list of Alignment objects representing the alignment results. """ tasks = [bowtie2_align_paired_reads(idx=idx, fs=sample) for sample in samples] return list(await asyncio.gather(*tasks)) # ## End-to-End Workflow # # We tie everything together in a final task that fetches assets, filters them, generates # an index, and aligns the samples. In place of the v1 `@workflow`, we use a top-level # `@base_env.task`. Parallelism across samples is achieved with `asyncio.gather`. # {{docs-fragment workflow}} @base_env.task async def alignment_wf() -> List[Alignment]: # Prepare raw samples from remote URLs ref, samples = await fetch_assets( ref_url="https://github.com/unionai-oss/unionbio/raw/main/tests/assets/references/GRCh38_short.fasta", read_urls=[ "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_1.fastq.gz", "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_2.fastq.gz", ], ) # Filter all samples in parallel filtered_samples = list( await asyncio.gather(*[pyfastp(rs=s) for s in samples]) ) # Generate a bowtie2 index or load it from cache bowtie2_idx = await bowtie2_index(ref=ref) # Generate alignments using bowtie2 sams = await bowtie2_align_samples(idx=bowtie2_idx, samples=filtered_samples) return sams # {{/docs-fragment workflow}} # You can now run the workflow using the command in the dropdown at the top of the page! if __name__ == "__main__": flyte.init_from_config() run = flyte.run(alignment_wf) print(run.url) run.wait() CODE1 # # Genomic Alignment # # This tutorial demonstrates how to use Flyte to build a workflow that # performs genomic alignment on sequencing data. The workflow takes as input # a reference genome and raw sequencing data, performs quality filtering and # preprocessing on the raw data, generates an index for the reference genome, # and aligns the filtered data to the reference genome using the Bowtie 2 aligner. # {{run-on-union}} # The tutorial is divided into the following sections: # 1. Define the container image # 2. Define the data classes # 3. Define the tasks # 4. Define the workflow # /// script # requires-python = "3.12" # dependencies = [ # "flyte", # "requests", # ] # main = "alignment_wf" # params = "" # /// import asyncio import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import List import requests import flyte from flyte.io import Dir, File # ## Defining a Container Image # # We define a custom container image using `flyte.Image`. Since we need bioinformatics # tools โ€” `fastp` for quality filtering and `bowtie2` for alignment โ€” we install them # via apt. This approach replaces the v1 `ImageSpec` with conda channels. # {{docs-fragment image}} main_img = ( flyte.Image.from_uv_script( __file__, name="alignment-tutorial", ) .with_apt_packages("fastp", "bowtie2") ) # {{/docs-fragment image}} # We define per-task environments with different resource requirements, then a # top-level `base_env` that declares all of them as dependencies (required because # `alignment_wf` and `bowtie2_align_samples` call tasks that live in those environments). # {{docs-fragment envs}} fetch_env = flyte.TaskEnvironment( name="alignment-tutorial-fetch", image=main_img, cache="auto", ) fastp_env = flyte.TaskEnvironment( name="alignment-tutorial-fastp", image=main_img, resources=flyte.Resources(memory="2Gi"), ) index_env = flyte.TaskEnvironment( name="alignment-tutorial-index", image=main_img, resources=flyte.Resources(memory="10Gi"), cache="auto", ) align_env = flyte.TaskEnvironment( name="alignment-tutorial-align", image=main_img, resources=flyte.Resources(cpu=2, memory="10Gi"), ) base_env = flyte.TaskEnvironment( name="alignment-tutorial", image=main_img, depends_on=[fetch_env, fastp_env, index_env, align_env], ) # {{/docs-fragment envs}} # ## Defining Data Classes # # We define three data classes to represent the reference genome, sequencing reads, # and alignment results. We'll first define a convenience function to download files, # which we'll use within the fetch task to materialize assets from their remote locations. def fetch_file(url: str, local_dir: str) -> Path: """ Downloads a file from the specified URL. Args: url (str): The URL of the file to download. local_dir (str): The directory where you would like this file saved. Returns: Path: The local path to the file. Raises: requests.HTTPError: If an HTTP error occurs while downloading the file. """ url_parts = url.split("/") fname = url_parts[-1] local_path = Path(local_dir) / fname response = requests.get(url) with open(local_path, "wb") as file: file.write(response.content) return local_path # Reference genomes are used extensively throughout bioinformatics workflows. We define a # `Reference` data class to represent a reference genome and its associated index files. # {{docs-fragment dataclasses}} @dataclass class Reference: """ Represents a reference FASTA and associated index files. Attributes: ref_name (str): Name or identifier of the reference file. ref_dir (Dir): Directory containing the reference and any index files. index_name (str): Index string to pass to tools requiring it. indexed_with (str): Name of tool used to create the index. """ ref_name: str ref_dir: Dir index_name: str | None = None indexed_with: str | None = None # Sequencing reads are the raw data generated from a sequencing experiment. @dataclass class Reads: """ Represents a sequencing reads sample via its associated FastQ files. Attributes: sample (str): The name or identifier of the raw sequencing sample. read1 (File): A File object representing the path to the raw R1 read file. read2 (File): A File object representing the path to the raw R2 read file. """ sample: str read1: File | None = None read2: File | None = None def get_read_fnames(self): return ( f"{self.sample}_1.fastq.gz", f"{self.sample}_2.fastq.gz", ) # Finally, we define an `Alignment` data class to represent an alignment file. @dataclass class Alignment: """ Represents an alignment file and its associated sample. Attributes: sample (str): The name or identifier of the sample. aligner (str): The name of the aligner used to generate the alignment file. format (str): The format of the alignment file (e.g., SAM, BAM). alignment (File): A File object representing the path to the alignment file. """ sample: str aligner: str format: str | None = None alignment: File | None = None def get_alignment_fname(self): return f"{self.sample}_{self.aligner}_aligned.{self.format}" # {{/docs-fragment dataclasses}} # ## Tasks # # We define a series of tasks to perform the following operations: # 1. Fetch assets from remote URLs # 2. Perform quality filtering and preprocessing using FastP # 3. Generate Bowtie2 index files from a reference genome # 4. Perform alignment using Bowtie2 on a filtered sample # # The first task fetches the reference genome and sequencing reads. It is cached # so that re-runs skip the download step. # {{docs-fragment fetch_assets}} @fetch_env.task async def fetch_assets( ref_url: str, read_urls: List[str] ) -> tuple[Reference, List[Reads]]: """ Fetch assets from remote URLs. """ # Download reference genome ref_dir = Path("/tmp/reference_genome") ref_dir.mkdir(exist_ok=True, parents=True) ref = fetch_file(ref_url, str(ref_dir)) ref_obj = Reference( ref_name=ref.name, ref_dir=await Dir.from_local(str(ref_dir)), ) # Download sequencing reads dl_loc = Path("/tmp/reads") dl_loc.mkdir(exist_ok=True, parents=True) samples: dict[str, Reads] = {} for url in read_urls: fp = fetch_file(url, str(dl_loc)) sample = fp.stem.split("_")[0] if sample not in samples: samples[sample] = Reads(sample=sample) if ".fastq.gz" in fp.name or "fasta" in fp.name: mate = fp.name.strip(".fastq.gz").strip(".filt").split("_")[-1] if "1" in mate: samples[sample].read1 = await File.from_local(str(fp)) elif "2" in mate: samples[sample].read2 = await File.from_local(str(fp)) return ref_obj, list(samples.values()) # {{/docs-fragment fetch_assets}} # The second task performs quality filtering and preprocessing using FastP on a Reads object. # FastP is a performant tool for removing duplicate or low-quality reads. We increase # the memory request for this task so FastP can efficiently process reads from larger files. # {{docs-fragment pyfastp}} @fastp_env.task async def pyfastp(rs: Reads) -> Reads: """ Perform quality filtering and preprocessing using Fastp on a Reads object. Args: rs (Reads): A Reads object containing raw sequencing data to be processed. Returns: Reads: A Reads object representing the filtered and preprocessed data. """ ldir = Path(tempfile.mkdtemp()) samp = Reads(rs.sample) o1, o2 = samp.get_read_fnames() o1p = ldir / o1 o2p = ldir / o2 assert rs.read1 is not None and rs.read2 is not None r1 = await rs.read1.download() r2 = await rs.read2.download() cmd = [ "fastp", "-i", str(r1), "-I", str(r2), "-o", str(o1p), "-O", str(o2p), ] subprocess.run(cmd, check=True) samp.read1 = await File.from_local(str(o1p)) samp.read2 = await File.from_local(str(o2p)) return samp # {{/docs-fragment pyfastp}} # Next, we define a task to generate Bowtie2 index files from a reference genome. As the index # for a given tool and reference seldom changes, we cache this task. # {{docs-fragment bowtie2_index}} @index_env.task async def bowtie2_index(ref: Reference) -> Reference: """ Generate Bowtie2 index files from a reference genome. Args: ref (Reference): A Reference object representing the reference genome. Returns: Reference: The same reference object with the index_name and indexed_with attributes set. """ ref_dir = await ref.ref_dir.download() idx_name = "bt2_idx" cmd = [ "bowtie2-build", str(Path(str(ref_dir)) / ref.ref_name), str(Path(str(ref_dir)) / idx_name), ] subprocess.run(cmd, check=True) return Reference( ref.ref_name, await Dir.from_local(str(ref_dir)), idx_name, "bowtie2", ) # {{/docs-fragment bowtie2_index}} # The next task performs paired-end alignment using Bowtie 2 on a single sample. # {{docs-fragment bowtie2_align}} @align_env.task async def bowtie2_align_paired_reads(idx: Reference, fs: Reads) -> Alignment: """ Perform paired-end alignment using Bowtie 2 on a filtered sample. Args: idx (Reference): A Reference object containing the Bowtie 2 index. fs (Reads): A filtered Reads object containing sample data to be aligned. Returns: Alignment: An Alignment object representing the alignment result. """ assert idx.indexed_with == "bowtie2", "Reference index must be generated with bowtie2" assert idx.index_name is not None assert fs.read1 is not None and fs.read2 is not None ref_dir = await idx.ref_dir.download() r1 = await fs.read1.download() r2 = await fs.read2.download() ldir = Path(tempfile.mkdtemp()) alignment = Alignment(fs.sample, "bowtie2", "sam") al = ldir / alignment.get_alignment_fname() cmd = [ "bowtie2", "-x", str(Path(str(ref_dir)) / idx.index_name), "-1", str(r1), "-2", str(r2), "-S", str(al), ] subprocess.run(cmd, check=True) alignment.alignment = await File.from_local(str(al)) return alignment # {{/docs-fragment bowtie2_align}} # In place of the v1 `@dynamic` workflow, we use a plain async task with `asyncio.gather` # to run alignments for all samples in parallel. @base_env.task async def bowtie2_align_samples( idx: Reference, samples: List[Reads] ) -> List[Alignment]: """ Process samples through bowtie2 in parallel. Args: idx (Reference): A Reference object containing the Bowtie 2 index. samples (List[Reads]): A list of Reads objects to be aligned. Returns: List[Alignment]: A list of Alignment objects representing the alignment results. """ tasks = [bowtie2_align_paired_reads(idx=idx, fs=sample) for sample in samples] return list(await asyncio.gather(*tasks)) # ## End-to-End Workflow # # We tie everything together in a final task that fetches assets, filters them, generates # an index, and aligns the samples. In place of the v1 `@workflow`, we use a top-level # `@base_env.task`. Parallelism across samples is achieved with `asyncio.gather`. # {{docs-fragment workflow}} @base_env.task async def alignment_wf() -> List[Alignment]: # Prepare raw samples from remote URLs ref, samples = await fetch_assets( ref_url="https://github.com/unionai-oss/unionbio/raw/main/tests/assets/references/GRCh38_short.fasta", read_urls=[ "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_1.fastq.gz", "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_2.fastq.gz", ], ) # Filter all samples in parallel filtered_samples = list( await asyncio.gather(*[pyfastp(rs=s) for s in samples]) ) # Generate a bowtie2 index or load it from cache bowtie2_idx = await bowtie2_index(ref=ref) # Generate alignments using bowtie2 sams = await bowtie2_align_samples(idx=bowtie2_idx, samples=filtered_samples) return sams # {{/docs-fragment workflow}} # You can now run the workflow using the command in the dropdown at the top of the page! if __name__ == "__main__": flyte.init_from_config() run = flyte.run(alignment_wf) print(run.url) run.wait() CODE2 # # Genomic Alignment # # This tutorial demonstrates how to use Flyte to build a workflow that # performs genomic alignment on sequencing data. The workflow takes as input # a reference genome and raw sequencing data, performs quality filtering and # preprocessing on the raw data, generates an index for the reference genome, # and aligns the filtered data to the reference genome using the Bowtie 2 aligner. # {{run-on-union}} # The tutorial is divided into the following sections: # 1. Define the container image # 2. Define the data classes # 3. Define the tasks # 4. Define the workflow # /// script # requires-python = "3.12" # dependencies = [ # "flyte", # "requests", # ] # main = "alignment_wf" # params = "" # /// import asyncio import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import List import requests import flyte from flyte.io import Dir, File # ## Defining a Container Image # # We define a custom container image using `flyte.Image`. Since we need bioinformatics # tools โ€” `fastp` for quality filtering and `bowtie2` for alignment โ€” we install them # via apt. This approach replaces the v1 `ImageSpec` with conda channels. # {{docs-fragment image}} main_img = ( flyte.Image.from_uv_script( __file__, name="alignment-tutorial", ) .with_apt_packages("fastp", "bowtie2") ) # {{/docs-fragment image}} # We define per-task environments with different resource requirements, then a # top-level `base_env` that declares all of them as dependencies (required because # `alignment_wf` and `bowtie2_align_samples` call tasks that live in those environments). # {{docs-fragment envs}} fetch_env = flyte.TaskEnvironment( name="alignment-tutorial-fetch", image=main_img, cache="auto", ) fastp_env = flyte.TaskEnvironment( name="alignment-tutorial-fastp", image=main_img, resources=flyte.Resources(memory="2Gi"), ) index_env = flyte.TaskEnvironment( name="alignment-tutorial-index", image=main_img, resources=flyte.Resources(memory="10Gi"), cache="auto", ) align_env = flyte.TaskEnvironment( name="alignment-tutorial-align", image=main_img, resources=flyte.Resources(cpu=2, memory="10Gi"), ) base_env = flyte.TaskEnvironment( name="alignment-tutorial", image=main_img, depends_on=[fetch_env, fastp_env, index_env, align_env], ) # {{/docs-fragment envs}} # ## Defining Data Classes # # We define three data classes to represent the reference genome, sequencing reads, # and alignment results. We'll first define a convenience function to download files, # which we'll use within the fetch task to materialize assets from their remote locations. def fetch_file(url: str, local_dir: str) -> Path: """ Downloads a file from the specified URL. Args: url (str): The URL of the file to download. local_dir (str): The directory where you would like this file saved. Returns: Path: The local path to the file. Raises: requests.HTTPError: If an HTTP error occurs while downloading the file. """ url_parts = url.split("/") fname = url_parts[-1] local_path = Path(local_dir) / fname response = requests.get(url) with open(local_path, "wb") as file: file.write(response.content) return local_path # Reference genomes are used extensively throughout bioinformatics workflows. We define a # `Reference` data class to represent a reference genome and its associated index files. # {{docs-fragment dataclasses}} @dataclass class Reference: """ Represents a reference FASTA and associated index files. Attributes: ref_name (str): Name or identifier of the reference file. ref_dir (Dir): Directory containing the reference and any index files. index_name (str): Index string to pass to tools requiring it. indexed_with (str): Name of tool used to create the index. """ ref_name: str ref_dir: Dir index_name: str | None = None indexed_with: str | None = None # Sequencing reads are the raw data generated from a sequencing experiment. @dataclass class Reads: """ Represents a sequencing reads sample via its associated FastQ files. Attributes: sample (str): The name or identifier of the raw sequencing sample. read1 (File): A File object representing the path to the raw R1 read file. read2 (File): A File object representing the path to the raw R2 read file. """ sample: str read1: File | None = None read2: File | None = None def get_read_fnames(self): return ( f"{self.sample}_1.fastq.gz", f"{self.sample}_2.fastq.gz", ) # Finally, we define an `Alignment` data class to represent an alignment file. @dataclass class Alignment: """ Represents an alignment file and its associated sample. Attributes: sample (str): The name or identifier of the sample. aligner (str): The name of the aligner used to generate the alignment file. format (str): The format of the alignment file (e.g., SAM, BAM). alignment (File): A File object representing the path to the alignment file. """ sample: str aligner: str format: str | None = None alignment: File | None = None def get_alignment_fname(self): return f"{self.sample}_{self.aligner}_aligned.{self.format}" # {{/docs-fragment dataclasses}} # ## Tasks # # We define a series of tasks to perform the following operations: # 1. Fetch assets from remote URLs # 2. Perform quality filtering and preprocessing using FastP # 3. Generate Bowtie2 index files from a reference genome # 4. Perform alignment using Bowtie2 on a filtered sample # # The first task fetches the reference genome and sequencing reads. It is cached # so that re-runs skip the download step. # {{docs-fragment fetch_assets}} @fetch_env.task async def fetch_assets( ref_url: str, read_urls: List[str] ) -> tuple[Reference, List[Reads]]: """ Fetch assets from remote URLs. """ # Download reference genome ref_dir = Path("/tmp/reference_genome") ref_dir.mkdir(exist_ok=True, parents=True) ref = fetch_file(ref_url, str(ref_dir)) ref_obj = Reference( ref_name=ref.name, ref_dir=await Dir.from_local(str(ref_dir)), ) # Download sequencing reads dl_loc = Path("/tmp/reads") dl_loc.mkdir(exist_ok=True, parents=True) samples: dict[str, Reads] = {} for url in read_urls: fp = fetch_file(url, str(dl_loc)) sample = fp.stem.split("_")[0] if sample not in samples: samples[sample] = Reads(sample=sample) if ".fastq.gz" in fp.name or "fasta" in fp.name: mate = fp.name.strip(".fastq.gz").strip(".filt").split("_")[-1] if "1" in mate: samples[sample].read1 = await File.from_local(str(fp)) elif "2" in mate: samples[sample].read2 = await File.from_local(str(fp)) return ref_obj, list(samples.values()) # {{/docs-fragment fetch_assets}} # The second task performs quality filtering and preprocessing using FastP on a Reads object. # FastP is a performant tool for removing duplicate or low-quality reads. We increase # the memory request for this task so FastP can efficiently process reads from larger files. # {{docs-fragment pyfastp}} @fastp_env.task async def pyfastp(rs: Reads) -> Reads: """ Perform quality filtering and preprocessing using Fastp on a Reads object. Args: rs (Reads): A Reads object containing raw sequencing data to be processed. Returns: Reads: A Reads object representing the filtered and preprocessed data. """ ldir = Path(tempfile.mkdtemp()) samp = Reads(rs.sample) o1, o2 = samp.get_read_fnames() o1p = ldir / o1 o2p = ldir / o2 assert rs.read1 is not None and rs.read2 is not None r1 = await rs.read1.download() r2 = await rs.read2.download() cmd = [ "fastp", "-i", str(r1), "-I", str(r2), "-o", str(o1p), "-O", str(o2p), ] subprocess.run(cmd, check=True) samp.read1 = await File.from_local(str(o1p)) samp.read2 = await File.from_local(str(o2p)) return samp # {{/docs-fragment pyfastp}} # Next, we define a task to generate Bowtie2 index files from a reference genome. As the index # for a given tool and reference seldom changes, we cache this task. # {{docs-fragment bowtie2_index}} @index_env.task async def bowtie2_index(ref: Reference) -> Reference: """ Generate Bowtie2 index files from a reference genome. Args: ref (Reference): A Reference object representing the reference genome. Returns: Reference: The same reference object with the index_name and indexed_with attributes set. """ ref_dir = await ref.ref_dir.download() idx_name = "bt2_idx" cmd = [ "bowtie2-build", str(Path(str(ref_dir)) / ref.ref_name), str(Path(str(ref_dir)) / idx_name), ] subprocess.run(cmd, check=True) return Reference( ref.ref_name, await Dir.from_local(str(ref_dir)), idx_name, "bowtie2", ) # {{/docs-fragment bowtie2_index}} # The next task performs paired-end alignment using Bowtie 2 on a single sample. # {{docs-fragment bowtie2_align}} @align_env.task async def bowtie2_align_paired_reads(idx: Reference, fs: Reads) -> Alignment: """ Perform paired-end alignment using Bowtie 2 on a filtered sample. Args: idx (Reference): A Reference object containing the Bowtie 2 index. fs (Reads): A filtered Reads object containing sample data to be aligned. Returns: Alignment: An Alignment object representing the alignment result. """ assert idx.indexed_with == "bowtie2", "Reference index must be generated with bowtie2" assert idx.index_name is not None assert fs.read1 is not None and fs.read2 is not None ref_dir = await idx.ref_dir.download() r1 = await fs.read1.download() r2 = await fs.read2.download() ldir = Path(tempfile.mkdtemp()) alignment = Alignment(fs.sample, "bowtie2", "sam") al = ldir / alignment.get_alignment_fname() cmd = [ "bowtie2", "-x", str(Path(str(ref_dir)) / idx.index_name), "-1", str(r1), "-2", str(r2), "-S", str(al), ] subprocess.run(cmd, check=True) alignment.alignment = await File.from_local(str(al)) return alignment # {{/docs-fragment bowtie2_align}} # In place of the v1 `@dynamic` workflow, we use a plain async task with `asyncio.gather` # to run alignments for all samples in parallel. @base_env.task async def bowtie2_align_samples( idx: Reference, samples: List[Reads] ) -> List[Alignment]: """ Process samples through bowtie2 in parallel. Args: idx (Reference): A Reference object containing the Bowtie 2 index. samples (List[Reads]): A list of Reads objects to be aligned. Returns: List[Alignment]: A list of Alignment objects representing the alignment results. """ tasks = [bowtie2_align_paired_reads(idx=idx, fs=sample) for sample in samples] return list(await asyncio.gather(*tasks)) # ## End-to-End Workflow # # We tie everything together in a final task that fetches assets, filters them, generates # an index, and aligns the samples. In place of the v1 `@workflow`, we use a top-level # `@base_env.task`. Parallelism across samples is achieved with `asyncio.gather`. # {{docs-fragment workflow}} @base_env.task async def alignment_wf() -> List[Alignment]: # Prepare raw samples from remote URLs ref, samples = await fetch_assets( ref_url="https://github.com/unionai-oss/unionbio/raw/main/tests/assets/references/GRCh38_short.fasta", read_urls=[ "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_1.fastq.gz", "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_2.fastq.gz", ], ) # Filter all samples in parallel filtered_samples = list( await asyncio.gather(*[pyfastp(rs=s) for s in samples]) ) # Generate a bowtie2 index or load it from cache bowtie2_idx = await bowtie2_index(ref=ref) # Generate alignments using bowtie2 sams = await bowtie2_align_samples(idx=bowtie2_idx, samples=filtered_samples) return sams # {{/docs-fragment workflow}} # You can now run the workflow using the command in the dropdown at the top of the page! if __name__ == "__main__": flyte.init_from_config() run = flyte.run(alignment_wf) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_alignment/genomic_alignment.py* ## Orchestrate the workflow The top-level task fetches the assets, filters every sample in parallel, builds the index, and aligns all samples. Parallelism across samples is achieved with `asyncio.gather` rather than a separate `@dynamic` decorator. ``` # # Genomic Alignment # # This tutorial demonstrates how to use Flyte to build a workflow that # performs genomic alignment on sequencing data. The workflow takes as input # a reference genome and raw sequencing data, performs quality filtering and # preprocessing on the raw data, generates an index for the reference genome, # and aligns the filtered data to the reference genome using the Bowtie 2 aligner. # {{run-on-union}} # The tutorial is divided into the following sections: # 1. Define the container image # 2. Define the data classes # 3. Define the tasks # 4. Define the workflow # /// script # requires-python = "3.12" # dependencies = [ # "flyte", # "requests", # ] # main = "alignment_wf" # params = "" # /// import asyncio import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import List import requests import flyte from flyte.io import Dir, File # ## Defining a Container Image # # We define a custom container image using `flyte.Image`. Since we need bioinformatics # tools โ€” `fastp` for quality filtering and `bowtie2` for alignment โ€” we install them # via apt. This approach replaces the v1 `ImageSpec` with conda channels. # {{docs-fragment image}} main_img = ( flyte.Image.from_uv_script( __file__, name="alignment-tutorial", ) .with_apt_packages("fastp", "bowtie2") ) # {{/docs-fragment image}} # We define per-task environments with different resource requirements, then a # top-level `base_env` that declares all of them as dependencies (required because # `alignment_wf` and `bowtie2_align_samples` call tasks that live in those environments). # {{docs-fragment envs}} fetch_env = flyte.TaskEnvironment( name="alignment-tutorial-fetch", image=main_img, cache="auto", ) fastp_env = flyte.TaskEnvironment( name="alignment-tutorial-fastp", image=main_img, resources=flyte.Resources(memory="2Gi"), ) index_env = flyte.TaskEnvironment( name="alignment-tutorial-index", image=main_img, resources=flyte.Resources(memory="10Gi"), cache="auto", ) align_env = flyte.TaskEnvironment( name="alignment-tutorial-align", image=main_img, resources=flyte.Resources(cpu=2, memory="10Gi"), ) base_env = flyte.TaskEnvironment( name="alignment-tutorial", image=main_img, depends_on=[fetch_env, fastp_env, index_env, align_env], ) # {{/docs-fragment envs}} # ## Defining Data Classes # # We define three data classes to represent the reference genome, sequencing reads, # and alignment results. We'll first define a convenience function to download files, # which we'll use within the fetch task to materialize assets from their remote locations. def fetch_file(url: str, local_dir: str) -> Path: """ Downloads a file from the specified URL. Args: url (str): The URL of the file to download. local_dir (str): The directory where you would like this file saved. Returns: Path: The local path to the file. Raises: requests.HTTPError: If an HTTP error occurs while downloading the file. """ url_parts = url.split("/") fname = url_parts[-1] local_path = Path(local_dir) / fname response = requests.get(url) with open(local_path, "wb") as file: file.write(response.content) return local_path # Reference genomes are used extensively throughout bioinformatics workflows. We define a # `Reference` data class to represent a reference genome and its associated index files. # {{docs-fragment dataclasses}} @dataclass class Reference: """ Represents a reference FASTA and associated index files. Attributes: ref_name (str): Name or identifier of the reference file. ref_dir (Dir): Directory containing the reference and any index files. index_name (str): Index string to pass to tools requiring it. indexed_with (str): Name of tool used to create the index. """ ref_name: str ref_dir: Dir index_name: str | None = None indexed_with: str | None = None # Sequencing reads are the raw data generated from a sequencing experiment. @dataclass class Reads: """ Represents a sequencing reads sample via its associated FastQ files. Attributes: sample (str): The name or identifier of the raw sequencing sample. read1 (File): A File object representing the path to the raw R1 read file. read2 (File): A File object representing the path to the raw R2 read file. """ sample: str read1: File | None = None read2: File | None = None def get_read_fnames(self): return ( f"{self.sample}_1.fastq.gz", f"{self.sample}_2.fastq.gz", ) # Finally, we define an `Alignment` data class to represent an alignment file. @dataclass class Alignment: """ Represents an alignment file and its associated sample. Attributes: sample (str): The name or identifier of the sample. aligner (str): The name of the aligner used to generate the alignment file. format (str): The format of the alignment file (e.g., SAM, BAM). alignment (File): A File object representing the path to the alignment file. """ sample: str aligner: str format: str | None = None alignment: File | None = None def get_alignment_fname(self): return f"{self.sample}_{self.aligner}_aligned.{self.format}" # {{/docs-fragment dataclasses}} # ## Tasks # # We define a series of tasks to perform the following operations: # 1. Fetch assets from remote URLs # 2. Perform quality filtering and preprocessing using FastP # 3. Generate Bowtie2 index files from a reference genome # 4. Perform alignment using Bowtie2 on a filtered sample # # The first task fetches the reference genome and sequencing reads. It is cached # so that re-runs skip the download step. # {{docs-fragment fetch_assets}} @fetch_env.task async def fetch_assets( ref_url: str, read_urls: List[str] ) -> tuple[Reference, List[Reads]]: """ Fetch assets from remote URLs. """ # Download reference genome ref_dir = Path("/tmp/reference_genome") ref_dir.mkdir(exist_ok=True, parents=True) ref = fetch_file(ref_url, str(ref_dir)) ref_obj = Reference( ref_name=ref.name, ref_dir=await Dir.from_local(str(ref_dir)), ) # Download sequencing reads dl_loc = Path("/tmp/reads") dl_loc.mkdir(exist_ok=True, parents=True) samples: dict[str, Reads] = {} for url in read_urls: fp = fetch_file(url, str(dl_loc)) sample = fp.stem.split("_")[0] if sample not in samples: samples[sample] = Reads(sample=sample) if ".fastq.gz" in fp.name or "fasta" in fp.name: mate = fp.name.strip(".fastq.gz").strip(".filt").split("_")[-1] if "1" in mate: samples[sample].read1 = await File.from_local(str(fp)) elif "2" in mate: samples[sample].read2 = await File.from_local(str(fp)) return ref_obj, list(samples.values()) # {{/docs-fragment fetch_assets}} # The second task performs quality filtering and preprocessing using FastP on a Reads object. # FastP is a performant tool for removing duplicate or low-quality reads. We increase # the memory request for this task so FastP can efficiently process reads from larger files. # {{docs-fragment pyfastp}} @fastp_env.task async def pyfastp(rs: Reads) -> Reads: """ Perform quality filtering and preprocessing using Fastp on a Reads object. Args: rs (Reads): A Reads object containing raw sequencing data to be processed. Returns: Reads: A Reads object representing the filtered and preprocessed data. """ ldir = Path(tempfile.mkdtemp()) samp = Reads(rs.sample) o1, o2 = samp.get_read_fnames() o1p = ldir / o1 o2p = ldir / o2 assert rs.read1 is not None and rs.read2 is not None r1 = await rs.read1.download() r2 = await rs.read2.download() cmd = [ "fastp", "-i", str(r1), "-I", str(r2), "-o", str(o1p), "-O", str(o2p), ] subprocess.run(cmd, check=True) samp.read1 = await File.from_local(str(o1p)) samp.read2 = await File.from_local(str(o2p)) return samp # {{/docs-fragment pyfastp}} # Next, we define a task to generate Bowtie2 index files from a reference genome. As the index # for a given tool and reference seldom changes, we cache this task. # {{docs-fragment bowtie2_index}} @index_env.task async def bowtie2_index(ref: Reference) -> Reference: """ Generate Bowtie2 index files from a reference genome. Args: ref (Reference): A Reference object representing the reference genome. Returns: Reference: The same reference object with the index_name and indexed_with attributes set. """ ref_dir = await ref.ref_dir.download() idx_name = "bt2_idx" cmd = [ "bowtie2-build", str(Path(str(ref_dir)) / ref.ref_name), str(Path(str(ref_dir)) / idx_name), ] subprocess.run(cmd, check=True) return Reference( ref.ref_name, await Dir.from_local(str(ref_dir)), idx_name, "bowtie2", ) # {{/docs-fragment bowtie2_index}} # The next task performs paired-end alignment using Bowtie 2 on a single sample. # {{docs-fragment bowtie2_align}} @align_env.task async def bowtie2_align_paired_reads(idx: Reference, fs: Reads) -> Alignment: """ Perform paired-end alignment using Bowtie 2 on a filtered sample. Args: idx (Reference): A Reference object containing the Bowtie 2 index. fs (Reads): A filtered Reads object containing sample data to be aligned. Returns: Alignment: An Alignment object representing the alignment result. """ assert idx.indexed_with == "bowtie2", "Reference index must be generated with bowtie2" assert idx.index_name is not None assert fs.read1 is not None and fs.read2 is not None ref_dir = await idx.ref_dir.download() r1 = await fs.read1.download() r2 = await fs.read2.download() ldir = Path(tempfile.mkdtemp()) alignment = Alignment(fs.sample, "bowtie2", "sam") al = ldir / alignment.get_alignment_fname() cmd = [ "bowtie2", "-x", str(Path(str(ref_dir)) / idx.index_name), "-1", str(r1), "-2", str(r2), "-S", str(al), ] subprocess.run(cmd, check=True) alignment.alignment = await File.from_local(str(al)) return alignment # {{/docs-fragment bowtie2_align}} # In place of the v1 `@dynamic` workflow, we use a plain async task with `asyncio.gather` # to run alignments for all samples in parallel. @base_env.task async def bowtie2_align_samples( idx: Reference, samples: List[Reads] ) -> List[Alignment]: """ Process samples through bowtie2 in parallel. Args: idx (Reference): A Reference object containing the Bowtie 2 index. samples (List[Reads]): A list of Reads objects to be aligned. Returns: List[Alignment]: A list of Alignment objects representing the alignment results. """ tasks = [bowtie2_align_paired_reads(idx=idx, fs=sample) for sample in samples] return list(await asyncio.gather(*tasks)) # ## End-to-End Workflow # # We tie everything together in a final task that fetches assets, filters them, generates # an index, and aligns the samples. In place of the v1 `@workflow`, we use a top-level # `@base_env.task`. Parallelism across samples is achieved with `asyncio.gather`. # {{docs-fragment workflow}} @base_env.task async def alignment_wf() -> List[Alignment]: # Prepare raw samples from remote URLs ref, samples = await fetch_assets( ref_url="https://github.com/unionai-oss/unionbio/raw/main/tests/assets/references/GRCh38_short.fasta", read_urls=[ "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_1.fastq.gz", "https://github.com/unionai-oss/unionbio/raw/main/tests/assets/sequences/raw/ERR250683-tiny_2.fastq.gz", ], ) # Filter all samples in parallel filtered_samples = list( await asyncio.gather(*[pyfastp(rs=s) for s in samples]) ) # Generate a bowtie2 index or load it from cache bowtie2_idx = await bowtie2_index(ref=ref) # Generate alignments using bowtie2 sams = await bowtie2_align_samples(idx=bowtie2_idx, samples=filtered_samples) return sams # {{/docs-fragment workflow}} # You can now run the workflow using the command in the dropdown at the top of the page! if __name__ == "__main__": flyte.init_from_config() run = flyte.run(alignment_wf) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_alignment/genomic_alignment.py* ## Run the workflow This example has no secrets or external API keys; it pulls public test data from GitHub. From the [example directory](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/genomic_alignment), run it as a `uv` script: CODE3 Or submit it with the Flyte CLI: CODE4 When the run completes, each returned `Alignment` points to a SAM file in blob storage that you can download from the run's outputs in the UI. === PAGE: https://www.union.ai/docs/v2/union/tutorials/biotech-healthcare/tumor-detection === Classify brain MRI scans with a two-phase EfficientNet-B4 pipeline featuring resumable GPU checkpointing and in-UI reports. # Brain tumor MRI classification > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/tumor_detection). This tutorial builds a medical-imaging pipeline that classifies brain MRI scans into four categories (Glioma, Meningioma, No Tumor, and Pituitary) using a two-phase EfficientNet-B4 transfer-learning strategy. The pipeline downloads the dataset, trains on a GPU with fault-tolerant checkpointing, and renders training curves and a confusion matrix directly in the Union.ai UI. The example is split into focused modules: - `config.py`: container image, task environments, and the `TrainingConfig` hyperparameters. - `dataset.py`: downloads the Hugging Face dataset, builds class-balanced data loaders. - `model.py` / `training.py`: the Lightning module and the two-phase training loop. - `utils.py`: plotting helpers for the report. - `run.py`: the three Flyte tasks and the pipeline driver. Flyte handles the production concerns: - **Per-task resources**: CPU for download/reporting, a GPU for training. - **`cache="auto"`** on dataset download and training, so reruns with the same data and config are free. - **`retries=3`** plus **Flyte checkpointing** on the training task so a preempted GPU job resumes from the last epoch. - **Built-in reports** to visualize metrics without separate dashboard infrastructure. ## Define the container image A single GPU-ready image is shared by all tasks. `with_source_folder` copies the local modules (`dataset.py`, `model.py`, etc.) into the image. ``` """ Configuration for brain tumor MRI classification pipeline. Defines task environments, resource requirements, and training hyperparameters. """ import pathlib import flyte # {{docs-fragment image}} image = flyte.Image.from_debian_base( name="tumor_detection_gpu" ).with_pip_packages( "torch", "lightning", "torchvision", "timm", "pillow", "scikit-learn", "plotly", "numpy", "pandas", "torchmetrics", "datasets", "typing_extensions", ).with_source_folder( pathlib.Path(__file__).parent, copy_contents_only=True, ) # {{/docs-fragment image}} # {{docs-fragment envs}} # Downloads raw MRI JPEG files โ€” CPU only, no auth needed, result is cached dataset_env = flyte.TaskEnvironment( name="tumor_dataset", image=image, resources=flyte.Resources(cpu=2, memory="4Gi", disk="8Gi"), cache="auto", ) # GPU training โ€” result is cached so re-running with the same data + config is free training_env = flyte.TaskEnvironment( name="tumor_gpu_training", image=image, resources=flyte.Resources( cpu=8, memory="32Gi", gpu="T4:1", disk="100Gi", ), env_vars={ "CUDA_VISIBLE_DEVICES": "0", "CUDA_LAUNCH_BLOCKING": "1", "TORCH_CUDA_MEMORY_FRACTION": "1.0", "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", }, cache="auto", ) # Report generation โ€” CPU only, reads training results and renders Union UI panels report_env = flyte.TaskEnvironment( name="tumor_report", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), ) # Pipeline driver โ€” lightweight orchestrator that calls the three tasks above pipeline_env = flyte.TaskEnvironment( name="tumor_pipeline", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[dataset_env, training_env, report_env], ) # {{/docs-fragment envs}} class TrainingConfig: """Unified training configuration for brain tumor MRI classification.""" def __init__( self, image_size: int = 380, num_classes: int = 4, model_name: str = "efficientnet_b4", pretrained: bool = True, phase1_epochs: int = 8, phase1_lr: float = 1e-3, phase1_freeze_backbone: bool = True, phase2_epochs: int = 25, phase2_lr: float = 5e-5, batch_size: int = 16, num_workers: int = 0, val_split: float = 0.2, weight_decay: float = 1e-4, warmup_steps: int = 200, focal_gamma: float = 2.0, mixup_alpha: float = 0.0, log_interval: int = 50, ): self.image_size = image_size self.num_classes = num_classes self.model_name = model_name self.pretrained = pretrained self.phase1_epochs = phase1_epochs self.phase1_lr = phase1_lr self.phase1_freeze_backbone = phase1_freeze_backbone self.phase2_epochs = phase2_epochs self.phase2_lr = phase2_lr self.batch_size = batch_size self.num_workers = num_workers self.val_split = val_split self.weight_decay = weight_decay self.warmup_steps = warmup_steps self.focal_gamma = focal_gamma self.mixup_alpha = mixup_alpha self.log_interval = log_interval def to_dict(self) -> dict: return self.__dict__ ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/config.py* ## Define the task environments Each stage declares the resources it needs. The lightweight `pipeline_env` orchestrates the others via `depends_on`. ``` """ Configuration for brain tumor MRI classification pipeline. Defines task environments, resource requirements, and training hyperparameters. """ import pathlib import flyte # {{docs-fragment image}} image = flyte.Image.from_debian_base( name="tumor_detection_gpu" ).with_pip_packages( "torch", "lightning", "torchvision", "timm", "pillow", "scikit-learn", "plotly", "numpy", "pandas", "torchmetrics", "datasets", "typing_extensions", ).with_source_folder( pathlib.Path(__file__).parent, copy_contents_only=True, ) # {{/docs-fragment image}} # {{docs-fragment envs}} # Downloads raw MRI JPEG files โ€” CPU only, no auth needed, result is cached dataset_env = flyte.TaskEnvironment( name="tumor_dataset", image=image, resources=flyte.Resources(cpu=2, memory="4Gi", disk="8Gi"), cache="auto", ) # GPU training โ€” result is cached so re-running with the same data + config is free training_env = flyte.TaskEnvironment( name="tumor_gpu_training", image=image, resources=flyte.Resources( cpu=8, memory="32Gi", gpu="T4:1", disk="100Gi", ), env_vars={ "CUDA_VISIBLE_DEVICES": "0", "CUDA_LAUNCH_BLOCKING": "1", "TORCH_CUDA_MEMORY_FRACTION": "1.0", "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", }, cache="auto", ) # Report generation โ€” CPU only, reads training results and renders Union UI panels report_env = flyte.TaskEnvironment( name="tumor_report", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), ) # Pipeline driver โ€” lightweight orchestrator that calls the three tasks above pipeline_env = flyte.TaskEnvironment( name="tumor_pipeline", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[dataset_env, training_env, report_env], ) # {{/docs-fragment envs}} class TrainingConfig: """Unified training configuration for brain tumor MRI classification.""" def __init__( self, image_size: int = 380, num_classes: int = 4, model_name: str = "efficientnet_b4", pretrained: bool = True, phase1_epochs: int = 8, phase1_lr: float = 1e-3, phase1_freeze_backbone: bool = True, phase2_epochs: int = 25, phase2_lr: float = 5e-5, batch_size: int = 16, num_workers: int = 0, val_split: float = 0.2, weight_decay: float = 1e-4, warmup_steps: int = 200, focal_gamma: float = 2.0, mixup_alpha: float = 0.0, log_interval: int = 50, ): self.image_size = image_size self.num_classes = num_classes self.model_name = model_name self.pretrained = pretrained self.phase1_epochs = phase1_epochs self.phase1_lr = phase1_lr self.phase1_freeze_backbone = phase1_freeze_backbone self.phase2_epochs = phase2_epochs self.phase2_lr = phase2_lr self.batch_size = batch_size self.num_workers = num_workers self.val_split = val_split self.weight_decay = weight_decay self.warmup_steps = warmup_steps self.focal_gamma = focal_gamma self.mixup_alpha = mixup_alpha self.log_interval = log_interval def to_dict(self) -> dict: return self.__dict__ ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/config.py* ## Configure training Hyperparameters are gathered in a single `TrainingConfig`, serialized to JSON, and passed into the training task so the exact configuration is captured alongside the run. ``` """ Flyte/Union pipeline for brain tumor MRI classification. Three-task pipeline: 1. load_dataset โ€” download Brain Tumor MRI from Hugging Face, cache as Dir (CPU) 2. train_model โ€” two-phase EfficientNet-B4 training with focal loss (GPU) 3. create_report โ€” render training curves and confusion matrix in the Union UI (CPU) """ import json import flyte from flyte.io import Dir from config import TrainingConfig, dataset_env, pipeline_env, report_env, training_env from dataset import download_tumor_dataset # {{docs-fragment config}} TRAINING_CONFIG = TrainingConfig( phase1_epochs=8, phase2_epochs=25, phase1_lr=1e-3, phase2_lr=5e-5, batch_size=16, num_workers=0, log_interval=50, mixup_alpha=0.0, image_size=380, focal_gamma=3.0, ) # {{/docs-fragment config}} # {{docs-fragment load_dataset}} @dataset_env.task async def load_dataset() -> Dir: """ Download raw Brain Tumor MRI JPEG files from Hugging Face and cache as flyte.io.Dir. Runs once โ€” result is reused on subsequent pipeline runs (cache="auto"). """ return await download_tumor_dataset() # {{/docs-fragment load_dataset}} # {{docs-fragment train_model}} @training_env.task(retries=3) async def train_model(dataset_dir: Dir, config_json: str) -> Dir: """ Download the raw dataset Dir, run two-phase training, and return training metrics and final predictions as a Dir for the report task. """ from pathlib import Path local_dir = Path("/tmp/tumor_local") local_dir.mkdir(parents=True, exist_ok=True) await dataset_dir.download(local_path=str(local_dir)) from training import train_tumor_classifier config = TrainingConfig(**json.loads(config_json)) result = train_tumor_classifier(config=config, dataset_path=str(local_dir)) output_dir = Path("/tmp/training_results") output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "metrics.json").write_text(json.dumps(result["metrics"])) (output_dir / "predictions.json").write_text(json.dumps({ "preds": result["final_preds"], "targets": result["final_targets"], })) return await Dir.from_local(str(output_dir)) # {{/docs-fragment train_model}} # {{docs-fragment create_report}} @report_env.task(report=True) async def create_report(results_dir: Dir) -> None: """ Download training metrics and render loss/accuracy curves, confusion matrix, and per-class F1 chart in the Union UI report panel. """ import numpy as np from pathlib import Path from utils import create_confusion_matrix_plot, create_metrics_plots, create_per_class_f1_plot local_dir = Path("/tmp/tumor_report") local_dir.mkdir(parents=True, exist_ok=True) await results_dir.download(local_path=str(local_dir)) matches = list(local_dir.glob("**/metrics.json")) if not matches: raise RuntimeError(f"metrics.json not found under {local_dir}") local_path = matches[0].parent history = json.loads((local_path / "metrics.json").read_text()) predictions = json.loads((local_path / "predictions.json").read_text()) preds = np.array(predictions["preds"]) targets = np.array(predictions["targets"]) loss_fig, acc_fig = create_metrics_plots(history) cm_fig = create_confusion_matrix_plot(preds, targets) f1_fig = create_per_class_f1_plot(preds, targets) combined_html = ( acc_fig.to_html(include_plotlyjs=True, full_html=False) + loss_fig.to_html(include_plotlyjs=False, full_html=False) + cm_fig.to_html(include_plotlyjs=False, full_html=False) + f1_fig.to_html(include_plotlyjs=False, full_html=False) ) flyte.report.log(combined_html, do_flush=True) # {{/docs-fragment create_report}} # {{docs-fragment pipeline}} @pipeline_env.task async def tumor_detection_pipeline() -> None: """Orchestrate dataset loading, GPU training, and report generation.""" dataset_dir = await load_dataset() results_dir = await train_model( dataset_dir=dataset_dir, config_json=json.dumps(TRAINING_CONFIG.to_dict()), ) await create_report(results_dir=results_dir) # {{/docs-fragment pipeline}} if __name__ == "__main__": import pathlib flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.with_runcontext().run(tumor_detection_pipeline) print(f"\nโœ“ Pipeline submitted!") print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/run.py* ## Load the dataset The first task downloads the public [Brain Tumor MRI dataset](https://huggingface.co/datasets/AIOmarRehan/Brain_Tumor_MRI_Dataset) from Hugging Face (no auth required) and stores it as a `flyte.io.Dir`. It's cached, so subsequent runs reuse it. ``` """ Flyte/Union pipeline for brain tumor MRI classification. Three-task pipeline: 1. load_dataset โ€” download Brain Tumor MRI from Hugging Face, cache as Dir (CPU) 2. train_model โ€” two-phase EfficientNet-B4 training with focal loss (GPU) 3. create_report โ€” render training curves and confusion matrix in the Union UI (CPU) """ import json import flyte from flyte.io import Dir from config import TrainingConfig, dataset_env, pipeline_env, report_env, training_env from dataset import download_tumor_dataset # {{docs-fragment config}} TRAINING_CONFIG = TrainingConfig( phase1_epochs=8, phase2_epochs=25, phase1_lr=1e-3, phase2_lr=5e-5, batch_size=16, num_workers=0, log_interval=50, mixup_alpha=0.0, image_size=380, focal_gamma=3.0, ) # {{/docs-fragment config}} # {{docs-fragment load_dataset}} @dataset_env.task async def load_dataset() -> Dir: """ Download raw Brain Tumor MRI JPEG files from Hugging Face and cache as flyte.io.Dir. Runs once โ€” result is reused on subsequent pipeline runs (cache="auto"). """ return await download_tumor_dataset() # {{/docs-fragment load_dataset}} # {{docs-fragment train_model}} @training_env.task(retries=3) async def train_model(dataset_dir: Dir, config_json: str) -> Dir: """ Download the raw dataset Dir, run two-phase training, and return training metrics and final predictions as a Dir for the report task. """ from pathlib import Path local_dir = Path("/tmp/tumor_local") local_dir.mkdir(parents=True, exist_ok=True) await dataset_dir.download(local_path=str(local_dir)) from training import train_tumor_classifier config = TrainingConfig(**json.loads(config_json)) result = train_tumor_classifier(config=config, dataset_path=str(local_dir)) output_dir = Path("/tmp/training_results") output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "metrics.json").write_text(json.dumps(result["metrics"])) (output_dir / "predictions.json").write_text(json.dumps({ "preds": result["final_preds"], "targets": result["final_targets"], })) return await Dir.from_local(str(output_dir)) # {{/docs-fragment train_model}} # {{docs-fragment create_report}} @report_env.task(report=True) async def create_report(results_dir: Dir) -> None: """ Download training metrics and render loss/accuracy curves, confusion matrix, and per-class F1 chart in the Union UI report panel. """ import numpy as np from pathlib import Path from utils import create_confusion_matrix_plot, create_metrics_plots, create_per_class_f1_plot local_dir = Path("/tmp/tumor_report") local_dir.mkdir(parents=True, exist_ok=True) await results_dir.download(local_path=str(local_dir)) matches = list(local_dir.glob("**/metrics.json")) if not matches: raise RuntimeError(f"metrics.json not found under {local_dir}") local_path = matches[0].parent history = json.loads((local_path / "metrics.json").read_text()) predictions = json.loads((local_path / "predictions.json").read_text()) preds = np.array(predictions["preds"]) targets = np.array(predictions["targets"]) loss_fig, acc_fig = create_metrics_plots(history) cm_fig = create_confusion_matrix_plot(preds, targets) f1_fig = create_per_class_f1_plot(preds, targets) combined_html = ( acc_fig.to_html(include_plotlyjs=True, full_html=False) + loss_fig.to_html(include_plotlyjs=False, full_html=False) + cm_fig.to_html(include_plotlyjs=False, full_html=False) + f1_fig.to_html(include_plotlyjs=False, full_html=False) ) flyte.report.log(combined_html, do_flush=True) # {{/docs-fragment create_report}} # {{docs-fragment pipeline}} @pipeline_env.task async def tumor_detection_pipeline() -> None: """Orchestrate dataset loading, GPU training, and report generation.""" dataset_dir = await load_dataset() results_dir = await train_model( dataset_dir=dataset_dir, config_json=json.dumps(TRAINING_CONFIG.to_dict()), ) await create_report(results_dir=results_dir) # {{/docs-fragment pipeline}} if __name__ == "__main__": import pathlib flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.with_runcontext().run(tumor_detection_pipeline) print(f"\nโœ“ Pipeline submitted!") print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/run.py* ## Train the model The training task downloads the dataset `Dir`, runs two-phase training (frozen backbone, then full fine-tuning), and writes metrics and predictions to an output `Dir`. It sets `retries=3` so a preempted GPU node restarts the task. ``` """ Flyte/Union pipeline for brain tumor MRI classification. Three-task pipeline: 1. load_dataset โ€” download Brain Tumor MRI from Hugging Face, cache as Dir (CPU) 2. train_model โ€” two-phase EfficientNet-B4 training with focal loss (GPU) 3. create_report โ€” render training curves and confusion matrix in the Union UI (CPU) """ import json import flyte from flyte.io import Dir from config import TrainingConfig, dataset_env, pipeline_env, report_env, training_env from dataset import download_tumor_dataset # {{docs-fragment config}} TRAINING_CONFIG = TrainingConfig( phase1_epochs=8, phase2_epochs=25, phase1_lr=1e-3, phase2_lr=5e-5, batch_size=16, num_workers=0, log_interval=50, mixup_alpha=0.0, image_size=380, focal_gamma=3.0, ) # {{/docs-fragment config}} # {{docs-fragment load_dataset}} @dataset_env.task async def load_dataset() -> Dir: """ Download raw Brain Tumor MRI JPEG files from Hugging Face and cache as flyte.io.Dir. Runs once โ€” result is reused on subsequent pipeline runs (cache="auto"). """ return await download_tumor_dataset() # {{/docs-fragment load_dataset}} # {{docs-fragment train_model}} @training_env.task(retries=3) async def train_model(dataset_dir: Dir, config_json: str) -> Dir: """ Download the raw dataset Dir, run two-phase training, and return training metrics and final predictions as a Dir for the report task. """ from pathlib import Path local_dir = Path("/tmp/tumor_local") local_dir.mkdir(parents=True, exist_ok=True) await dataset_dir.download(local_path=str(local_dir)) from training import train_tumor_classifier config = TrainingConfig(**json.loads(config_json)) result = train_tumor_classifier(config=config, dataset_path=str(local_dir)) output_dir = Path("/tmp/training_results") output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "metrics.json").write_text(json.dumps(result["metrics"])) (output_dir / "predictions.json").write_text(json.dumps({ "preds": result["final_preds"], "targets": result["final_targets"], })) return await Dir.from_local(str(output_dir)) # {{/docs-fragment train_model}} # {{docs-fragment create_report}} @report_env.task(report=True) async def create_report(results_dir: Dir) -> None: """ Download training metrics and render loss/accuracy curves, confusion matrix, and per-class F1 chart in the Union UI report panel. """ import numpy as np from pathlib import Path from utils import create_confusion_matrix_plot, create_metrics_plots, create_per_class_f1_plot local_dir = Path("/tmp/tumor_report") local_dir.mkdir(parents=True, exist_ok=True) await results_dir.download(local_path=str(local_dir)) matches = list(local_dir.glob("**/metrics.json")) if not matches: raise RuntimeError(f"metrics.json not found under {local_dir}") local_path = matches[0].parent history = json.loads((local_path / "metrics.json").read_text()) predictions = json.loads((local_path / "predictions.json").read_text()) preds = np.array(predictions["preds"]) targets = np.array(predictions["targets"]) loss_fig, acc_fig = create_metrics_plots(history) cm_fig = create_confusion_matrix_plot(preds, targets) f1_fig = create_per_class_f1_plot(preds, targets) combined_html = ( acc_fig.to_html(include_plotlyjs=True, full_html=False) + loss_fig.to_html(include_plotlyjs=False, full_html=False) + cm_fig.to_html(include_plotlyjs=False, full_html=False) + f1_fig.to_html(include_plotlyjs=False, full_html=False) ) flyte.report.log(combined_html, do_flush=True) # {{/docs-fragment create_report}} # {{docs-fragment pipeline}} @pipeline_env.task async def tumor_detection_pipeline() -> None: """Orchestrate dataset loading, GPU training, and report generation.""" dataset_dir = await load_dataset() results_dir = await train_model( dataset_dir=dataset_dir, config_json=json.dumps(TRAINING_CONFIG.to_dict()), ) await create_report(results_dir=results_dir) # {{/docs-fragment pipeline}} if __name__ == "__main__": import pathlib flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.with_runcontext().run(tumor_detection_pipeline) print(f"\nโœ“ Pipeline submitted!") print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/run.py* ### Resumable checkpointing To make retries cheap, training mirrors its Lightning checkpoint directory to a `flyte.Checkpoint` after every epoch, and resumes from the latest checkpoint when the task restarts. ``` """ Training pipeline for brain tumor MRI classification. Implements two-phase training: - Phase 1: Frozen backbone (feature extractor), train classification head - Phase 2: Fine-tune full model with differential LRs + cosine annealing """ from config import TrainingConfig from dataset import compute_class_weights, create_data_loaders from model import TumorClassifierLightningModule from utils import get_model_size, get_trainable_params def train_tumor_classifier( config: TrainingConfig, dataset_path: str, ) -> dict: """ Run two-phase training on the preprocessed dataset and return metrics + final predictions. dataset_path: local directory where the flyte.io.Dir was downloaded by the training task. """ import pathlib import flyte import lightning as L import torch from lightning.pytorch.callbacks import ModelCheckpoint from typing_extensions import override # {{docs-fragment flyte_checkpoint}} class FlyteLightningCheckpointCallback(ModelCheckpoint): """Mirrors the checkpoint directory to Flyte after every epoch so retries can resume.""" def __init__(self, flyte_checkpoint: flyte.Checkpoint, *, dirpath: str, **kwargs): super().__init__(dirpath=dirpath, **kwargs) self._flyte_checkpoint = flyte_checkpoint @override def on_train_epoch_end(self, trainer: L.Trainer, pl_module: L.LightningModule) -> None: super().on_train_epoch_end(trainer, pl_module) if self.dirpath: self._flyte_checkpoint.save_sync(pathlib.Path(self.dirpath)) # {{/docs-fragment flyte_checkpoint}} class MetricsLoggerCallback(L.Callback): def __init__(self, phase1_epochs: int): super().__init__() self.phase1_epochs = phase1_epochs self.history = [] def on_validation_epoch_end(self, trainer, _pl_module): epoch = trainer.current_epoch metrics = trainer.callback_metrics self.history.append({ "epoch": epoch, "phase": 1 if epoch < self.phase1_epochs else 2, "train_loss": float(metrics.get("train/loss_epoch", 0)), "val_loss": float(metrics.get("val/loss", 0)), "val_acc": float(metrics.get("val/acc", 0)), "macro_f1": float(metrics.get("val/macro_f1", 0)), }) class PhaseChangeCallback(L.Callback): def __init__(self, phase1_epochs: int, phase2_lr: float): super().__init__() self.phase1_epochs = phase1_epochs self.phase2_lr = phase2_lr self.phase_changed = False def on_train_epoch_end(self, trainer, pl_module): if not self.phase_changed and (trainer.current_epoch + 1) == self.phase1_epochs: print("\n" + "=" * 80) print("TRANSITIONING TO PHASE 2: UNFREEZING BACKBONE AND ADJUSTING LR") print("=" * 80 + "\n") pl_module.model.unfreeze_backbone() for param_group in trainer.optimizers[0].param_groups: param_group["lr"] = self.phase2_lr # Add backbone params to optimizer with 10x lower LR. # Backbone was excluded at init because it was frozen. backbone_lr = self.phase2_lr * 0.1 backbone_decay, backbone_no_decay = [], [] for param in pl_module.model.backbone.parameters(): if param.ndim >= 2: backbone_decay.append(param) else: backbone_no_decay.append(param) optimizer = trainer.optimizers[0] optimizer.add_param_group({"params": backbone_decay, "lr": backbone_lr, "weight_decay": pl_module.weight_decay}) optimizer.add_param_group({"params": backbone_no_decay, "lr": backbone_lr, "weight_decay": 0.0}) # Fresh cosine schedule over remaining Phase 2 steps to avoid # the Phase 1 schedule arriving near-zero before Phase 2 begins. steps_remaining = trainer.estimated_stepping_batches - trainer.global_step new_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( trainer.optimizers[0], T_max=max(1, steps_remaining), eta_min=1e-6, ) for lr_scheduler_config in trainer.lr_scheduler_configs: lr_scheduler_config.scheduler = new_scheduler print(f"Phase 2 started: lr={self.phase2_lr}") print(f"Total parameters: {get_model_size(pl_module.model):,}") print(f"Trainable parameters: {get_trainable_params(pl_module.model):,}") self.phase_changed = True print("\n" + "=" * 80) print("BRAIN TUMOR MRI CLASSIFICATION WITH EFFICIENTNET-B4") print("=" * 80) print(f"Config: {config.to_dict()}\n") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"Using device: {device}") if torch.cuda.is_available(): print(f"GPU: {torch.cuda.get_device_name(0)}") print(f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.2f} GB") print("\nLoading MRI images...") train_loader, val_loader = create_data_loaders( dataset_path=dataset_path, image_size=config.image_size, batch_size=config.batch_size, num_workers=config.num_workers, val_split=config.val_split, ) print(f"Data loaders created: {len(train_loader)} train batches, {len(val_loader)} val batches") print("\nComputing class weights for focal loss...") class_weights = compute_class_weights(dataset_path) print(f"Class weights: {class_weights.tolist()}") # Per-class gamma: Meningioma gets 7.0, all others 3.0. # CLASS_NAMES alphabetical order: Glioma=0, Meningioma=1, No Tumor=2, Pituitary=3 gamma_per_class = torch.tensor([3.0, 7.0, 3.0, 3.0]) print("\nInitializing model...") model = TumorClassifierLightningModule( num_classes=config.num_classes, model_name=config.model_name, pretrained=config.pretrained, learning_rate=config.phase1_lr, freeze_backbone=config.phase1_freeze_backbone, weight_decay=config.weight_decay, warmup_steps=config.warmup_steps, max_epochs=config.phase1_epochs + config.phase2_epochs, focal_gamma=config.focal_gamma, mixup_alpha=config.mixup_alpha, class_weights=class_weights, gamma_per_class=gamma_per_class, ) print(f"Model: {config.model_name}") print(f"Total parameters: {get_model_size(model.model):,}") print(f"Trainable parameters: {get_trainable_params(model.model):,}") from pathlib import Path checkpoint_dir = Path("/tmp/tumor_checkpoints") checkpoint_dir.mkdir(parents=True, exist_ok=True) # {{docs-fragment resume}} # --- Flyte checkpoint: resume from previous attempt if one exists --- resume_ckpt: str | None = None ctx = flyte.ctx() flyte_checkpoint = getattr(ctx, "checkpoint", None) if ctx else None if flyte_checkpoint: prev_path = flyte_checkpoint.load_sync() if prev_path: last = flyte.latest_checkpoint(prev_path) if last: ck = torch.load(str(last), map_location="cpu", weights_only=False) epoch_start = int(ck.get("epoch", 0)) resume_ckpt = str(last) print(f"Resuming from epoch {epoch_start}, checkpoint: {last}") # -------------------------------------------------------------------- # {{/docs-fragment resume}} metrics_cb = MetricsLoggerCallback(phase1_epochs=config.phase1_epochs) resume_callback = ( FlyteLightningCheckpointCallback( flyte_checkpoint, dirpath=str(checkpoint_dir), filename="last", save_last=True, save_top_k=1, ) if flyte_checkpoint else ModelCheckpoint( dirpath=str(checkpoint_dir), filename="best-{epoch:03d}-{val_acc:.3f}", monitor="val/acc", mode="max", save_top_k=3, verbose=True, auto_insert_metric_name=False, ) ) callbacks = [ resume_callback, metrics_cb, PhaseChangeCallback( phase1_epochs=config.phase1_epochs, phase2_lr=config.phase2_lr, ), ] trainer = L.Trainer( max_epochs=config.phase1_epochs + config.phase2_epochs, accelerator="gpu" if torch.cuda.is_available() else "cpu", devices=1, precision="16-mixed", callbacks=callbacks, enable_progress_bar=True, enable_model_summary=True, log_every_n_steps=config.log_interval, gradient_clip_val=1.0, ) trainer.fit(model, train_loader, val_loader, ckpt_path=resume_ckpt) best_checkpoint = trainer.checkpoint_callback.best_model_path print(f"\nโœ“ Training complete!") print(f"Best checkpoint: {best_checkpoint}") # Final inference with TTA (test-time augmentation): average logits over # original + h-flip + v-flip + 90ยฐ rotations for a free accuracy boost. print("\nRunning final inference with TTA for confusion matrix...") import numpy as np import torchvision.transforms.functional as TF model.eval() model.to(device) all_preds, all_targets = [], [] with torch.no_grad(): for images, labels in val_loader: images = images.to(device) aug_logits = [ model.model(images), model.model(TF.hflip(images)), model.model(TF.vflip(images)), model.model(torch.rot90(images, k=1, dims=[2, 3])), model.model(torch.rot90(images, k=3, dims=[2, 3])), ] avg_logits = torch.stack(aug_logits).mean(dim=0) all_preds.append(avg_logits.argmax(dim=1).cpu()) all_targets.append(labels.cpu()) final_preds = torch.cat(all_preds).numpy() final_targets = torch.cat(all_targets).numpy() return { "best_checkpoint": best_checkpoint, "metrics": metrics_cb.history, "final_preds": final_preds.tolist(), "final_targets": final_targets.tolist(), } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/training.py* On startup, the training loop looks for a checkpoint from a previous attempt and resumes from it if present: ``` """ Training pipeline for brain tumor MRI classification. Implements two-phase training: - Phase 1: Frozen backbone (feature extractor), train classification head - Phase 2: Fine-tune full model with differential LRs + cosine annealing """ from config import TrainingConfig from dataset import compute_class_weights, create_data_loaders from model import TumorClassifierLightningModule from utils import get_model_size, get_trainable_params def train_tumor_classifier( config: TrainingConfig, dataset_path: str, ) -> dict: """ Run two-phase training on the preprocessed dataset and return metrics + final predictions. dataset_path: local directory where the flyte.io.Dir was downloaded by the training task. """ import pathlib import flyte import lightning as L import torch from lightning.pytorch.callbacks import ModelCheckpoint from typing_extensions import override # {{docs-fragment flyte_checkpoint}} class FlyteLightningCheckpointCallback(ModelCheckpoint): """Mirrors the checkpoint directory to Flyte after every epoch so retries can resume.""" def __init__(self, flyte_checkpoint: flyte.Checkpoint, *, dirpath: str, **kwargs): super().__init__(dirpath=dirpath, **kwargs) self._flyte_checkpoint = flyte_checkpoint @override def on_train_epoch_end(self, trainer: L.Trainer, pl_module: L.LightningModule) -> None: super().on_train_epoch_end(trainer, pl_module) if self.dirpath: self._flyte_checkpoint.save_sync(pathlib.Path(self.dirpath)) # {{/docs-fragment flyte_checkpoint}} class MetricsLoggerCallback(L.Callback): def __init__(self, phase1_epochs: int): super().__init__() self.phase1_epochs = phase1_epochs self.history = [] def on_validation_epoch_end(self, trainer, _pl_module): epoch = trainer.current_epoch metrics = trainer.callback_metrics self.history.append({ "epoch": epoch, "phase": 1 if epoch < self.phase1_epochs else 2, "train_loss": float(metrics.get("train/loss_epoch", 0)), "val_loss": float(metrics.get("val/loss", 0)), "val_acc": float(metrics.get("val/acc", 0)), "macro_f1": float(metrics.get("val/macro_f1", 0)), }) class PhaseChangeCallback(L.Callback): def __init__(self, phase1_epochs: int, phase2_lr: float): super().__init__() self.phase1_epochs = phase1_epochs self.phase2_lr = phase2_lr self.phase_changed = False def on_train_epoch_end(self, trainer, pl_module): if not self.phase_changed and (trainer.current_epoch + 1) == self.phase1_epochs: print("\n" + "=" * 80) print("TRANSITIONING TO PHASE 2: UNFREEZING BACKBONE AND ADJUSTING LR") print("=" * 80 + "\n") pl_module.model.unfreeze_backbone() for param_group in trainer.optimizers[0].param_groups: param_group["lr"] = self.phase2_lr # Add backbone params to optimizer with 10x lower LR. # Backbone was excluded at init because it was frozen. backbone_lr = self.phase2_lr * 0.1 backbone_decay, backbone_no_decay = [], [] for param in pl_module.model.backbone.parameters(): if param.ndim >= 2: backbone_decay.append(param) else: backbone_no_decay.append(param) optimizer = trainer.optimizers[0] optimizer.add_param_group({"params": backbone_decay, "lr": backbone_lr, "weight_decay": pl_module.weight_decay}) optimizer.add_param_group({"params": backbone_no_decay, "lr": backbone_lr, "weight_decay": 0.0}) # Fresh cosine schedule over remaining Phase 2 steps to avoid # the Phase 1 schedule arriving near-zero before Phase 2 begins. steps_remaining = trainer.estimated_stepping_batches - trainer.global_step new_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( trainer.optimizers[0], T_max=max(1, steps_remaining), eta_min=1e-6, ) for lr_scheduler_config in trainer.lr_scheduler_configs: lr_scheduler_config.scheduler = new_scheduler print(f"Phase 2 started: lr={self.phase2_lr}") print(f"Total parameters: {get_model_size(pl_module.model):,}") print(f"Trainable parameters: {get_trainable_params(pl_module.model):,}") self.phase_changed = True print("\n" + "=" * 80) print("BRAIN TUMOR MRI CLASSIFICATION WITH EFFICIENTNET-B4") print("=" * 80) print(f"Config: {config.to_dict()}\n") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"Using device: {device}") if torch.cuda.is_available(): print(f"GPU: {torch.cuda.get_device_name(0)}") print(f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.2f} GB") print("\nLoading MRI images...") train_loader, val_loader = create_data_loaders( dataset_path=dataset_path, image_size=config.image_size, batch_size=config.batch_size, num_workers=config.num_workers, val_split=config.val_split, ) print(f"Data loaders created: {len(train_loader)} train batches, {len(val_loader)} val batches") print("\nComputing class weights for focal loss...") class_weights = compute_class_weights(dataset_path) print(f"Class weights: {class_weights.tolist()}") # Per-class gamma: Meningioma gets 7.0, all others 3.0. # CLASS_NAMES alphabetical order: Glioma=0, Meningioma=1, No Tumor=2, Pituitary=3 gamma_per_class = torch.tensor([3.0, 7.0, 3.0, 3.0]) print("\nInitializing model...") model = TumorClassifierLightningModule( num_classes=config.num_classes, model_name=config.model_name, pretrained=config.pretrained, learning_rate=config.phase1_lr, freeze_backbone=config.phase1_freeze_backbone, weight_decay=config.weight_decay, warmup_steps=config.warmup_steps, max_epochs=config.phase1_epochs + config.phase2_epochs, focal_gamma=config.focal_gamma, mixup_alpha=config.mixup_alpha, class_weights=class_weights, gamma_per_class=gamma_per_class, ) print(f"Model: {config.model_name}") print(f"Total parameters: {get_model_size(model.model):,}") print(f"Trainable parameters: {get_trainable_params(model.model):,}") from pathlib import Path checkpoint_dir = Path("/tmp/tumor_checkpoints") checkpoint_dir.mkdir(parents=True, exist_ok=True) # {{docs-fragment resume}} # --- Flyte checkpoint: resume from previous attempt if one exists --- resume_ckpt: str | None = None ctx = flyte.ctx() flyte_checkpoint = getattr(ctx, "checkpoint", None) if ctx else None if flyte_checkpoint: prev_path = flyte_checkpoint.load_sync() if prev_path: last = flyte.latest_checkpoint(prev_path) if last: ck = torch.load(str(last), map_location="cpu", weights_only=False) epoch_start = int(ck.get("epoch", 0)) resume_ckpt = str(last) print(f"Resuming from epoch {epoch_start}, checkpoint: {last}") # -------------------------------------------------------------------- # {{/docs-fragment resume}} metrics_cb = MetricsLoggerCallback(phase1_epochs=config.phase1_epochs) resume_callback = ( FlyteLightningCheckpointCallback( flyte_checkpoint, dirpath=str(checkpoint_dir), filename="last", save_last=True, save_top_k=1, ) if flyte_checkpoint else ModelCheckpoint( dirpath=str(checkpoint_dir), filename="best-{epoch:03d}-{val_acc:.3f}", monitor="val/acc", mode="max", save_top_k=3, verbose=True, auto_insert_metric_name=False, ) ) callbacks = [ resume_callback, metrics_cb, PhaseChangeCallback( phase1_epochs=config.phase1_epochs, phase2_lr=config.phase2_lr, ), ] trainer = L.Trainer( max_epochs=config.phase1_epochs + config.phase2_epochs, accelerator="gpu" if torch.cuda.is_available() else "cpu", devices=1, precision="16-mixed", callbacks=callbacks, enable_progress_bar=True, enable_model_summary=True, log_every_n_steps=config.log_interval, gradient_clip_val=1.0, ) trainer.fit(model, train_loader, val_loader, ckpt_path=resume_ckpt) best_checkpoint = trainer.checkpoint_callback.best_model_path print(f"\nโœ“ Training complete!") print(f"Best checkpoint: {best_checkpoint}") # Final inference with TTA (test-time augmentation): average logits over # original + h-flip + v-flip + 90ยฐ rotations for a free accuracy boost. print("\nRunning final inference with TTA for confusion matrix...") import numpy as np import torchvision.transforms.functional as TF model.eval() model.to(device) all_preds, all_targets = [], [] with torch.no_grad(): for images, labels in val_loader: images = images.to(device) aug_logits = [ model.model(images), model.model(TF.hflip(images)), model.model(TF.vflip(images)), model.model(torch.rot90(images, k=1, dims=[2, 3])), model.model(torch.rot90(images, k=3, dims=[2, 3])), ] avg_logits = torch.stack(aug_logits).mean(dim=0) all_preds.append(avg_logits.argmax(dim=1).cpu()) all_targets.append(labels.cpu()) final_preds = torch.cat(all_preds).numpy() final_targets = torch.cat(all_targets).numpy() return { "best_checkpoint": best_checkpoint, "metrics": metrics_cb.history, "final_preds": final_preds.tolist(), "final_targets": final_targets.tolist(), } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/training.py* ## Generate the report The reporting task reads the metrics and predictions, then renders accuracy/loss curves, a confusion matrix, and a per-class F1 chart with Plotly. `report=True` surfaces the HTML directly in the run's report panel. ``` """ Flyte/Union pipeline for brain tumor MRI classification. Three-task pipeline: 1. load_dataset โ€” download Brain Tumor MRI from Hugging Face, cache as Dir (CPU) 2. train_model โ€” two-phase EfficientNet-B4 training with focal loss (GPU) 3. create_report โ€” render training curves and confusion matrix in the Union UI (CPU) """ import json import flyte from flyte.io import Dir from config import TrainingConfig, dataset_env, pipeline_env, report_env, training_env from dataset import download_tumor_dataset # {{docs-fragment config}} TRAINING_CONFIG = TrainingConfig( phase1_epochs=8, phase2_epochs=25, phase1_lr=1e-3, phase2_lr=5e-5, batch_size=16, num_workers=0, log_interval=50, mixup_alpha=0.0, image_size=380, focal_gamma=3.0, ) # {{/docs-fragment config}} # {{docs-fragment load_dataset}} @dataset_env.task async def load_dataset() -> Dir: """ Download raw Brain Tumor MRI JPEG files from Hugging Face and cache as flyte.io.Dir. Runs once โ€” result is reused on subsequent pipeline runs (cache="auto"). """ return await download_tumor_dataset() # {{/docs-fragment load_dataset}} # {{docs-fragment train_model}} @training_env.task(retries=3) async def train_model(dataset_dir: Dir, config_json: str) -> Dir: """ Download the raw dataset Dir, run two-phase training, and return training metrics and final predictions as a Dir for the report task. """ from pathlib import Path local_dir = Path("/tmp/tumor_local") local_dir.mkdir(parents=True, exist_ok=True) await dataset_dir.download(local_path=str(local_dir)) from training import train_tumor_classifier config = TrainingConfig(**json.loads(config_json)) result = train_tumor_classifier(config=config, dataset_path=str(local_dir)) output_dir = Path("/tmp/training_results") output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "metrics.json").write_text(json.dumps(result["metrics"])) (output_dir / "predictions.json").write_text(json.dumps({ "preds": result["final_preds"], "targets": result["final_targets"], })) return await Dir.from_local(str(output_dir)) # {{/docs-fragment train_model}} # {{docs-fragment create_report}} @report_env.task(report=True) async def create_report(results_dir: Dir) -> None: """ Download training metrics and render loss/accuracy curves, confusion matrix, and per-class F1 chart in the Union UI report panel. """ import numpy as np from pathlib import Path from utils import create_confusion_matrix_plot, create_metrics_plots, create_per_class_f1_plot local_dir = Path("/tmp/tumor_report") local_dir.mkdir(parents=True, exist_ok=True) await results_dir.download(local_path=str(local_dir)) matches = list(local_dir.glob("**/metrics.json")) if not matches: raise RuntimeError(f"metrics.json not found under {local_dir}") local_path = matches[0].parent history = json.loads((local_path / "metrics.json").read_text()) predictions = json.loads((local_path / "predictions.json").read_text()) preds = np.array(predictions["preds"]) targets = np.array(predictions["targets"]) loss_fig, acc_fig = create_metrics_plots(history) cm_fig = create_confusion_matrix_plot(preds, targets) f1_fig = create_per_class_f1_plot(preds, targets) combined_html = ( acc_fig.to_html(include_plotlyjs=True, full_html=False) + loss_fig.to_html(include_plotlyjs=False, full_html=False) + cm_fig.to_html(include_plotlyjs=False, full_html=False) + f1_fig.to_html(include_plotlyjs=False, full_html=False) ) flyte.report.log(combined_html, do_flush=True) # {{/docs-fragment create_report}} # {{docs-fragment pipeline}} @pipeline_env.task async def tumor_detection_pipeline() -> None: """Orchestrate dataset loading, GPU training, and report generation.""" dataset_dir = await load_dataset() results_dir = await train_model( dataset_dir=dataset_dir, config_json=json.dumps(TRAINING_CONFIG.to_dict()), ) await create_report(results_dir=results_dir) # {{/docs-fragment pipeline}} if __name__ == "__main__": import pathlib flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.with_runcontext().run(tumor_detection_pipeline) print(f"\nโœ“ Pipeline submitted!") print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/run.py* ## Orchestrate the pipeline The driver task wires the three steps together. ``` """ Flyte/Union pipeline for brain tumor MRI classification. Three-task pipeline: 1. load_dataset โ€” download Brain Tumor MRI from Hugging Face, cache as Dir (CPU) 2. train_model โ€” two-phase EfficientNet-B4 training with focal loss (GPU) 3. create_report โ€” render training curves and confusion matrix in the Union UI (CPU) """ import json import flyte from flyte.io import Dir from config import TrainingConfig, dataset_env, pipeline_env, report_env, training_env from dataset import download_tumor_dataset # {{docs-fragment config}} TRAINING_CONFIG = TrainingConfig( phase1_epochs=8, phase2_epochs=25, phase1_lr=1e-3, phase2_lr=5e-5, batch_size=16, num_workers=0, log_interval=50, mixup_alpha=0.0, image_size=380, focal_gamma=3.0, ) # {{/docs-fragment config}} # {{docs-fragment load_dataset}} @dataset_env.task async def load_dataset() -> Dir: """ Download raw Brain Tumor MRI JPEG files from Hugging Face and cache as flyte.io.Dir. Runs once โ€” result is reused on subsequent pipeline runs (cache="auto"). """ return await download_tumor_dataset() # {{/docs-fragment load_dataset}} # {{docs-fragment train_model}} @training_env.task(retries=3) async def train_model(dataset_dir: Dir, config_json: str) -> Dir: """ Download the raw dataset Dir, run two-phase training, and return training metrics and final predictions as a Dir for the report task. """ from pathlib import Path local_dir = Path("/tmp/tumor_local") local_dir.mkdir(parents=True, exist_ok=True) await dataset_dir.download(local_path=str(local_dir)) from training import train_tumor_classifier config = TrainingConfig(**json.loads(config_json)) result = train_tumor_classifier(config=config, dataset_path=str(local_dir)) output_dir = Path("/tmp/training_results") output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "metrics.json").write_text(json.dumps(result["metrics"])) (output_dir / "predictions.json").write_text(json.dumps({ "preds": result["final_preds"], "targets": result["final_targets"], })) return await Dir.from_local(str(output_dir)) # {{/docs-fragment train_model}} # {{docs-fragment create_report}} @report_env.task(report=True) async def create_report(results_dir: Dir) -> None: """ Download training metrics and render loss/accuracy curves, confusion matrix, and per-class F1 chart in the Union UI report panel. """ import numpy as np from pathlib import Path from utils import create_confusion_matrix_plot, create_metrics_plots, create_per_class_f1_plot local_dir = Path("/tmp/tumor_report") local_dir.mkdir(parents=True, exist_ok=True) await results_dir.download(local_path=str(local_dir)) matches = list(local_dir.glob("**/metrics.json")) if not matches: raise RuntimeError(f"metrics.json not found under {local_dir}") local_path = matches[0].parent history = json.loads((local_path / "metrics.json").read_text()) predictions = json.loads((local_path / "predictions.json").read_text()) preds = np.array(predictions["preds"]) targets = np.array(predictions["targets"]) loss_fig, acc_fig = create_metrics_plots(history) cm_fig = create_confusion_matrix_plot(preds, targets) f1_fig = create_per_class_f1_plot(preds, targets) combined_html = ( acc_fig.to_html(include_plotlyjs=True, full_html=False) + loss_fig.to_html(include_plotlyjs=False, full_html=False) + cm_fig.to_html(include_plotlyjs=False, full_html=False) + f1_fig.to_html(include_plotlyjs=False, full_html=False) ) flyte.report.log(combined_html, do_flush=True) # {{/docs-fragment create_report}} # {{docs-fragment pipeline}} @pipeline_env.task async def tumor_detection_pipeline() -> None: """Orchestrate dataset loading, GPU training, and report generation.""" dataset_dir = await load_dataset() results_dir = await train_model( dataset_dir=dataset_dir, config_json=json.dumps(TRAINING_CONFIG.to_dict()), ) await create_report(results_dir=results_dir) # {{/docs-fragment pipeline}} if __name__ == "__main__": import pathlib flyte.init_from_config(root_dir=pathlib.Path(__file__).parent) run = flyte.with_runcontext().run(tumor_detection_pipeline) print(f"\nโœ“ Pipeline submitted!") print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/tumor_detection/run.py* ## Run the pipeline This example has no secrets: the dataset is public. Because the pipeline imports sibling modules and uses `with_source_folder`, run it from inside the example directory so the local files are picked up. From the [example directory](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/tumor_detection): ``` cd v2/tutorials/tumor_detection python run.py ``` Or submit it with the Flyte CLI from the same directory: ``` flyte run run.py tumor_detection_pipeline ``` When the run completes, open the `create_report` task in the UI to view the training curves, confusion matrix, and per-class F1 scores. === PAGE: https://www.union.ai/docs/v2/union/tutorials/biotech-healthcare/genomic-gene-comparison === Compare homologous genes across species with Carbon scoring, sequence alignment, and ESMFold 3D structures. # Cross-species gene comparison > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/genomic_gene_comparison). This tutorial builds a bioinformatics pipeline that compares homologous genes across species. The workflow loads curated gene sequences (insulin, hemoglobin, or p53 by default), scores each sequence with the [Carbon](https://huggingface.co/HuggingFaceBio/Carbon-3B) genomic language model, aligns DNA and translated protein sequences, folds proteins with [ESMFold](https://github.com/facebookresearch/esm), and renders interactive HTML reports with identity heatmaps, phylogenetic trees, and 3D structure viewers. Flyte makes the multi-stage GPU/CPU pipeline reliable: - **Separate CPU and GPU `TaskEnvironment`s** so alignment runs on modest CPU boxes while Carbon scoring and ESMFold run on GPUs. - **`report=True`** on every stage after gene loading for live HTML progress and final summaries in the Flyte UI. ## Define the task environments GPU tasks handle Carbon log-likelihood scoring and ESMFold structure prediction; CPU tasks load gene sets, run Needleman-Wunsch alignments, and generate the final summary. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "torch>=2.9.0", # "transformers>=4.49.0", # "accelerate>=0.34.0", # "numpy", # ] # main = "pipeline" # params = "" # /// import json import logging import math import os import tempfile import flyte import flyte.io import flyte.report # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="genomic-gene-comparison", pre=True) gpu_env = flyte.TaskEnvironment( name="genomic-gene-comparison-gpu", image=main_img, resources=flyte.Resources(cpu=4, memory="32Gi", gpu=1), ) cpu_env = flyte.TaskEnvironment( name="genomic-gene-comparison-cpu", image=main_img, resources=flyte.Resources(cpu=2, memory="8Gi"), depends_on=[gpu_env], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Homologous gene sets - same gene across species # ------------------------------------------------------------------ # Full-length coding sequences from NCBI RefSeq (stop codon excluded). GENE_SETS = { "insulin": { "gene_name": "Insulin", "description": "Insulin regulates blood sugar in all vertebrates. Highly conserved across 500M+ years of evolution - even fish insulin can lower blood sugar in humans. Comparing across species reveals which regions are functionally essential (conserved) vs free to drift.", "sequences": { "Human": { "dna": "ATGGCCCTGTGGATGCGCCTCCTGCCCCTGCTGGCGCTGCTGGCCCTCTGGGGACCTGACCCAGCCGCAGCCTTTGTGAACCAACACCTGTGCGGCTCACACCTGGTGGAAGCTCTCTACCTAGTGTGCGGGGAACGAGGCTTCTTCTACACACCCAAGACCCGCCGGGAGGCAGAGGACCTGCAGGTGGGGCAGGTGGAGCTGGGCGGGGGCCCTGGTGCAGGCAGCCTGCAGCCCTTGGCCCTGGAGGGGTCCCTGCAGAAGCGTGGCATTGTGGAACAATGCTGTACCAGCATCTGCTCCCTCTACCAGCTGGAGAACTACTGCAAC", "common_name": "Homo sapiens", }, "Mouse": { "dna": "ATGGCCCTGTGGATGCGCTTCCTGCCCCTGCTGGCCCTGCTCTTCCTCTGGGAGTCCCACCCCACCCAGGCTTTTGTCAAGCAGCACCTTTGTGGTTCCCACCTGGTGGAGGCTCTCTACCTGGTGTGTGGGGAGCGTGGCTTCTTCTACACACCCATGTCCCGCCGTGAAGTGGAGGACCCACAAGTGGCACAACTGGAGCTGGGTGGAGGCCCGGGAGCAGGTGACCTTCAGACCTTGGCACTGGAGGTGGCCCAGCAGAAGCGTGGCATTGTAGATCAGTGCTGCACCAGCATCTGCTCCCTCTACCAGCTGGAGAACTACTGCAAC", "common_name": "Mus musculus", }, "Chicken": { "dna": "ATGGCTCTCTGGATCCGATCACTGCCTCTTCTGGCTCTCCTTGTCTTTTCTGGCCCTGGAACCAGCTATGCAGCTGCCAACCAGCACCTCTGTGGCTCCCACTTGGTGGAGGCTCTCTACCTGGTGTGTGGAGAGCGTGGCTTCTTCTACTCCCCCAAAGCCCGACGGGATGTCGAGCAGCCCCTAGTGAGCAGTCCCTTGCGTGGCGAGGCAGGAGTGCTGCCTTTCCAGCAGGAGGAATACGAGAAAGTCAAGCGAGGGATTGTTGAGCAATGCTGCCATAACACGTGTTCCCTCTACCAACTGGAGAACTACTGCAAC", "common_name": "Gallus gallus", }, "Zebrafish": { "dna": "ATGGCAGTGTGGCTTCAGGCTGGTGCTCTGTTGGTCCTGTTGGTCGTGTCCAGTGTAAGCACTAACCCAGGCACACCGCAGCACCTGTGTGGATCTCATCTGGTCGATGCCCTTTATCTGGTCTGTGGCCCAACAGGCTTCTTCTACAACCCCAAGAGAGACGTTGAGCCCCTTCTGGGTTTCCTTCCTCCTAAATCTGCCCAGGAAACTGAGGTGGCTGACTTTGCATTTAAAGATCATGCCGAGCTGATAAGGAAGAGAGGCATTGTAGAGCAGTGCTGCCACAAACCCTGCAGCATCTTTGAGCTGCAGAACTACTGTAAC", "common_name": "Danio rerio", }, "Frog": { "dna": "ATGGCTCTATGGATGCAGTGTCTGCCCCTGGTTCTTGTCCTCTTTTTCTCTACACCCAACACCGAAGCTCTAGTTAACCAGCACTTGTGTGGGTCTCACCTGGTAGAAGCCCTGTACTTAGTATGTGGGGATCGAGGCTTCTTCTACTACCCTAAGGTCAAACGGGACATGGAACAAGCACTTGTCAGTGGACCCCAGGATAATGAGTTGGATGGAATGCAGCTCCAGCCTCAGGAGTATCAGAAAATGAAGAGGGGGATTGTGGAGCAATGTTGCCACAGCACATGTTCTCTCTTCCAGCTGGAGAGTTACTGCAAC", "common_name": "Xenopus laevis", }, "Cow": { "dna": "ATGGCCCTGTGGACACGCCTGGCGCCCCTGCTGGCCCTGCTGGCGCTCTGGGCCCCCGCCCCGGCCCGCGCCTTCGTCAACCAGCATCTGTGTGGCTCCCACCTGGTGGAGGCGCTGTACCTGGTGTGCGGAGAGCGCGGCTTCTTCTACACGCCCAAGGCCCGCCGGGAGGTGGAGGGCCCCCAGGTGGGGGCGCTGGAGCTGGCCGGAGGCCCGGGCGCGGGCGGCCTGGAGGGGCCCCCGCAGAAGCGTGGCATCGTGGAGCAGTGCTGTGCCAGCGTCTGCTCGCTCTACCAGCTGGAGAACTACTGTAAC", "common_name": "Bos taurus", }, }, }, "hemoglobin": { "gene_name": "Hemoglobin Beta", "description": "Beta-globin carries oxygen from lungs to tissues. The most studied gene in molecular evolution - sequence differences power the 'molecular clock' hypothesis. Sickle cell mutation (E6V) in humans shows how a single base change creates devastating disease.", "sequences": { "Human": { "dna": "ATGGTGCATCTGACTCCTGAGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTGGTCTACCCTTGGACCCAGAGGTTCTTTGAGTCCTTTGGGGATCTGTCCACTCCTGATGCTGTTATGGGCAACCCTAAGGTGAAGGCTCATGGCAAGAAAGTGCTCGGTGCCTTTAGTGATGGCCTGGCTCACCTGGACAACCTCAAGGGCACCTTTGCCACACTGAGTGAGCTGCACTGTGACAAGCTGCACGTGGATCCTGAGAACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTCACCCCACCAGTGCAGGCTGCCTATCAGAAAGTGGTGGCTGGTGTGGCTAATGCCCTGGCCCACAAGTATCAC", "common_name": "Homo sapiens", }, "Mouse": { "dna": "ATGGTGCACCTGACTGATGCTGAGAAGGCTGCTGTCTCTGGCCTGTGGGGAAAGGTGAACGCCGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTTGTCTACCCTTGGACCCAGCGGTACTTTGATAGCTTTGGAGACCTATCCTCTGCCTCTGCTATCATGGGTAATGCCAAAGTGAAGGCCCATGGCAAGAAAGTGATAACTGCCTTTAACGATGGCCTGAATCACTTGGACAGCCTCAAGGGCACCTTTGCCAGCCTCAGTGAGCTCCACTGTGACAAGCTGCATGTGGATCCTGAGAACTTCAGGCTCCTGGGCAATATGATCGTGATTGTGCTGGGCCACCACCTGGGCAAGGATTTCACCCCCGCTGCACAGGCTGCCTTCCAGAAGGTGGTGGCTGGAGTGGCTGCTGCCCTGGCTCACAAGTACCAC", "common_name": "Mus musculus", }, "Chicken": { "dna": "ATGGTGCACTGGACTGCTGAGGAGAAGCAGCTCATCACCGGCCTCTGGGGCAAGGTCAATGTGGCCGAATGTGGGGCTGAAGCCCTGGCCAGGCTGCTGATCGTCTACCCCTGGACCCAGAGGTTCTTTGCGTCCTTTGGGAACCTCTCCAGCCCCACTGCCATCCTTGGCAACCCCATGGTCCGCGCCCATGGCAAGAAAGTGCTCACCTCCTTTGGGGATGCTGTGAAGAACCTGGACAACATCAAGAACACCTTCTCCCAACTGTCCGAACTGCATTGTGACAAGCTGCATGTGGACCCCGAGAACTTCAGGCTCCTGGGTGACATCCTCATCATTGTCCTGGCCGCCCACTTCAGCAAGGACTTCACTCCTGAATGCCAGGCTGCCTGGCAGAAGCTGGTCCGCGTGGTGGCCCATGCCCTGGCTCGCAAGTACCAC", "common_name": "Gallus gallus", }, "Zebrafish": { "dna": "ATGGTTGAGTGGACAGATGCCGAGCGCACAGCCATCCTTGGCCTGTGGGGAAAGCTCAATATCGATGAAATCGGACCTCAGGCCCTATCCAGATGTCTGATCGTGTATCCCTGGACTCAGAGATATTTCGCCACATTCGGCAACCTGTCAAGCCCCGCTGCGATCATGGGTAACCCCAAAGTGGCAGCTCATGGGAGGACTGTGATGGGAGGTCTTGAGAGAGCCATCAAGAACATGGACAACGTCAAGAACACCTATGCCGCCCTCAGTGTGATGCACTCTGAGAAACTGCATGTGGATCCCGACAACTTCAGGCTTCTCGCTGATTGCATCACCGTTTGCGCTGCCATGAAGTTCGGCCAAGCTGGTTTCAATGCTGATGTCCAGGAGGCCTGGCAGAAGTTTCTGGCTGTGGTCGTTTCTGCTCTGTGCAGACAGTACCAC", "common_name": "Danio rerio", }, "Frog": { "dna": "ATGGTTCATTGGACAGCTGAAGAGAAGGCCGCCATCACCTCTGTGTGGCAGGAGGTCAACCAGGAGCAAGATGGCCATGATGCACTCACAAGGCTGCTGGTTGTGTACCCCTGGACCCAGAGATACTTCAGCAGTTTTGGAAATCTCGGTAATGCCACAGCTATTGCTGGAAATGTCAAGGTGCGTGCCCATGGCAAGAAGGTTCTTTCAGCTGTTGGTGATGCCATCGCCCATCTTGACAACGTGAAGGGAACTCTCCATGACCTCAGTGTGGTCCACGCCTTCAAGCTCTATGTGGATCCTGAGAACTTCAAGCGTCTTGGTGAAGTTCTGGTCATTGTCTTGGCTTCCAAACTGGGATCAGCCTTTACTCCTCAAGTCCAGGGAGCCTGGGAGAAATTTGTTGCTGTTCTGGTTGATGCCCTCAGCCAAGGATACAAC", "common_name": "Xenopus laevis", }, "Cow": { "dna": "ATGCTGACTGCTGAGGAGAAGGCTGCCGTCACCGCCTTTTGGGGCAAGGTGAAAGTGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTTGTCTACCCCTGGACTCAGAGGTTCTTTGAGTCCTTTGGGGACTTGTCCACTGCTGATGCTGTTATGAACAACCCTAAGGTGAAGGCCCATGGCAAGAAGGTGCTAGATTCCTTTAGTAATGGCATGAAGCATCTCGATGACCTCAAGGGCACCTTTGCTGCGCTGAGTGAGCTGCACTGTGATAAGCTGCATGTGGATCCTGAGAACTTCAAGCTCCTGGGCAACGTGCTAGTGGTTGTGCTGGCTCGCAATTTTGGCAAGGAATTCACCCCGGTGCTGCAGGCTGACTTTCAGAAGGTGGTGGCTGGTGTGGCCAATGCCCTGGCCCACAGATATCAT", "common_name": "Bos taurus", }, }, }, "p53": { "gene_name": "p53 (TP53)", "description": "The 'guardian of the genome' - p53 detects DNA damage and triggers repair or cell death. Mutated in >50% of human cancers. Elephants have 20 copies of p53 (humans have 1), which may explain their extremely low cancer rates despite their size (Peto's paradox).", "sequences": { "Human": { "dna": "ATGGAGGAGCCGCAGTCAGATCCTAGCGTCGAGCCCCCTCTGAGTCAGGAAACATTTTCAGACCTATGGAAACTACTTCCTGAAAACAACGTTCTGTCCCCCTTGCCGTCCCAAGCAATGGATGATTTGATGCTGTCCCCGGACGATATTGAACAATGGTTCACTGAAGACCCAGGTCCAGATGAAGCTCCCAGAATGCCAGAGGCTGCTCCCCCCGTGGCCCCTGCACCAGCAGCTCCTACACCGGCGGCCCCTGCACCAGCCCCCTCCTGGCCCCTGTCATCTTCTGTCCCTTCCCAGAAAACCTACCAGGGCAGCTACGGTTTCCGTCTGGGCTTCTTGCATTCTGGGACAGCCAAGTCTGTGACTTGCACGTACTCCCCTGCCCTCAACAAGATGTTTTGCCAACTGGCCAAGACCTGCCCTGTGCAGCTGTGGGTTGATTCCACACCCCCGCCCGGCACCCGCGTCCGCGCCATGGCCATCTACAAGCAGTCACAGCACATGACGGAGGTTGTGAGGCGCTGCCCCCACCATGAGCGCTGCTCAGATAGCGATGGTCTGGCCCCTCCTCAGCATCTTATCCGAGTGGAAGGAAATTTGCGTGTGGAGTATTTGGATGACAGAAACACTTTTCGACATAGTGTGGTGGTGCCCTATGAGCCGCCTGAGGTTGGCTCTGACTGTACCACCATCCACTACAACTACATGTGTAACAGTTCCTGCATGGGCGGCATGAACCGGAGGCCCATCCTCACCATCATCACACTGGAAGACTCCAGTGGTAATCTACTGGGACGGAACAGCTTTGAGGTGCGTGTTTGTGCCTGTCCTGGGAGAGACCGGCGCACAGAGGAAGAGAATCTCCGCAAGAAAGGGGAGCCTCACCACGAGCTGCCCCCAGGGAGCACTAAGCGAGCACTGCCCAACAACACCAGCTCCTCTCCCCAGCCAAAGAAGAAACCACTGGATGGAGAATATTTCACCCTTCAGATCCGTGGGCGTGAGCGCTTCGAGATGTTCCGAGAGCTGAATGAGGCCTTGGAACTCAAGGATGCCCAGGCTGGGAAGGAGCCAGGGGGGAGCAGGGCTCACTCCAGCCACCTGAAGTCCAAAAAGGGTCAGTCTACCTCCCGCCATAAAAAACTCATGTTCAAGACAGAAGGGCCTGACTCAGAC", "common_name": "Homo sapiens", }, "Mouse": { "dna": "ATGACTGCCATGGAGGAGTCACAGTCGGATATCAGCCTCGAGCTCCCTCTGAGCCAGGAGACATTTTCAGGCTTATGGAAACTACTTCCTCCAGAAGATATCCTGCCATCACCTCACTGCATGGACGATCTGTTGCTGCCCCAGGATGTTGAGGAGTTTTTTGAAGGCCCAAGTGAAGCCCTCCGAGTGTCAGGAGCTCCTGCAGCACAGGACCCTGTCACCGAGACCCCTGGGCCAGTGGCCCCTGCCCCAGCCACTCCATGGCCCCTGTCATCTTTTGTCCCTTCTCAAAAAACTTACCAGGGCAACTATGGCTTCCACCTGGGCTTCCTGCAGTCTGGGACAGCCAAGTCTGTTATGTGCACGTACTCTCCTCCCCTCAATAAGCTATTCTGCCAGCTGGCGAAGACGTGCCCTGTGCAGTTGTGGGTCAGCGCCACACCTCCAGCTGGGAGCCGTGTCCGCGCCATGGCCATCTACAAGAAGTCACAGCACATGACGGAGGTCGTGAGACGCTGCCCCCACCATGAGCGCTGCTCCGATGGTGATGGCCTGGCTCCTCCCCAGCATCTTATCCGGGTGGAAGGAAATTTGTATCCCGAGTATCTGGAAGACAGGCAGACTTTTCGCCACAGCGTGGTGGTACCTTATGAGCCACCCGAGGCCGGCTCTGAGTATACCACCATCCACTACAAGTACATGTGTAATAGCTCCTGCATGGGGGGCATGAACCGCCGACCTATCCTTACCATCATCACACTGGAAGACTCCAGTGGGAACCTTCTGGGACGGGACAGCTTTGAGGTTCGTGTTTGTGCCTGCCCTGGGAGAGACCGCCGTACAGAAGAAGAAAATTTCCGCAAAAAGGAAGTCCTTTGCCCTGAACTGCCCCCAGGGAGCGCAAAGAGAGCGCTGCCCACCTGCACAAGCGCCTCTCCCCCGCAAAAGAAAAAACCACTTGATGGAGAGTATTTCACCCTCAAGATCCGCGGGCGTAAACGCTTCGAGATGTTCCGGGAGCTGAATGAGGCCTTAGAGTTAAAGGATGCCCATGCTACAGAGGAGTCTGGAGACAGCAGGGCTCACTCCAGCTACCTGAAGACCAAGAAGGGCCAGTCTACTTCCCGCCATAAAAAAACAATGGTCAAGAAAGTGGGGCCTGACTCAGAC", "common_name": "Mus musculus", }, "Chicken": { "dna": "ATGGCGGAGGAGATGGAACCATTGCTGGAACCCACTGAGGTCTTCATGGACCTCTGGAGCATGCTCCCCTATAGCATGCAACAGCTGCCCCTCCCTGAGGATCACAGCAACTGGCAGGAGCTGAGCCCCCTGGAACCCAGCGACCCCCCCCCACCACCGCCACCACCACCTCTGCCATTGGCCGCCGCCGCCCCCCCCCCATTAAACCCCCCCACCCCCCCCCGCGCTGCCCCCTCCCCGGTGGTCCCATCCACGGAGGATTATGGGGGGGACTTCGACTTCCGGGTGGGGTTCGTGGAGGCGGGCACAGCCAAATCGGTCACCTGCACTTACTCCCCGGTGCTGAATAAGGTCTATTGCCGCCTGGCCAAGCCGTGCCCGGTGCAGGTGAGGGTGGGGGTGGCGCCCCCCCCCGGTTCCTCCCTCCGCGCCGTGGCCGTCTATAAGAAATCAGAGCACGTGGCCGAAGTGGTGCGGCGCTGCCCCCACCACGAGCGCTGCGGGGGGGGCACCGACGGCCTGGCCCCCGCACAGCACCTCATCCGGGTGGAGGGGAACCCCCAGGCGCGTTACCACGACGACGAGACCACCAAACGGCACAGCGTCGTCGTCCCCTATGAGCCCCCCGAGGTGGGCTCTGACTGTACCACGGTGCTGTACAACTTCATGTGCAACAGTTCCTGCATGGGGGGGATGAACCGCCGCCCCATCCTCACCATCCTTACACTGGAGGGGCCGGGGGGGCAGCTGTTGGGGCGGCGCTGCTTCGAGGTGCGCGTGTGCGCATGTCCGGGGAGGGACCGCAAGATCGAGGAGGAGAACTTCCGCAAGAGGGGCGGGGCCGGGGGCGTGGCTAAGCGAGCCATGTCGCCCCCAACCGAAGCCCCCGAGCCCCCCAAGAAGCGCGTGCTGAACCCCGACAATGAGATATTCTACCTGCAGGTGCGCGGGCGCCGCCGCTATGAGATGCTGAAGGAGATCAATGAGGCGCTGCAGCTCGCCGAGGGGGGGTCCGCACCGCGGCCTTCCAAAGGCCGCCGTGTGAAGGTGGAGGGACCCCAACCCAGCTGCGGGAAGAAACTGCTGCAAAAAGGCTCGGAC", "common_name": "Gallus gallus", }, "Zebrafish": { "dna": "ATGGCGCAAAACGACAGCCAAGAGTTCGCGGAGCTCTGGGAGAAGAATTTGATTATTCAGCCCCCAGGTGGTGGCTCTTGCTGGGACATCATTAATGATGAGGAGTACTTGCCGGGATCGTTTGACCCCAATTTTTTTGAAAATGTGCTTGAAGAACAGCCTCAGCCATCCACTCTCCCACCAACATCCACTGTTCCGGAGACAAGCGACTATCCCGGCGATCATGGATTTAGGCTCAGGTTCCCGCAGTCTGGCACAGCAAAATCTGTAACTTGCACTTATTCACCGGACCTGAATAAACTCTTCTGTCAGCTGGCAAAAACTTGCCCCGTTCAAATGGTGGTGGACGTTGCCCCTCCACAGGGCTCCGTGGTTCGAGCCACTGCCATCTATAAGAAGTCCGAGCATGTGGCTGAAGTGGTCCGCAGATGCCCCCATCATGAGCGAACCCCGGATGGAGATAACTTGGCGCCTGCTGGTCATTTGATAAGAGTGGAGGGCAATCAGCGAGCAAATTACAGGGAAGATAACATCACTTTAAGGCATAGTGTTTTTGTCCCATATGAAGCACCACAGCTTGGTGCTGAATGGACAACTGTGCTACTAAACTACATGTGCAATAGCAGCTGCATGGGGGGGATGAACCGCAGGCCCATCCTCACAATCATCACTCTGGAGACTCAGGAAGGTCAGTTGCTGGGCCGGAGGTCTTTTGAGGTGCGTGTGTGTGCATGTCCAGGCAGAGACAGGAAAACTGAGGAGAGCAACTTCAAGAAAGACCAAGAGACCAAAACCATGGCCAAAACCACCACTGGGACCAAACGTAGTTTGGTGAAAGAATCTTCTTCAGCTACATTACGACCTGAGGGGAGCAAAAAGGCCAAGGGCTCCAGCAGCGATGAGGAGATCTTTACCCTGCAGGTGAGGGGCAGGGAGCGTTATGAAATTTTAAAGAAATTGAACGACAGTCTGGAGTTAAGTGATGTGGTGCCTGCCTCAGATGCTGAAAAGTATCGTCAGAAATTCATGACAAAAAACAAAAAAGAGAATCGTGAATCATCTGAGCCCAAACAGGGAAAGAAGCTGATGGTGAAGGACGAAGGAAGAAGCGACTCTGAT", "common_name": "Danio rerio", }, "Elephant": { "dna": "ATGGAGGAGCCCCAGTCAGATCTCAGCACCGAGCTCCCTCTGAGTCAAGAGACGTTTTCATACTTATGGGAACTCCTTCCTGAGAATCCGGTTCTGTCCCCCACACTACCCCCGGCAGTGGAGGTCATGGACGATCTGCTACTCTCAGAAGACACTGCAAACTGGCTAGAAAGCCAAGTTGAGGCTCAGGGAATGTCCACAACCCCTGCACCAGCCACCCCTACACCGGTGGCCCCCGCACCAGCCACCTCCTGGACCCTGTCATCTTCCGTCCCTTCCCAAAAGACCTACCCTGGCACCTATGGTTTCCGTCTGGGCTTCCTACATTCTGGGACAGCCAAGTCCGTCACCTGCACGTACTCCCCTGACCTTAACAAGCTGTTTTGCCAGCTGGCAAAAACCTGCCCAGTGCAGCTGTGGGTCGCCTCACCACCCCCGCCCGGCACCCGTGTTCGCACCATGGCCATCTACAAGAAGTCAGAGCATATGACGGAGGTCGTCAAGCGCTGCCCCCACCATGAGCGCTGCTCTGACTCTAGCGATGGCCTGGCCCCTCCTCAGCACCTCATCCGGGTGGAAGGAAACCTGCGTGCTGAGTATCTGGAGGACAGCATCACTCTCCGACACAGTGTGGTGGTGCCCTACGAGCCGCCCGAGGTTGGGTCTGACTGTACCACCATCCACTTCAACTTCATGTGTAACAGCTCCTGCATGGGGGGCATGAACCGGCGGCCCATCCTCACCATCATCACACTGGAAGACTCCAGTGGTAATCTGCTGGGACGTAACAGCTTTGAGGTGCGCATTTGTGCCTGTCCTGGAAGAGACAGACGTACAGAAGAAGAAAATTTCCACAAGAAGGGAGAGCCTTGCCCAGAGCCGCCACCCCCTGGGAGGAGCACTAAGCGAGCACTGCCCACCAACACCAGCTCCTCTACCCAGCCAAAGAAGAAGCCACTGGATGAAGAATATTTCACCCTTCAGATCCGTGGGCGTGAACGCTTCAAGATGTTCCTAGAGCTAAATGAGGCCTTGGAGCTGAAGGATGCCCAGGCTGGGAAGGAGCCAGAGGGGAGCCGGGCTCACTCCAGCCCTTCGAAGTCTAAGAAGGGACAGTCTACCTCCCGCCATAAAAAACCAATGTTCAAGAGAGAGGGACCTGACTCAGAC", "common_name": "Loxodonta africana", }, "Dog": { "dna": "ATGGAGGAGTCGCAGTCAGAGCTCAATATCGACCCCCCTCTGAGCCAGGAGACATTTTCAGAATTGTGGAACCTGCTTCCTGAAAACAATGTTCTGTCTTCGGAGCTGTGCCCAGCAGTGGATGAGCTGCTGCTCCCAGAGAGCGTCGTGAACTGGCTAGACGAAGACTCAGATGATGCTCCCAGGATGCCAGCCACTTCTGCCCCCACAGCCCCTGGACCGGCCCCCTCGTGGCCCCTATCATCCTCTGTCCCTTCCCCGAAGACCTACCCTGGCACCTATGGGTTCCGTTTGGGGTTCCTGCATTCCGGGACAGCCAAGTCTGTTACTTGGACGTACTCCCCTCTCCTCAACAAGTTGTTTTGCCAGCTGGCGAAGACCTGCCCCGTGCAGCTGTGGGTCAGCTCCCCACCCCCACCCAATACCTGCGTCCGCGCTATGGCCATCTATAAGAAGTCGGAGTTCGTGACCGAGGTTGTGCGGCGCTGCCCCCACCATGAACGCTGCTCTGACAGTAGTGACGGTCTTGCCCCTCCTCAGCATCTCATCCGAGTGGAAGGAAATTTGCGGGCCAAGTACCTGGACGACAGAAACACTTTTCGACACAGTGTGGTGGTGCCTTATGAGCCACCCGAGGTTGGCTCTGACTATACCACCATCCACTACAACTACATGTGTAACAGTTCCTGCATGGGAGGCATGAACCGGCGGCCCATCCTCACTATCATCACCCTGGAAGACTCCAGTGGAAACGTGCTGGGACGCAACAGCTTTGAGGTACGCGTTTGTGCCTGTCCCGGGAGAGACCGCCGGACTGAGGAGGAGAATTTCCACAAGAAGGGGGAGCCTTGTCCTGAGCCACCCCCCGGGAGTACCAAGCGAGCACTGCCTCCCAGCACCAGCTCCTCTCCCCCGCAAAAGAAGAAGCCACTAGATGGAGAATATTTCACCCTTCAGATCCGTGGGCGTGAACGCTATGAGATGTTCAGGAATCTGAATGAAGCCTTGGAGCTGAAGGATGCCCAGAGTGGAAAGGAGCCAGGGGGAAGCAGGGCTCACTCCAGCCACCTGAAGGCAAAGAAGGGGCAATCTACCTCTCGCCATAAAAAACTGATGTTCAAGAGAGAAGGGCTTGACTCAGAC", "common_name": "Canis lupus familiaris", }, }, }, } # Standard genetic code CODON_TABLE = { "TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L", "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L", "ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M", "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V", "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S", "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P", "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T", "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A", "TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*", "CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q", "AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K", "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E", "TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W", "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R", "AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R", "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G", } BASE_COLORS = {"A": "#2ecc71", "T": "#e74c3c", "G": "#f39c12", "C": "#3498db"} def _translate(dna: str) -> str: """Translate DNA to protein in reading frame 0.""" dna = dna.upper() protein = [] for i in range(0, len(dna) - 2, 3): codon = dna[i:i + 3] aa = CODON_TABLE.get(codon, "X") if aa == "*": break protein.append(aa) return "".join(protein) def _gc_content(seq: str) -> float: if not seq: return 0.0 return sum(1 for b in seq.upper() if b in "GC") / len(seq) def _sequence_identity(seq1: str, seq2: str, match: int = 2, mismatch: int = -1, gap: int = -2) -> float: """Percent identity via Needleman-Wunsch global alignment.""" if not seq1 or not seq2: return 0.0 n, m = len(seq1), len(seq2) # Build score matrix dp = [[0] * (m + 1) for _ in range(n + 1)] for i in range(1, n + 1): dp[i][0] = dp[i - 1][0] + gap for j in range(1, m + 1): dp[0][j] = dp[0][j - 1] + gap for i in range(1, n + 1): for j in range(1, m + 1): s = match if seq1[i - 1] == seq2[j - 1] else mismatch dp[i][j] = max(dp[i - 1][j - 1] + s, dp[i - 1][j] + gap, dp[i][j - 1] + gap) # Traceback to count matches and alignment length i, j = n, m matches = 0 aligned = 0 while i > 0 or j > 0: if i > 0 and j > 0: s = match if seq1[i - 1] == seq2[j - 1] else mismatch if dp[i][j] == dp[i - 1][j - 1] + s: if seq1[i - 1] == seq2[j - 1]: matches += 1 aligned += 1 i -= 1 j -= 1 continue if i > 0 and dp[i][j] == dp[i - 1][j] + gap: aligned += 1 i -= 1 else: aligned += 1 j -= 1 return matches / aligned if aligned else 0.0 # ------------------------------------------------------------------ # Report styling # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers # ------------------------------------------------------------------ def _make_heatmap( matrix: list[list[float]], row_labels: list[str], col_labels: list[str], title: str = "", width: int = 600, height: int = 500, value_format: str = ".1f", color_scale: str = "blue", ) -> str: """Generate an SVG heatmap.""" n_rows = len(matrix) n_cols = len(matrix[0]) if matrix else 0 if not n_rows or not n_cols: return "" show_values = n_rows <= 10 and n_cols <= 10 flat = [v for row in matrix for v in row] v_min = min(flat) v_max = max(flat) v_range = v_max - v_min or 1 if color_scale == "blue": def get_color(v): t = (v - v_min) / v_range r = int(255 - t * (255 - 30)) g = int(255 - t * (255 - 58)) b = int(255 - t * (255 - 95)) return f"rgb({r},{g},{b})" else: # green def get_color(v): t = (v - v_min) / v_range r = int(255 - t * (255 - 6)) g = int(255 - t * (255 - 95)) b = int(255 - t * (255 - 70)) return f"rgb({r},{g},{b})" ml = max(80, max(len(l) for l in row_labels) * 7 + 10) if row_labels else 80 mr = 20 mt = 80 mb = 20 cw = width - ml - mr ch = height - mt - mb cell_w = cw / n_cols cell_h = ch / n_rows svg = [ f'', f'', ] if title: svg.append(f'{title}') for j, label in enumerate(col_labels): cx = ml + j * cell_w + cell_w / 2 svg.append(f'{label}') for i, row_label in enumerate(row_labels): ry = mt + i * cell_h + cell_h / 2 svg.append(f'{row_label}') for j in range(n_cols): val = matrix[i][j] color = get_color(val) cx = ml + j * cell_w cy = mt + i * cell_h svg.append(f'') if show_values: t = (val - v_min) / v_range text_color = "#fff" if t > 0.55 else "#1a1a2e" fs = min(10, int(cell_w / 4), int(cell_h / 2.5)) fs = max(7, fs) svg.append(f'{val:{value_format}}') svg.append("") return "\n".join(svg) def _make_dendrogram( names: list[str], matrix: list[list[float]], title: str = "", width: int = 700, height: int = 350, color: str = "#2563eb", ) -> str: """Generate an SVG dendrogram from a similarity matrix using UPGMA.""" n = len(names) if n < 2: return "" dist = [[1.0 - matrix[i][j] for j in range(n)] for i in range(n)] clusters = [{"members": [i], "height": 0.0, "left": None, "right": None} for i in range(n)] active = list(range(n)) while len(active) > 1: best_d = float("inf") bi, bj = 0, 1 for ii in range(len(active)): for jj in range(ii + 1, len(active)): ci, cj = active[ii], active[jj] d = 0 count = 0 for mi in clusters[ci]["members"]: for mj in clusters[cj]["members"]: d += dist[mi][mj] count += 1 avg_d = d / count if count else 0 if avg_d < best_d: best_d = avg_d bi, bj = ii, jj ci, cj = active[bi], active[bj] new_cluster = { "members": clusters[ci]["members"] + clusters[cj]["members"], "height": best_d, "left": clusters[ci], "right": clusters[cj], } clusters.append(new_cluster) new_idx = len(clusters) - 1 active.pop(bj) active.pop(bi) active.append(new_idx) root = clusters[active[0]] max_label_len = max((len(n) for n in names), default=0) ml, mr, mt, mb = max(50, max_label_len * 5 + 10), 30, 40, 80 cw = width - ml - mr ch = height - mt - mb max_h = root["height"] or 1 leaf_positions = {} leaf_counter = [0] def assign_leaves(node): if node["left"] is None and node["right"] is None: leaf_positions[node["members"][0]] = leaf_counter[0] leaf_counter[0] += 1 else: if node["left"]: assign_leaves(node["left"]) if node["right"]: assign_leaves(node["right"]) assign_leaves(root) n_leaves = len(leaf_positions) leaf_spacing = cw / max(n_leaves - 1, 1) svg = [ f'', f'', ] if title: svg.append(f'{title}') def get_x(node): if node["left"] is None and node["right"] is None: return ml + leaf_positions[node["members"][0]] * leaf_spacing return (get_x(node["left"]) + get_x(node["right"])) / 2 def get_y(h): return mt + ch - (h / max_h) * ch def draw_node(node): if node["left"] is None and node["right"] is None: return lx = get_x(node["left"]) rx = get_x(node["right"]) ly = get_y(node["left"]["height"]) ry = get_y(node["right"]["height"]) my = get_y(node["height"]) svg.append(f'') svg.append(f'') svg.append(f'') if node["left"]: draw_node(node["left"]) if node["right"]: draw_node(node["right"]) draw_node(root) for idx, pos in leaf_positions.items(): x = ml + pos * leaf_spacing svg.append( f'{names[idx]}' ) for i in range(5): d = max_h * i / 4 y = get_y(d) svg.append(f'{d:.3f}') svg.append("") return "\n".join(svg) def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 300, value_format: str = ".1f", ) -> str: """Generate an SVG grouped bar chart.""" if not labels: return "" default_colors = ["#2563eb", "#059669", "#f59e0b", "#dc2626", "#7c3aed"] colors = colors or default_colors ml, mr, mt, mb = 60, 20, 40, 80 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_min = min(all_vals) if all_vals else 0 y_max = max(all_vals) if all_vals else 1 if y_min >= 0: y_min_plot = 0 y_max_plot = y_max * 1.15 or 1 else: y_range = y_max - y_min or 1 y_min_plot = y_min - y_range * 0.05 y_max_plot = y_max + y_range * 0.15 n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - ((v - y_min_plot) / (y_max_plot - y_min_plot)) * ch svg = [ f'', f'', ] for i in range(6): y_tick = y_min_plot + (y_max_plot - y_min_plot) * i / 5 py = sy(y_tick) svg.append(f'') svg.append(f'{y_tick:{value_format}}') for gi, label in enumerate(labels): gx = ml + gi * group_width + gap for si, (name, vals) in enumerate(series.items()): color = colors[si % len(colors)] bx = gx + si * bar_width val = vals[gi] by = sy(val) bh = mt + ch - by svg.append(f'') svg.append(f'{val:{value_format}}') lx = gx + n_series * bar_width / 2 svg.append(f'{label}') if title: svg.append(f'{title}') if n_series > 1: lx = ml + cw - len(series) * 110 for si, name in enumerate(series): color = colors[si % len(colors)] svg.append(f'') svg.append(f'{name}') svg.append("") return "\n".join(svg) def _make_plddt_sparkline(values: list[float], width: int = 400, height: int = 50) -> str: """pLDDT sparkline with AlphaFold-style coloring.""" if not values or len(values) < 2: return "" pad = 4 cw = width - 2 * pad ch = height - 2 * pad seg_w = cw / len(values) svg = [ f'', ] for i, v in enumerate(values): x = pad + i * seg_w bar_h = (v / 100) * ch y = pad + ch - bar_h if v >= 90: color = "#0053d6" elif v >= 70: color = "#65cbf3" elif v >= 50: color = "#ffdb13" else: color = "#ff7d45" svg.append(f'') ref_y = pad + ch - (70 / 100) * ch svg.append(f'') svg.append("") return "\n".join(svg) def _outputs_to_pdb(outputs, sequence: str) -> str: """Convert ESMFold outputs to PDB format string.""" import numpy as np pos = outputs.positions[0] if pos.dim() == 4: pos = pos[-1] positions = pos.cpu().numpy() atom_names = ["N", "CA", "C", "O"] aa_3letter = { "A": "ALA", "R": "ARG", "N": "ASN", "D": "ASP", "C": "CYS", "Q": "GLN", "E": "GLU", "G": "GLY", "H": "HIS", "I": "ILE", "L": "LEU", "K": "LYS", "M": "MET", "F": "PHE", "P": "PRO", "S": "SER", "T": "THR", "W": "TRP", "Y": "TYR", "V": "VAL", } pdb_lines = [] atom_idx = 1 for res_idx, aa in enumerate(sequence): res_name = aa_3letter.get(aa, "UNK") for atom_i, atom_name in enumerate(atom_names): if atom_i >= positions.shape[1]: break x, y, z = positions[res_idx, atom_i] if any(math.isnan(c) for c in (x, y, z)): continue pdb_lines.append( f"ATOM {atom_idx:5d} {atom_name:<3s} {res_name} A{res_idx + 1:4d} " f"{x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 {atom_name[0]:>2s}" ) atom_idx += 1 pdb_lines.append("END") return "\n".join(pdb_lines) # ------------------------------------------------------------------ # Task 1: Load gene set # ------------------------------------------------------------------ @cpu_env.task() async def load_genes( gene_set: str = "insulin", custom_json: str = "", ) -> flyte.io.Dir: """Load a set of homologous genes from different species.""" if custom_json: data = json.loads(custom_json) elif gene_set in GENE_SETS: data = GENE_SETS[gene_set] else: available = ", ".join(GENE_SETS.keys()) raise ValueError(f"Unknown gene set '{gene_set}'. Available: {available}") log.info(f"Loaded gene set: {data['gene_name']} - {len(data['sequences'])} species") out_dir = tempfile.mkdtemp(prefix="gene_compare_") with open(os.path.join(out_dir, "genes.json"), "w") as f: json.dump(data, f) return await flyte.io.Dir.from_local(out_dir) # ------------------------------------------------------------------ # Task 2: Score sequences with Carbon # ------------------------------------------------------------------ @gpu_env.task(report=True) async def score_sequences( genes_dir: flyte.io.Dir, model_name: str = "HuggingFaceBio/Carbon-3B", ) -> str: """Score each species' gene with Carbon-3B genomic language model. Returns per-species log-likelihood scores and sequence metadata. """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer log.info(f"Loading Carbon model: {model_name}") device = "cuda" if torch.cuda.is_available() else "cpu" tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_name, trust_remote_code=True, dtype=torch.bfloat16 if device == "cuda" else torch.float32, ).to(device) model.eval() genes_path = await genes_dir.download() with open(os.path.join(genes_path, "genes.json")) as f: data = json.load(f) species_names = list(data["sequences"].keys()) n = len(species_names) scores = {} for i, species in enumerate(species_names): await flyte.report.replace.aio(_wrap_report( f"

Carbon Scoring

" f"

Scoring {species} ({i + 1}/{n})...

" ), do_flush=True) dna = data["sequences"][species]["dna"] prompt = f"{dna}" inputs = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): output = model(**inputs, labels=inputs["input_ids"]) loss = output.loss.item() ll = -loss * inputs["input_ids"].shape[1] protein = _translate(dna) scores[species] = { "log_likelihood": round(ll, 4), "loss": round(loss, 4), "gc_content": round(_gc_content(dna), 4), "length": len(dna), "protein": protein, "protein_length": len(protein), "common_name": data["sequences"][species]["common_name"], } log.info(f" {species} ({data['sequences'][species]['common_name']}): LL={ll:.2f}, GC={_gc_content(dna):.1%}") # Report html_parts = [ f"

{data['gene_name']} - Carbon Scoring

", f'
{data["description"]}
', '
', f'
{n}
Species
', f'
{data["gene_name"]}
Gene
', f'
{model_name.split("/")[-1]}
Model
', "
", ] html_parts.append( "" "" ) for species in species_names: s = scores[species] html_parts.append( f'' f'' f'' f'' ) html_parts.append("
SpeciesScientific NameDNA LengthGC%Protein LengthCarbon LL
{species}{s["common_name"]}{s["length"]}bp{s["gc_content"]:.1%}{s["protein_length"]}aa{s["log_likelihood"]:.2f}
") html_parts.append('
') html_parts.append(_make_bar_chart( species_names, {"Log-Likelihood": [scores[s]["log_likelihood"] for s in species_names]}, title="Carbon Log-Likelihood per Species", value_format=".1f", )) html_parts.append("
") await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) result = { "gene_name": data["gene_name"], "description": data["description"], "species": species_names, "scores": scores, } return json.dumps(result) # ------------------------------------------------------------------ # Task 3: Align sequences and compute similarity # ------------------------------------------------------------------ @cpu_env.task(report=True) async def align_and_compare( scores_json: str, genes_dir: flyte.io.Dir, ) -> str: """Align sequences with Needleman-Wunsch and compute pairwise identity. Translates DNA to protein, builds DNA and protein identity matrices, and generates phylogenetic trees from sequence divergence. """ scores_data = json.loads(scores_json) species_names = scores_data["species"] scores = scores_data["scores"] gene_name = scores_data["gene_name"] n = len(species_names) genes_path = await genes_dir.download() with open(os.path.join(genes_path, "genes.json")) as f: data = json.load(f) await flyte.report.replace.aio(_wrap_report( f"

{gene_name} - Sequence Alignment

" f"

Aligning {n} species with Needleman-Wunsch...

" ), do_flush=True) # Pairwise DNA identity matrix identity_matrix = [] for sp1 in species_names: row = [] for sp2 in species_names: dna1 = data["sequences"][sp1]["dna"] dna2 = data["sequences"][sp2]["dna"] identity = _sequence_identity(dna1, dna2) row.append(round(identity, 4)) identity_matrix.append(row) # Pairwise protein identity matrix protein_matrix = [] for sp1 in species_names: row = [] for sp2 in species_names: identity = _sequence_identity(scores[sp1]["protein"], scores[sp2]["protein"]) row.append(round(identity, 4)) protein_matrix.append(row) # Average pairwise identities (exclude diagonal) dna_pairs = [identity_matrix[i][j] for i in range(n) for j in range(i + 1, n)] prot_pairs = [protein_matrix[i][j] for i in range(n) for j in range(i + 1, n)] avg_dna = sum(dna_pairs) / len(dna_pairs) if dna_pairs else 0 avg_prot = sum(prot_pairs) / len(prot_pairs) if prot_pairs else 0 # Most/least similar pair best_pair = max(range(len(dna_pairs)), key=lambda k: dna_pairs[k]) worst_pair = min(range(len(dna_pairs)), key=lambda k: dna_pairs[k]) pair_indices = [(i, j) for i in range(n) for j in range(i + 1, n)] best_sp = f"{species_names[pair_indices[best_pair][0]]}-{species_names[pair_indices[best_pair][1]]}" worst_sp = f"{species_names[pair_indices[worst_pair][0]]}-{species_names[pair_indices[worst_pair][1]]}" # Report html_parts = [ f"

{gene_name} - Sequence Alignment

", f'
Pairwise alignment using Needleman-Wunsch (match=2, mismatch=-1, gap=-2). ' f"Identity is computed as matches / aligned length from the optimal global alignment.
", '
', f'
{n}
Species Aligned
', f'
{n * (n - 1) // 2}
Pairwise Alignments
', f'
{avg_dna:.0%}
Avg DNA Identity
', f'
{avg_prot:.0%}
Avg Protein Identity
', f'
{best_sp}
Most Similar
', f'
{worst_sp}
Most Divergent
', "
", ] # DNA identity heatmap html_parts.append('
') html_parts.append(_make_heatmap( identity_matrix, species_names, species_names, title="Pairwise DNA Sequence Identity (%)", value_format=".0%", )) html_parts.append("
") # Protein identity heatmap html_parts.append('
') html_parts.append(_make_heatmap( protein_matrix, species_names, species_names, title="Pairwise Protein Sequence Identity (%)", value_format=".0%", color_scale="green", )) html_parts.append("
") # DNA phylogenetic tree html_parts.append('
') html_parts.append(_make_dendrogram( species_names, identity_matrix, title=f"{gene_name} - Phylogenetic Tree (DNA Identity)", )) html_parts.append("
") # Protein phylogenetic tree html_parts.append('
') html_parts.append(_make_dendrogram( species_names, protein_matrix, title=f"{gene_name} - Phylogenetic Tree (Protein Identity)", color="#059669", )) html_parts.append("
") # DNA vs Protein conservation comparison html_parts.append('
') html_parts.append(_make_bar_chart( species_names, { "DNA vs Human": [identity_matrix[0][j] for j in range(n)], "Protein vs Human": [protein_matrix[0][j] for j in range(n)], }, title=f"Conservation vs {species_names[0]} (DNA and Protein)", value_format=".0%", )) html_parts.append("
") await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) result = { "gene_name": gene_name, "description": scores_data["description"], "species": species_names, "scores": scores, "dna_identity_matrix": identity_matrix, "protein_identity_matrix": protein_matrix, } return json.dumps(result) # ------------------------------------------------------------------ # Task 4: Fold proteins with ESMFold # ------------------------------------------------------------------ @gpu_env.task(report=True) async def fold_proteins( comparison_json: str, max_length: int = 400, ) -> str: """Fold each species' translated protein with ESMFold for 3D comparison. Returns PDB strings and pLDDT confidence scores for each species. """ import torch import numpy as np from transformers import AutoTokenizer, EsmForProteinFolding comparison = json.loads(comparison_json) species_names = comparison["species"] scores = comparison["scores"] log.info("Loading ESMFold model...") device = "cuda" if torch.cuda.is_available() else "cpu" tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1") model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1", low_cpu_mem_usage=True) model = model.to(device) model.eval() structure_data = {} n = len(species_names) for idx, species in enumerate(species_names): protein = scores[species]["protein"] if len(protein) > max_length: log.info(f"Skipping {species} ({len(protein)} aa > {max_length} max)") continue log.info(f"ESMFold [{idx + 1}/{n}]: {species} ({len(protein)} aa)") await flyte.report.replace.aio(_wrap_report( f"

ESMFold - 3D Structure Prediction

" f"

Folding {species} ({idx + 1}/{n}): {len(protein)} residues...

" ), do_flush=True) inputs = tokenizer(protein, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): outputs = model(**inputs) pdb_str = _outputs_to_pdb(outputs, protein) plddt_raw = outputs.plddt[0].cpu().numpy() if plddt_raw.ndim == 2: plddt_raw = plddt_raw[-1] plddt = plddt_raw.flatten()[:len(protein)] if plddt.max() <= 1.0: plddt = plddt * 100 plddt_mean = float(np.mean(plddt)) structure_data[species] = { "pdb_str": pdb_str, "plddt_mean": round(plddt_mean, 1), "plddt_per_residue": [round(float(v), 1) for v in plddt[:len(protein)]], "protein_length": len(protein), } log.info(f" โ†’ mean pLDDT: {plddt_mean:.1f}") # Report with 3D viewers n_folded = len(structure_data) avg_plddt = sum(d["plddt_mean"] for d in structure_data.values()) / n_folded if n_folded else 0 threeDmol_script = '' stats_html = f"""

ESMFold - Cross-Species Structure Comparison

ESMFold predicts 3D structure directly from amino acid sequence. Comparing structures across species reveals which parts of the protein are structurally conserved (functional core) vs divergent (surface loops, species-specific adaptations).
{n_folded}
Structures
{avg_plddt:.1f}
Avg pLDDT
{comparison['gene_name']}
Gene
""" viewers_html = '
' for species, sdata in structure_data.items(): plddt_val = sdata["plddt_mean"] common = scores[species]["common_name"] if plddt_val >= 90: badge = 'Very High' elif plddt_val >= 70: badge = 'Confident' elif plddt_val >= 50: badge = 'Low' else: badge = 'Disordered' plddt_sparkline = _make_plddt_sparkline(sdata["plddt_per_residue"], width=300) pdb_escaped = sdata["pdb_str"].replace("\\", "\\\\").replace("`", "\\`").replace("$", "\\$") viewer_id = f"viewer_{hash(species) & 0xFFFFFF:06x}" viewers_html += f"""

{species} ({sdata['protein_length']} aa) {badge}

{common}

Mean pLDDT: {plddt_val:.1f} / 100
{plddt_sparkline}
█ >90 █ 70-90 █ 50-70 █ <50
""" viewers_html += "
" # pLDDT comparison bar chart plddt_chart = _make_bar_chart( list(structure_data.keys()), {"Mean pLDDT": [d["plddt_mean"] for d in structure_data.values()]}, title="Structure Confidence Comparison (pLDDT)", value_format=".1f", colors=["#0053d6"], ) report_html = f""" {threeDmol_script} {stats_html} {viewers_html}
{plddt_chart}
""" await flyte.report.replace.aio(_wrap_report(report_html), do_flush=True) return json.dumps(structure_data) # ------------------------------------------------------------------ # Task 5: Generate summary # ------------------------------------------------------------------ @cpu_env.task(report=True) async def generate_summary( comparison_json: str, structures_json: str, ) -> str: """Generate comprehensive cross-species summary.""" comparison = json.loads(comparison_json) structures = json.loads(structures_json) species = comparison["species"] scores = comparison["scores"] gene_name = comparison["gene_name"] dna_matrix = comparison["dna_identity_matrix"] protein_matrix = comparison["protein_identity_matrix"] html_parts = [ f"

{gene_name} - Cross-Species Evolution Summary

", f'
{comparison["description"]}
', ] # Key metrics # Average pairwise identity (exclude diagonal) n = len(species) dna_pairs = [dna_matrix[i][j] for i in range(n) for j in range(i + 1, n)] protein_pairs = [protein_matrix[i][j] for i in range(n) for j in range(i + 1, n)] avg_dna_id = sum(dna_pairs) / len(dna_pairs) if dna_pairs else 0 avg_protein_id = sum(protein_pairs) / len(protein_pairs) if protein_pairs else 0 avg_plddt = sum(d["plddt_mean"] for d in structures.values()) / len(structures) if structures else 0 html_parts.append('
') html_parts.append(f'
{n}
Species
') html_parts.append(f'
{avg_dna_id:.0%}
Avg DNA Identity
') html_parts.append(f'
{avg_protein_id:.0%}
Avg Protein Identity
') html_parts.append(f'
{avg_plddt:.1f}
Avg pLDDT
') html_parts.append(f'
{len(structures)}
Structures Folded
') html_parts.append("
") # Full comparison table html_parts.append("

Per-Species Detail

") html_parts.append( "" "" ) for sp in species: s = scores[sp] plddt = structures.get(sp, {}).get("plddt_mean", "N/A") plddt_str = f"{plddt:.1f}" if isinstance(plddt, float) else plddt html_parts.append( f'' f'' f'' f'' ) html_parts.append("
SpeciesScientific NameDNA (bp)Protein (aa)GC%Carbon LLpLDDT
{sp}{s["common_name"]}{s["length"]}{s["protein_length"]}{s["gc_content"]:.1%}{s["log_likelihood"]:.2f}{plddt_str}
") # GC content comparison html_parts.append('
') html_parts.append(_make_bar_chart( species, {"GC Content": [scores[s]["gc_content"] for s in species]}, title="GC Content Across Species", value_format=".2f", )) html_parts.append("
") # DNA phylogenetic tree html_parts.append("

Phylogenetic Relationships

") html_parts.append( '
' "Trees built from pairwise sequence identity using UPGMA clustering. " "Species that diverged more recently cluster together. DNA and protein trees " "may differ when synonymous mutations dominate." "
" ) html_parts.append('
') html_parts.append(_make_dendrogram( species, dna_matrix, title=f"{gene_name} - DNA Phylogenetic Tree", )) html_parts.append("
") html_parts.append('
') html_parts.append(_make_dendrogram( species, protein_matrix, title=f"{gene_name} - Protein Phylogenetic Tree", color="#059669", )) html_parts.append("
") await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) summary = { "gene_name": gene_name, "n_species": n, "avg_dna_identity": round(avg_dna_id, 4), "avg_protein_identity": round(avg_protein_id, 4), "avg_plddt": round(avg_plddt, 1), "n_structures": len(structures), } return json.dumps(summary) # ------------------------------------------------------------------ # Pipeline orchestrator # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @cpu_env.task(report=True) async def pipeline( gene_set: str = "insulin", model_name: str = "HuggingFaceBio/Carbon-3B", custom_json: str = "", ) -> tuple[str, str]: """ End-to-end cross-species gene comparison pipeline. Returns (comparison JSON, structures JSON). 1. Load homologous gene sequences across species 2. Score with Carbon genomic language model 3. Align sequences and compute pairwise similarity 4. Fold translated proteins with ESMFold 5. Generate comprehensive summary with phylogenetic trees """ log.info(f"Starting cross-species gene comparison pipeline (gene_set={gene_set})...") def _pipeline_progress(step: int, label: str) -> str: steps = [ "Load Genes", "Carbon Scoring", "Sequence Alignment", "ESMFold Structures", "Generate Summary", ] dots = "" for i, s in enumerate(steps): if i + 1 < step: icon = '✓' elif i + 1 == step: icon = '●' else: icon = '○' dots += f"{icon} {s}" return f"""

Cross-Species Gene Comparison

{dots}

{label}

""" # Stage 1 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(1, "Loading homologous gene sequences...")), do_flush=True, ) genes_dir = await load_genes(gene_set=gene_set, custom_json=custom_json) # Stage 2 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(2, "Scoring sequences with Carbon...")), do_flush=True, ) scores_json = await score_sequences(genes_dir=genes_dir, model_name=model_name) # Stage 3 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(3, "Aligning sequences with Needleman-Wunsch...")), do_flush=True, ) comparison_json = await align_and_compare(scores_json=scores_json, genes_dir=genes_dir) # Stage 4 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(4, "Folding proteins with ESMFold...")), do_flush=True, ) structures_json = await fold_proteins(comparison_json=comparison_json) # Stage 5 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(5, "Generating summary report...")), do_flush=True, ) summary_json = await generate_summary( comparison_json=comparison_json, structures_json=structures_json, ) # Final report summary = json.loads(summary_json) comparison = json.loads(comparison_json) final_html = f"""

Pipeline Complete

{summary['gene_name']}
Gene
{summary['n_species']}
Species
{summary['avg_dna_identity']:.0%}
Avg DNA Identity
{summary['avg_protein_identity']:.0%}
Avg Protein Identity
{summary['avg_plddt']:.1f}
Avg pLDDT
{summary['n_structures']}
3D Structures
Gene: {summary['gene_name']} | Species: {', '.join(comparison['species'])} | Model: {model_name}
All 4 pipeline stages completed. View individual task reports for DNA/protein identity heatmaps, phylogenetic trees, interactive 3D protein structures with pLDDT confidence, Carbon log-likelihood scores, and evolutionary analysis.
""" await flyte.report.replace.aio(_wrap_report(final_html), do_flush=True) log.info("Pipeline complete.") return comparison_json, structures_json # {{/docs-fragment pipeline}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_gene_comparison/genomic_gene_comparison.py* Dependencies are declared at the top of the file using the `uv` script style: CODE0 ## Orchestrate the pipeline The top-level `pipeline` task chains five stages: load genes, Carbon scoring, sequence alignment, ESMFold folding, and a cross-species summary report. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "torch>=2.9.0", # "transformers>=4.49.0", # "accelerate>=0.34.0", # "numpy", # ] # main = "pipeline" # params = "" # /// import json import logging import math import os import tempfile import flyte import flyte.io import flyte.report # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="genomic-gene-comparison", pre=True) gpu_env = flyte.TaskEnvironment( name="genomic-gene-comparison-gpu", image=main_img, resources=flyte.Resources(cpu=4, memory="32Gi", gpu=1), ) cpu_env = flyte.TaskEnvironment( name="genomic-gene-comparison-cpu", image=main_img, resources=flyte.Resources(cpu=2, memory="8Gi"), depends_on=[gpu_env], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Homologous gene sets - same gene across species # ------------------------------------------------------------------ # Full-length coding sequences from NCBI RefSeq (stop codon excluded). GENE_SETS = { "insulin": { "gene_name": "Insulin", "description": "Insulin regulates blood sugar in all vertebrates. Highly conserved across 500M+ years of evolution - even fish insulin can lower blood sugar in humans. Comparing across species reveals which regions are functionally essential (conserved) vs free to drift.", "sequences": { "Human": { "dna": "ATGGCCCTGTGGATGCGCCTCCTGCCCCTGCTGGCGCTGCTGGCCCTCTGGGGACCTGACCCAGCCGCAGCCTTTGTGAACCAACACCTGTGCGGCTCACACCTGGTGGAAGCTCTCTACCTAGTGTGCGGGGAACGAGGCTTCTTCTACACACCCAAGACCCGCCGGGAGGCAGAGGACCTGCAGGTGGGGCAGGTGGAGCTGGGCGGGGGCCCTGGTGCAGGCAGCCTGCAGCCCTTGGCCCTGGAGGGGTCCCTGCAGAAGCGTGGCATTGTGGAACAATGCTGTACCAGCATCTGCTCCCTCTACCAGCTGGAGAACTACTGCAAC", "common_name": "Homo sapiens", }, "Mouse": { "dna": "ATGGCCCTGTGGATGCGCTTCCTGCCCCTGCTGGCCCTGCTCTTCCTCTGGGAGTCCCACCCCACCCAGGCTTTTGTCAAGCAGCACCTTTGTGGTTCCCACCTGGTGGAGGCTCTCTACCTGGTGTGTGGGGAGCGTGGCTTCTTCTACACACCCATGTCCCGCCGTGAAGTGGAGGACCCACAAGTGGCACAACTGGAGCTGGGTGGAGGCCCGGGAGCAGGTGACCTTCAGACCTTGGCACTGGAGGTGGCCCAGCAGAAGCGTGGCATTGTAGATCAGTGCTGCACCAGCATCTGCTCCCTCTACCAGCTGGAGAACTACTGCAAC", "common_name": "Mus musculus", }, "Chicken": { "dna": "ATGGCTCTCTGGATCCGATCACTGCCTCTTCTGGCTCTCCTTGTCTTTTCTGGCCCTGGAACCAGCTATGCAGCTGCCAACCAGCACCTCTGTGGCTCCCACTTGGTGGAGGCTCTCTACCTGGTGTGTGGAGAGCGTGGCTTCTTCTACTCCCCCAAAGCCCGACGGGATGTCGAGCAGCCCCTAGTGAGCAGTCCCTTGCGTGGCGAGGCAGGAGTGCTGCCTTTCCAGCAGGAGGAATACGAGAAAGTCAAGCGAGGGATTGTTGAGCAATGCTGCCATAACACGTGTTCCCTCTACCAACTGGAGAACTACTGCAAC", "common_name": "Gallus gallus", }, "Zebrafish": { "dna": "ATGGCAGTGTGGCTTCAGGCTGGTGCTCTGTTGGTCCTGTTGGTCGTGTCCAGTGTAAGCACTAACCCAGGCACACCGCAGCACCTGTGTGGATCTCATCTGGTCGATGCCCTTTATCTGGTCTGTGGCCCAACAGGCTTCTTCTACAACCCCAAGAGAGACGTTGAGCCCCTTCTGGGTTTCCTTCCTCCTAAATCTGCCCAGGAAACTGAGGTGGCTGACTTTGCATTTAAAGATCATGCCGAGCTGATAAGGAAGAGAGGCATTGTAGAGCAGTGCTGCCACAAACCCTGCAGCATCTTTGAGCTGCAGAACTACTGTAAC", "common_name": "Danio rerio", }, "Frog": { "dna": "ATGGCTCTATGGATGCAGTGTCTGCCCCTGGTTCTTGTCCTCTTTTTCTCTACACCCAACACCGAAGCTCTAGTTAACCAGCACTTGTGTGGGTCTCACCTGGTAGAAGCCCTGTACTTAGTATGTGGGGATCGAGGCTTCTTCTACTACCCTAAGGTCAAACGGGACATGGAACAAGCACTTGTCAGTGGACCCCAGGATAATGAGTTGGATGGAATGCAGCTCCAGCCTCAGGAGTATCAGAAAATGAAGAGGGGGATTGTGGAGCAATGTTGCCACAGCACATGTTCTCTCTTCCAGCTGGAGAGTTACTGCAAC", "common_name": "Xenopus laevis", }, "Cow": { "dna": "ATGGCCCTGTGGACACGCCTGGCGCCCCTGCTGGCCCTGCTGGCGCTCTGGGCCCCCGCCCCGGCCCGCGCCTTCGTCAACCAGCATCTGTGTGGCTCCCACCTGGTGGAGGCGCTGTACCTGGTGTGCGGAGAGCGCGGCTTCTTCTACACGCCCAAGGCCCGCCGGGAGGTGGAGGGCCCCCAGGTGGGGGCGCTGGAGCTGGCCGGAGGCCCGGGCGCGGGCGGCCTGGAGGGGCCCCCGCAGAAGCGTGGCATCGTGGAGCAGTGCTGTGCCAGCGTCTGCTCGCTCTACCAGCTGGAGAACTACTGTAAC", "common_name": "Bos taurus", }, }, }, "hemoglobin": { "gene_name": "Hemoglobin Beta", "description": "Beta-globin carries oxygen from lungs to tissues. The most studied gene in molecular evolution - sequence differences power the 'molecular clock' hypothesis. Sickle cell mutation (E6V) in humans shows how a single base change creates devastating disease.", "sequences": { "Human": { "dna": "ATGGTGCATCTGACTCCTGAGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTGGTCTACCCTTGGACCCAGAGGTTCTTTGAGTCCTTTGGGGATCTGTCCACTCCTGATGCTGTTATGGGCAACCCTAAGGTGAAGGCTCATGGCAAGAAAGTGCTCGGTGCCTTTAGTGATGGCCTGGCTCACCTGGACAACCTCAAGGGCACCTTTGCCACACTGAGTGAGCTGCACTGTGACAAGCTGCACGTGGATCCTGAGAACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTCACCCCACCAGTGCAGGCTGCCTATCAGAAAGTGGTGGCTGGTGTGGCTAATGCCCTGGCCCACAAGTATCAC", "common_name": "Homo sapiens", }, "Mouse": { "dna": "ATGGTGCACCTGACTGATGCTGAGAAGGCTGCTGTCTCTGGCCTGTGGGGAAAGGTGAACGCCGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTTGTCTACCCTTGGACCCAGCGGTACTTTGATAGCTTTGGAGACCTATCCTCTGCCTCTGCTATCATGGGTAATGCCAAAGTGAAGGCCCATGGCAAGAAAGTGATAACTGCCTTTAACGATGGCCTGAATCACTTGGACAGCCTCAAGGGCACCTTTGCCAGCCTCAGTGAGCTCCACTGTGACAAGCTGCATGTGGATCCTGAGAACTTCAGGCTCCTGGGCAATATGATCGTGATTGTGCTGGGCCACCACCTGGGCAAGGATTTCACCCCCGCTGCACAGGCTGCCTTCCAGAAGGTGGTGGCTGGAGTGGCTGCTGCCCTGGCTCACAAGTACCAC", "common_name": "Mus musculus", }, "Chicken": { "dna": "ATGGTGCACTGGACTGCTGAGGAGAAGCAGCTCATCACCGGCCTCTGGGGCAAGGTCAATGTGGCCGAATGTGGGGCTGAAGCCCTGGCCAGGCTGCTGATCGTCTACCCCTGGACCCAGAGGTTCTTTGCGTCCTTTGGGAACCTCTCCAGCCCCACTGCCATCCTTGGCAACCCCATGGTCCGCGCCCATGGCAAGAAAGTGCTCACCTCCTTTGGGGATGCTGTGAAGAACCTGGACAACATCAAGAACACCTTCTCCCAACTGTCCGAACTGCATTGTGACAAGCTGCATGTGGACCCCGAGAACTTCAGGCTCCTGGGTGACATCCTCATCATTGTCCTGGCCGCCCACTTCAGCAAGGACTTCACTCCTGAATGCCAGGCTGCCTGGCAGAAGCTGGTCCGCGTGGTGGCCCATGCCCTGGCTCGCAAGTACCAC", "common_name": "Gallus gallus", }, "Zebrafish": { "dna": "ATGGTTGAGTGGACAGATGCCGAGCGCACAGCCATCCTTGGCCTGTGGGGAAAGCTCAATATCGATGAAATCGGACCTCAGGCCCTATCCAGATGTCTGATCGTGTATCCCTGGACTCAGAGATATTTCGCCACATTCGGCAACCTGTCAAGCCCCGCTGCGATCATGGGTAACCCCAAAGTGGCAGCTCATGGGAGGACTGTGATGGGAGGTCTTGAGAGAGCCATCAAGAACATGGACAACGTCAAGAACACCTATGCCGCCCTCAGTGTGATGCACTCTGAGAAACTGCATGTGGATCCCGACAACTTCAGGCTTCTCGCTGATTGCATCACCGTTTGCGCTGCCATGAAGTTCGGCCAAGCTGGTTTCAATGCTGATGTCCAGGAGGCCTGGCAGAAGTTTCTGGCTGTGGTCGTTTCTGCTCTGTGCAGACAGTACCAC", "common_name": "Danio rerio", }, "Frog": { "dna": "ATGGTTCATTGGACAGCTGAAGAGAAGGCCGCCATCACCTCTGTGTGGCAGGAGGTCAACCAGGAGCAAGATGGCCATGATGCACTCACAAGGCTGCTGGTTGTGTACCCCTGGACCCAGAGATACTTCAGCAGTTTTGGAAATCTCGGTAATGCCACAGCTATTGCTGGAAATGTCAAGGTGCGTGCCCATGGCAAGAAGGTTCTTTCAGCTGTTGGTGATGCCATCGCCCATCTTGACAACGTGAAGGGAACTCTCCATGACCTCAGTGTGGTCCACGCCTTCAAGCTCTATGTGGATCCTGAGAACTTCAAGCGTCTTGGTGAAGTTCTGGTCATTGTCTTGGCTTCCAAACTGGGATCAGCCTTTACTCCTCAAGTCCAGGGAGCCTGGGAGAAATTTGTTGCTGTTCTGGTTGATGCCCTCAGCCAAGGATACAAC", "common_name": "Xenopus laevis", }, "Cow": { "dna": "ATGCTGACTGCTGAGGAGAAGGCTGCCGTCACCGCCTTTTGGGGCAAGGTGAAAGTGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTTGTCTACCCCTGGACTCAGAGGTTCTTTGAGTCCTTTGGGGACTTGTCCACTGCTGATGCTGTTATGAACAACCCTAAGGTGAAGGCCCATGGCAAGAAGGTGCTAGATTCCTTTAGTAATGGCATGAAGCATCTCGATGACCTCAAGGGCACCTTTGCTGCGCTGAGTGAGCTGCACTGTGATAAGCTGCATGTGGATCCTGAGAACTTCAAGCTCCTGGGCAACGTGCTAGTGGTTGTGCTGGCTCGCAATTTTGGCAAGGAATTCACCCCGGTGCTGCAGGCTGACTTTCAGAAGGTGGTGGCTGGTGTGGCCAATGCCCTGGCCCACAGATATCAT", "common_name": "Bos taurus", }, }, }, "p53": { "gene_name": "p53 (TP53)", "description": "The 'guardian of the genome' - p53 detects DNA damage and triggers repair or cell death. Mutated in >50% of human cancers. Elephants have 20 copies of p53 (humans have 1), which may explain their extremely low cancer rates despite their size (Peto's paradox).", "sequences": { "Human": { "dna": "ATGGAGGAGCCGCAGTCAGATCCTAGCGTCGAGCCCCCTCTGAGTCAGGAAACATTTTCAGACCTATGGAAACTACTTCCTGAAAACAACGTTCTGTCCCCCTTGCCGTCCCAAGCAATGGATGATTTGATGCTGTCCCCGGACGATATTGAACAATGGTTCACTGAAGACCCAGGTCCAGATGAAGCTCCCAGAATGCCAGAGGCTGCTCCCCCCGTGGCCCCTGCACCAGCAGCTCCTACACCGGCGGCCCCTGCACCAGCCCCCTCCTGGCCCCTGTCATCTTCTGTCCCTTCCCAGAAAACCTACCAGGGCAGCTACGGTTTCCGTCTGGGCTTCTTGCATTCTGGGACAGCCAAGTCTGTGACTTGCACGTACTCCCCTGCCCTCAACAAGATGTTTTGCCAACTGGCCAAGACCTGCCCTGTGCAGCTGTGGGTTGATTCCACACCCCCGCCCGGCACCCGCGTCCGCGCCATGGCCATCTACAAGCAGTCACAGCACATGACGGAGGTTGTGAGGCGCTGCCCCCACCATGAGCGCTGCTCAGATAGCGATGGTCTGGCCCCTCCTCAGCATCTTATCCGAGTGGAAGGAAATTTGCGTGTGGAGTATTTGGATGACAGAAACACTTTTCGACATAGTGTGGTGGTGCCCTATGAGCCGCCTGAGGTTGGCTCTGACTGTACCACCATCCACTACAACTACATGTGTAACAGTTCCTGCATGGGCGGCATGAACCGGAGGCCCATCCTCACCATCATCACACTGGAAGACTCCAGTGGTAATCTACTGGGACGGAACAGCTTTGAGGTGCGTGTTTGTGCCTGTCCTGGGAGAGACCGGCGCACAGAGGAAGAGAATCTCCGCAAGAAAGGGGAGCCTCACCACGAGCTGCCCCCAGGGAGCACTAAGCGAGCACTGCCCAACAACACCAGCTCCTCTCCCCAGCCAAAGAAGAAACCACTGGATGGAGAATATTTCACCCTTCAGATCCGTGGGCGTGAGCGCTTCGAGATGTTCCGAGAGCTGAATGAGGCCTTGGAACTCAAGGATGCCCAGGCTGGGAAGGAGCCAGGGGGGAGCAGGGCTCACTCCAGCCACCTGAAGTCCAAAAAGGGTCAGTCTACCTCCCGCCATAAAAAACTCATGTTCAAGACAGAAGGGCCTGACTCAGAC", "common_name": "Homo sapiens", }, "Mouse": { "dna": "ATGACTGCCATGGAGGAGTCACAGTCGGATATCAGCCTCGAGCTCCCTCTGAGCCAGGAGACATTTTCAGGCTTATGGAAACTACTTCCTCCAGAAGATATCCTGCCATCACCTCACTGCATGGACGATCTGTTGCTGCCCCAGGATGTTGAGGAGTTTTTTGAAGGCCCAAGTGAAGCCCTCCGAGTGTCAGGAGCTCCTGCAGCACAGGACCCTGTCACCGAGACCCCTGGGCCAGTGGCCCCTGCCCCAGCCACTCCATGGCCCCTGTCATCTTTTGTCCCTTCTCAAAAAACTTACCAGGGCAACTATGGCTTCCACCTGGGCTTCCTGCAGTCTGGGACAGCCAAGTCTGTTATGTGCACGTACTCTCCTCCCCTCAATAAGCTATTCTGCCAGCTGGCGAAGACGTGCCCTGTGCAGTTGTGGGTCAGCGCCACACCTCCAGCTGGGAGCCGTGTCCGCGCCATGGCCATCTACAAGAAGTCACAGCACATGACGGAGGTCGTGAGACGCTGCCCCCACCATGAGCGCTGCTCCGATGGTGATGGCCTGGCTCCTCCCCAGCATCTTATCCGGGTGGAAGGAAATTTGTATCCCGAGTATCTGGAAGACAGGCAGACTTTTCGCCACAGCGTGGTGGTACCTTATGAGCCACCCGAGGCCGGCTCTGAGTATACCACCATCCACTACAAGTACATGTGTAATAGCTCCTGCATGGGGGGCATGAACCGCCGACCTATCCTTACCATCATCACACTGGAAGACTCCAGTGGGAACCTTCTGGGACGGGACAGCTTTGAGGTTCGTGTTTGTGCCTGCCCTGGGAGAGACCGCCGTACAGAAGAAGAAAATTTCCGCAAAAAGGAAGTCCTTTGCCCTGAACTGCCCCCAGGGAGCGCAAAGAGAGCGCTGCCCACCTGCACAAGCGCCTCTCCCCCGCAAAAGAAAAAACCACTTGATGGAGAGTATTTCACCCTCAAGATCCGCGGGCGTAAACGCTTCGAGATGTTCCGGGAGCTGAATGAGGCCTTAGAGTTAAAGGATGCCCATGCTACAGAGGAGTCTGGAGACAGCAGGGCTCACTCCAGCTACCTGAAGACCAAGAAGGGCCAGTCTACTTCCCGCCATAAAAAAACAATGGTCAAGAAAGTGGGGCCTGACTCAGAC", "common_name": "Mus musculus", }, "Chicken": { "dna": "ATGGCGGAGGAGATGGAACCATTGCTGGAACCCACTGAGGTCTTCATGGACCTCTGGAGCATGCTCCCCTATAGCATGCAACAGCTGCCCCTCCCTGAGGATCACAGCAACTGGCAGGAGCTGAGCCCCCTGGAACCCAGCGACCCCCCCCCACCACCGCCACCACCACCTCTGCCATTGGCCGCCGCCGCCCCCCCCCCATTAAACCCCCCCACCCCCCCCCGCGCTGCCCCCTCCCCGGTGGTCCCATCCACGGAGGATTATGGGGGGGACTTCGACTTCCGGGTGGGGTTCGTGGAGGCGGGCACAGCCAAATCGGTCACCTGCACTTACTCCCCGGTGCTGAATAAGGTCTATTGCCGCCTGGCCAAGCCGTGCCCGGTGCAGGTGAGGGTGGGGGTGGCGCCCCCCCCCGGTTCCTCCCTCCGCGCCGTGGCCGTCTATAAGAAATCAGAGCACGTGGCCGAAGTGGTGCGGCGCTGCCCCCACCACGAGCGCTGCGGGGGGGGCACCGACGGCCTGGCCCCCGCACAGCACCTCATCCGGGTGGAGGGGAACCCCCAGGCGCGTTACCACGACGACGAGACCACCAAACGGCACAGCGTCGTCGTCCCCTATGAGCCCCCCGAGGTGGGCTCTGACTGTACCACGGTGCTGTACAACTTCATGTGCAACAGTTCCTGCATGGGGGGGATGAACCGCCGCCCCATCCTCACCATCCTTACACTGGAGGGGCCGGGGGGGCAGCTGTTGGGGCGGCGCTGCTTCGAGGTGCGCGTGTGCGCATGTCCGGGGAGGGACCGCAAGATCGAGGAGGAGAACTTCCGCAAGAGGGGCGGGGCCGGGGGCGTGGCTAAGCGAGCCATGTCGCCCCCAACCGAAGCCCCCGAGCCCCCCAAGAAGCGCGTGCTGAACCCCGACAATGAGATATTCTACCTGCAGGTGCGCGGGCGCCGCCGCTATGAGATGCTGAAGGAGATCAATGAGGCGCTGCAGCTCGCCGAGGGGGGGTCCGCACCGCGGCCTTCCAAAGGCCGCCGTGTGAAGGTGGAGGGACCCCAACCCAGCTGCGGGAAGAAACTGCTGCAAAAAGGCTCGGAC", "common_name": "Gallus gallus", }, "Zebrafish": { "dna": "ATGGCGCAAAACGACAGCCAAGAGTTCGCGGAGCTCTGGGAGAAGAATTTGATTATTCAGCCCCCAGGTGGTGGCTCTTGCTGGGACATCATTAATGATGAGGAGTACTTGCCGGGATCGTTTGACCCCAATTTTTTTGAAAATGTGCTTGAAGAACAGCCTCAGCCATCCACTCTCCCACCAACATCCACTGTTCCGGAGACAAGCGACTATCCCGGCGATCATGGATTTAGGCTCAGGTTCCCGCAGTCTGGCACAGCAAAATCTGTAACTTGCACTTATTCACCGGACCTGAATAAACTCTTCTGTCAGCTGGCAAAAACTTGCCCCGTTCAAATGGTGGTGGACGTTGCCCCTCCACAGGGCTCCGTGGTTCGAGCCACTGCCATCTATAAGAAGTCCGAGCATGTGGCTGAAGTGGTCCGCAGATGCCCCCATCATGAGCGAACCCCGGATGGAGATAACTTGGCGCCTGCTGGTCATTTGATAAGAGTGGAGGGCAATCAGCGAGCAAATTACAGGGAAGATAACATCACTTTAAGGCATAGTGTTTTTGTCCCATATGAAGCACCACAGCTTGGTGCTGAATGGACAACTGTGCTACTAAACTACATGTGCAATAGCAGCTGCATGGGGGGGATGAACCGCAGGCCCATCCTCACAATCATCACTCTGGAGACTCAGGAAGGTCAGTTGCTGGGCCGGAGGTCTTTTGAGGTGCGTGTGTGTGCATGTCCAGGCAGAGACAGGAAAACTGAGGAGAGCAACTTCAAGAAAGACCAAGAGACCAAAACCATGGCCAAAACCACCACTGGGACCAAACGTAGTTTGGTGAAAGAATCTTCTTCAGCTACATTACGACCTGAGGGGAGCAAAAAGGCCAAGGGCTCCAGCAGCGATGAGGAGATCTTTACCCTGCAGGTGAGGGGCAGGGAGCGTTATGAAATTTTAAAGAAATTGAACGACAGTCTGGAGTTAAGTGATGTGGTGCCTGCCTCAGATGCTGAAAAGTATCGTCAGAAATTCATGACAAAAAACAAAAAAGAGAATCGTGAATCATCTGAGCCCAAACAGGGAAAGAAGCTGATGGTGAAGGACGAAGGAAGAAGCGACTCTGAT", "common_name": "Danio rerio", }, "Elephant": { "dna": "ATGGAGGAGCCCCAGTCAGATCTCAGCACCGAGCTCCCTCTGAGTCAAGAGACGTTTTCATACTTATGGGAACTCCTTCCTGAGAATCCGGTTCTGTCCCCCACACTACCCCCGGCAGTGGAGGTCATGGACGATCTGCTACTCTCAGAAGACACTGCAAACTGGCTAGAAAGCCAAGTTGAGGCTCAGGGAATGTCCACAACCCCTGCACCAGCCACCCCTACACCGGTGGCCCCCGCACCAGCCACCTCCTGGACCCTGTCATCTTCCGTCCCTTCCCAAAAGACCTACCCTGGCACCTATGGTTTCCGTCTGGGCTTCCTACATTCTGGGACAGCCAAGTCCGTCACCTGCACGTACTCCCCTGACCTTAACAAGCTGTTTTGCCAGCTGGCAAAAACCTGCCCAGTGCAGCTGTGGGTCGCCTCACCACCCCCGCCCGGCACCCGTGTTCGCACCATGGCCATCTACAAGAAGTCAGAGCATATGACGGAGGTCGTCAAGCGCTGCCCCCACCATGAGCGCTGCTCTGACTCTAGCGATGGCCTGGCCCCTCCTCAGCACCTCATCCGGGTGGAAGGAAACCTGCGTGCTGAGTATCTGGAGGACAGCATCACTCTCCGACACAGTGTGGTGGTGCCCTACGAGCCGCCCGAGGTTGGGTCTGACTGTACCACCATCCACTTCAACTTCATGTGTAACAGCTCCTGCATGGGGGGCATGAACCGGCGGCCCATCCTCACCATCATCACACTGGAAGACTCCAGTGGTAATCTGCTGGGACGTAACAGCTTTGAGGTGCGCATTTGTGCCTGTCCTGGAAGAGACAGACGTACAGAAGAAGAAAATTTCCACAAGAAGGGAGAGCCTTGCCCAGAGCCGCCACCCCCTGGGAGGAGCACTAAGCGAGCACTGCCCACCAACACCAGCTCCTCTACCCAGCCAAAGAAGAAGCCACTGGATGAAGAATATTTCACCCTTCAGATCCGTGGGCGTGAACGCTTCAAGATGTTCCTAGAGCTAAATGAGGCCTTGGAGCTGAAGGATGCCCAGGCTGGGAAGGAGCCAGAGGGGAGCCGGGCTCACTCCAGCCCTTCGAAGTCTAAGAAGGGACAGTCTACCTCCCGCCATAAAAAACCAATGTTCAAGAGAGAGGGACCTGACTCAGAC", "common_name": "Loxodonta africana", }, "Dog": { "dna": "ATGGAGGAGTCGCAGTCAGAGCTCAATATCGACCCCCCTCTGAGCCAGGAGACATTTTCAGAATTGTGGAACCTGCTTCCTGAAAACAATGTTCTGTCTTCGGAGCTGTGCCCAGCAGTGGATGAGCTGCTGCTCCCAGAGAGCGTCGTGAACTGGCTAGACGAAGACTCAGATGATGCTCCCAGGATGCCAGCCACTTCTGCCCCCACAGCCCCTGGACCGGCCCCCTCGTGGCCCCTATCATCCTCTGTCCCTTCCCCGAAGACCTACCCTGGCACCTATGGGTTCCGTTTGGGGTTCCTGCATTCCGGGACAGCCAAGTCTGTTACTTGGACGTACTCCCCTCTCCTCAACAAGTTGTTTTGCCAGCTGGCGAAGACCTGCCCCGTGCAGCTGTGGGTCAGCTCCCCACCCCCACCCAATACCTGCGTCCGCGCTATGGCCATCTATAAGAAGTCGGAGTTCGTGACCGAGGTTGTGCGGCGCTGCCCCCACCATGAACGCTGCTCTGACAGTAGTGACGGTCTTGCCCCTCCTCAGCATCTCATCCGAGTGGAAGGAAATTTGCGGGCCAAGTACCTGGACGACAGAAACACTTTTCGACACAGTGTGGTGGTGCCTTATGAGCCACCCGAGGTTGGCTCTGACTATACCACCATCCACTACAACTACATGTGTAACAGTTCCTGCATGGGAGGCATGAACCGGCGGCCCATCCTCACTATCATCACCCTGGAAGACTCCAGTGGAAACGTGCTGGGACGCAACAGCTTTGAGGTACGCGTTTGTGCCTGTCCCGGGAGAGACCGCCGGACTGAGGAGGAGAATTTCCACAAGAAGGGGGAGCCTTGTCCTGAGCCACCCCCCGGGAGTACCAAGCGAGCACTGCCTCCCAGCACCAGCTCCTCTCCCCCGCAAAAGAAGAAGCCACTAGATGGAGAATATTTCACCCTTCAGATCCGTGGGCGTGAACGCTATGAGATGTTCAGGAATCTGAATGAAGCCTTGGAGCTGAAGGATGCCCAGAGTGGAAAGGAGCCAGGGGGAAGCAGGGCTCACTCCAGCCACCTGAAGGCAAAGAAGGGGCAATCTACCTCTCGCCATAAAAAACTGATGTTCAAGAGAGAAGGGCTTGACTCAGAC", "common_name": "Canis lupus familiaris", }, }, }, } # Standard genetic code CODON_TABLE = { "TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L", "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L", "ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M", "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V", "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S", "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P", "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T", "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A", "TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*", "CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q", "AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K", "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E", "TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W", "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R", "AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R", "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G", } BASE_COLORS = {"A": "#2ecc71", "T": "#e74c3c", "G": "#f39c12", "C": "#3498db"} def _translate(dna: str) -> str: """Translate DNA to protein in reading frame 0.""" dna = dna.upper() protein = [] for i in range(0, len(dna) - 2, 3): codon = dna[i:i + 3] aa = CODON_TABLE.get(codon, "X") if aa == "*": break protein.append(aa) return "".join(protein) def _gc_content(seq: str) -> float: if not seq: return 0.0 return sum(1 for b in seq.upper() if b in "GC") / len(seq) def _sequence_identity(seq1: str, seq2: str, match: int = 2, mismatch: int = -1, gap: int = -2) -> float: """Percent identity via Needleman-Wunsch global alignment.""" if not seq1 or not seq2: return 0.0 n, m = len(seq1), len(seq2) # Build score matrix dp = [[0] * (m + 1) for _ in range(n + 1)] for i in range(1, n + 1): dp[i][0] = dp[i - 1][0] + gap for j in range(1, m + 1): dp[0][j] = dp[0][j - 1] + gap for i in range(1, n + 1): for j in range(1, m + 1): s = match if seq1[i - 1] == seq2[j - 1] else mismatch dp[i][j] = max(dp[i - 1][j - 1] + s, dp[i - 1][j] + gap, dp[i][j - 1] + gap) # Traceback to count matches and alignment length i, j = n, m matches = 0 aligned = 0 while i > 0 or j > 0: if i > 0 and j > 0: s = match if seq1[i - 1] == seq2[j - 1] else mismatch if dp[i][j] == dp[i - 1][j - 1] + s: if seq1[i - 1] == seq2[j - 1]: matches += 1 aligned += 1 i -= 1 j -= 1 continue if i > 0 and dp[i][j] == dp[i - 1][j] + gap: aligned += 1 i -= 1 else: aligned += 1 j -= 1 return matches / aligned if aligned else 0.0 # ------------------------------------------------------------------ # Report styling # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers # ------------------------------------------------------------------ def _make_heatmap( matrix: list[list[float]], row_labels: list[str], col_labels: list[str], title: str = "", width: int = 600, height: int = 500, value_format: str = ".1f", color_scale: str = "blue", ) -> str: """Generate an SVG heatmap.""" n_rows = len(matrix) n_cols = len(matrix[0]) if matrix else 0 if not n_rows or not n_cols: return "" show_values = n_rows <= 10 and n_cols <= 10 flat = [v for row in matrix for v in row] v_min = min(flat) v_max = max(flat) v_range = v_max - v_min or 1 if color_scale == "blue": def get_color(v): t = (v - v_min) / v_range r = int(255 - t * (255 - 30)) g = int(255 - t * (255 - 58)) b = int(255 - t * (255 - 95)) return f"rgb({r},{g},{b})" else: # green def get_color(v): t = (v - v_min) / v_range r = int(255 - t * (255 - 6)) g = int(255 - t * (255 - 95)) b = int(255 - t * (255 - 70)) return f"rgb({r},{g},{b})" ml = max(80, max(len(l) for l in row_labels) * 7 + 10) if row_labels else 80 mr = 20 mt = 80 mb = 20 cw = width - ml - mr ch = height - mt - mb cell_w = cw / n_cols cell_h = ch / n_rows svg = [ f'', f'', ] if title: svg.append(f'{title}') for j, label in enumerate(col_labels): cx = ml + j * cell_w + cell_w / 2 svg.append(f'{label}') for i, row_label in enumerate(row_labels): ry = mt + i * cell_h + cell_h / 2 svg.append(f'{row_label}') for j in range(n_cols): val = matrix[i][j] color = get_color(val) cx = ml + j * cell_w cy = mt + i * cell_h svg.append(f'') if show_values: t = (val - v_min) / v_range text_color = "#fff" if t > 0.55 else "#1a1a2e" fs = min(10, int(cell_w / 4), int(cell_h / 2.5)) fs = max(7, fs) svg.append(f'{val:{value_format}}') svg.append("") return "\n".join(svg) def _make_dendrogram( names: list[str], matrix: list[list[float]], title: str = "", width: int = 700, height: int = 350, color: str = "#2563eb", ) -> str: """Generate an SVG dendrogram from a similarity matrix using UPGMA.""" n = len(names) if n < 2: return "" dist = [[1.0 - matrix[i][j] for j in range(n)] for i in range(n)] clusters = [{"members": [i], "height": 0.0, "left": None, "right": None} for i in range(n)] active = list(range(n)) while len(active) > 1: best_d = float("inf") bi, bj = 0, 1 for ii in range(len(active)): for jj in range(ii + 1, len(active)): ci, cj = active[ii], active[jj] d = 0 count = 0 for mi in clusters[ci]["members"]: for mj in clusters[cj]["members"]: d += dist[mi][mj] count += 1 avg_d = d / count if count else 0 if avg_d < best_d: best_d = avg_d bi, bj = ii, jj ci, cj = active[bi], active[bj] new_cluster = { "members": clusters[ci]["members"] + clusters[cj]["members"], "height": best_d, "left": clusters[ci], "right": clusters[cj], } clusters.append(new_cluster) new_idx = len(clusters) - 1 active.pop(bj) active.pop(bi) active.append(new_idx) root = clusters[active[0]] max_label_len = max((len(n) for n in names), default=0) ml, mr, mt, mb = max(50, max_label_len * 5 + 10), 30, 40, 80 cw = width - ml - mr ch = height - mt - mb max_h = root["height"] or 1 leaf_positions = {} leaf_counter = [0] def assign_leaves(node): if node["left"] is None and node["right"] is None: leaf_positions[node["members"][0]] = leaf_counter[0] leaf_counter[0] += 1 else: if node["left"]: assign_leaves(node["left"]) if node["right"]: assign_leaves(node["right"]) assign_leaves(root) n_leaves = len(leaf_positions) leaf_spacing = cw / max(n_leaves - 1, 1) svg = [ f'', f'', ] if title: svg.append(f'{title}') def get_x(node): if node["left"] is None and node["right"] is None: return ml + leaf_positions[node["members"][0]] * leaf_spacing return (get_x(node["left"]) + get_x(node["right"])) / 2 def get_y(h): return mt + ch - (h / max_h) * ch def draw_node(node): if node["left"] is None and node["right"] is None: return lx = get_x(node["left"]) rx = get_x(node["right"]) ly = get_y(node["left"]["height"]) ry = get_y(node["right"]["height"]) my = get_y(node["height"]) svg.append(f'') svg.append(f'') svg.append(f'') if node["left"]: draw_node(node["left"]) if node["right"]: draw_node(node["right"]) draw_node(root) for idx, pos in leaf_positions.items(): x = ml + pos * leaf_spacing svg.append( f'{names[idx]}' ) for i in range(5): d = max_h * i / 4 y = get_y(d) svg.append(f'{d:.3f}') svg.append("") return "\n".join(svg) def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 300, value_format: str = ".1f", ) -> str: """Generate an SVG grouped bar chart.""" if not labels: return "" default_colors = ["#2563eb", "#059669", "#f59e0b", "#dc2626", "#7c3aed"] colors = colors or default_colors ml, mr, mt, mb = 60, 20, 40, 80 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_min = min(all_vals) if all_vals else 0 y_max = max(all_vals) if all_vals else 1 if y_min >= 0: y_min_plot = 0 y_max_plot = y_max * 1.15 or 1 else: y_range = y_max - y_min or 1 y_min_plot = y_min - y_range * 0.05 y_max_plot = y_max + y_range * 0.15 n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - ((v - y_min_plot) / (y_max_plot - y_min_plot)) * ch svg = [ f'', f'', ] for i in range(6): y_tick = y_min_plot + (y_max_plot - y_min_plot) * i / 5 py = sy(y_tick) svg.append(f'') svg.append(f'{y_tick:{value_format}}') for gi, label in enumerate(labels): gx = ml + gi * group_width + gap for si, (name, vals) in enumerate(series.items()): color = colors[si % len(colors)] bx = gx + si * bar_width val = vals[gi] by = sy(val) bh = mt + ch - by svg.append(f'') svg.append(f'{val:{value_format}}') lx = gx + n_series * bar_width / 2 svg.append(f'{label}') if title: svg.append(f'{title}') if n_series > 1: lx = ml + cw - len(series) * 110 for si, name in enumerate(series): color = colors[si % len(colors)] svg.append(f'') svg.append(f'{name}') svg.append("") return "\n".join(svg) def _make_plddt_sparkline(values: list[float], width: int = 400, height: int = 50) -> str: """pLDDT sparkline with AlphaFold-style coloring.""" if not values or len(values) < 2: return "" pad = 4 cw = width - 2 * pad ch = height - 2 * pad seg_w = cw / len(values) svg = [ f'', ] for i, v in enumerate(values): x = pad + i * seg_w bar_h = (v / 100) * ch y = pad + ch - bar_h if v >= 90: color = "#0053d6" elif v >= 70: color = "#65cbf3" elif v >= 50: color = "#ffdb13" else: color = "#ff7d45" svg.append(f'') ref_y = pad + ch - (70 / 100) * ch svg.append(f'') svg.append("") return "\n".join(svg) def _outputs_to_pdb(outputs, sequence: str) -> str: """Convert ESMFold outputs to PDB format string.""" import numpy as np pos = outputs.positions[0] if pos.dim() == 4: pos = pos[-1] positions = pos.cpu().numpy() atom_names = ["N", "CA", "C", "O"] aa_3letter = { "A": "ALA", "R": "ARG", "N": "ASN", "D": "ASP", "C": "CYS", "Q": "GLN", "E": "GLU", "G": "GLY", "H": "HIS", "I": "ILE", "L": "LEU", "K": "LYS", "M": "MET", "F": "PHE", "P": "PRO", "S": "SER", "T": "THR", "W": "TRP", "Y": "TYR", "V": "VAL", } pdb_lines = [] atom_idx = 1 for res_idx, aa in enumerate(sequence): res_name = aa_3letter.get(aa, "UNK") for atom_i, atom_name in enumerate(atom_names): if atom_i >= positions.shape[1]: break x, y, z = positions[res_idx, atom_i] if any(math.isnan(c) for c in (x, y, z)): continue pdb_lines.append( f"ATOM {atom_idx:5d} {atom_name:<3s} {res_name} A{res_idx + 1:4d} " f"{x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 {atom_name[0]:>2s}" ) atom_idx += 1 pdb_lines.append("END") return "\n".join(pdb_lines) # ------------------------------------------------------------------ # Task 1: Load gene set # ------------------------------------------------------------------ @cpu_env.task() async def load_genes( gene_set: str = "insulin", custom_json: str = "", ) -> flyte.io.Dir: """Load a set of homologous genes from different species.""" if custom_json: data = json.loads(custom_json) elif gene_set in GENE_SETS: data = GENE_SETS[gene_set] else: available = ", ".join(GENE_SETS.keys()) raise ValueError(f"Unknown gene set '{gene_set}'. Available: {available}") log.info(f"Loaded gene set: {data['gene_name']} - {len(data['sequences'])} species") out_dir = tempfile.mkdtemp(prefix="gene_compare_") with open(os.path.join(out_dir, "genes.json"), "w") as f: json.dump(data, f) return await flyte.io.Dir.from_local(out_dir) # ------------------------------------------------------------------ # Task 2: Score sequences with Carbon # ------------------------------------------------------------------ @gpu_env.task(report=True) async def score_sequences( genes_dir: flyte.io.Dir, model_name: str = "HuggingFaceBio/Carbon-3B", ) -> str: """Score each species' gene with Carbon-3B genomic language model. Returns per-species log-likelihood scores and sequence metadata. """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer log.info(f"Loading Carbon model: {model_name}") device = "cuda" if torch.cuda.is_available() else "cpu" tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_name, trust_remote_code=True, dtype=torch.bfloat16 if device == "cuda" else torch.float32, ).to(device) model.eval() genes_path = await genes_dir.download() with open(os.path.join(genes_path, "genes.json")) as f: data = json.load(f) species_names = list(data["sequences"].keys()) n = len(species_names) scores = {} for i, species in enumerate(species_names): await flyte.report.replace.aio(_wrap_report( f"

Carbon Scoring

" f"

Scoring {species} ({i + 1}/{n})...

" ), do_flush=True) dna = data["sequences"][species]["dna"] prompt = f"{dna}" inputs = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): output = model(**inputs, labels=inputs["input_ids"]) loss = output.loss.item() ll = -loss * inputs["input_ids"].shape[1] protein = _translate(dna) scores[species] = { "log_likelihood": round(ll, 4), "loss": round(loss, 4), "gc_content": round(_gc_content(dna), 4), "length": len(dna), "protein": protein, "protein_length": len(protein), "common_name": data["sequences"][species]["common_name"], } log.info(f" {species} ({data['sequences'][species]['common_name']}): LL={ll:.2f}, GC={_gc_content(dna):.1%}") # Report html_parts = [ f"

{data['gene_name']} - Carbon Scoring

", f'
{data["description"]}
', '
', f'
{n}
Species
', f'
{data["gene_name"]}
Gene
', f'
{model_name.split("/")[-1]}
Model
', "
", ] html_parts.append( "" "" ) for species in species_names: s = scores[species] html_parts.append( f'' f'' f'' f'' ) html_parts.append("
SpeciesScientific NameDNA LengthGC%Protein LengthCarbon LL
{species}{s["common_name"]}{s["length"]}bp{s["gc_content"]:.1%}{s["protein_length"]}aa{s["log_likelihood"]:.2f}
") html_parts.append('
') html_parts.append(_make_bar_chart( species_names, {"Log-Likelihood": [scores[s]["log_likelihood"] for s in species_names]}, title="Carbon Log-Likelihood per Species", value_format=".1f", )) html_parts.append("
") await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) result = { "gene_name": data["gene_name"], "description": data["description"], "species": species_names, "scores": scores, } return json.dumps(result) # ------------------------------------------------------------------ # Task 3: Align sequences and compute similarity # ------------------------------------------------------------------ @cpu_env.task(report=True) async def align_and_compare( scores_json: str, genes_dir: flyte.io.Dir, ) -> str: """Align sequences with Needleman-Wunsch and compute pairwise identity. Translates DNA to protein, builds DNA and protein identity matrices, and generates phylogenetic trees from sequence divergence. """ scores_data = json.loads(scores_json) species_names = scores_data["species"] scores = scores_data["scores"] gene_name = scores_data["gene_name"] n = len(species_names) genes_path = await genes_dir.download() with open(os.path.join(genes_path, "genes.json")) as f: data = json.load(f) await flyte.report.replace.aio(_wrap_report( f"

{gene_name} - Sequence Alignment

" f"

Aligning {n} species with Needleman-Wunsch...

" ), do_flush=True) # Pairwise DNA identity matrix identity_matrix = [] for sp1 in species_names: row = [] for sp2 in species_names: dna1 = data["sequences"][sp1]["dna"] dna2 = data["sequences"][sp2]["dna"] identity = _sequence_identity(dna1, dna2) row.append(round(identity, 4)) identity_matrix.append(row) # Pairwise protein identity matrix protein_matrix = [] for sp1 in species_names: row = [] for sp2 in species_names: identity = _sequence_identity(scores[sp1]["protein"], scores[sp2]["protein"]) row.append(round(identity, 4)) protein_matrix.append(row) # Average pairwise identities (exclude diagonal) dna_pairs = [identity_matrix[i][j] for i in range(n) for j in range(i + 1, n)] prot_pairs = [protein_matrix[i][j] for i in range(n) for j in range(i + 1, n)] avg_dna = sum(dna_pairs) / len(dna_pairs) if dna_pairs else 0 avg_prot = sum(prot_pairs) / len(prot_pairs) if prot_pairs else 0 # Most/least similar pair best_pair = max(range(len(dna_pairs)), key=lambda k: dna_pairs[k]) worst_pair = min(range(len(dna_pairs)), key=lambda k: dna_pairs[k]) pair_indices = [(i, j) for i in range(n) for j in range(i + 1, n)] best_sp = f"{species_names[pair_indices[best_pair][0]]}-{species_names[pair_indices[best_pair][1]]}" worst_sp = f"{species_names[pair_indices[worst_pair][0]]}-{species_names[pair_indices[worst_pair][1]]}" # Report html_parts = [ f"

{gene_name} - Sequence Alignment

", f'
Pairwise alignment using Needleman-Wunsch (match=2, mismatch=-1, gap=-2). ' f"Identity is computed as matches / aligned length from the optimal global alignment.
", '
', f'
{n}
Species Aligned
', f'
{n * (n - 1) // 2}
Pairwise Alignments
', f'
{avg_dna:.0%}
Avg DNA Identity
', f'
{avg_prot:.0%}
Avg Protein Identity
', f'
{best_sp}
Most Similar
', f'
{worst_sp}
Most Divergent
', "
", ] # DNA identity heatmap html_parts.append('
') html_parts.append(_make_heatmap( identity_matrix, species_names, species_names, title="Pairwise DNA Sequence Identity (%)", value_format=".0%", )) html_parts.append("
") # Protein identity heatmap html_parts.append('
') html_parts.append(_make_heatmap( protein_matrix, species_names, species_names, title="Pairwise Protein Sequence Identity (%)", value_format=".0%", color_scale="green", )) html_parts.append("
") # DNA phylogenetic tree html_parts.append('
') html_parts.append(_make_dendrogram( species_names, identity_matrix, title=f"{gene_name} - Phylogenetic Tree (DNA Identity)", )) html_parts.append("
") # Protein phylogenetic tree html_parts.append('
') html_parts.append(_make_dendrogram( species_names, protein_matrix, title=f"{gene_name} - Phylogenetic Tree (Protein Identity)", color="#059669", )) html_parts.append("
") # DNA vs Protein conservation comparison html_parts.append('
') html_parts.append(_make_bar_chart( species_names, { "DNA vs Human": [identity_matrix[0][j] for j in range(n)], "Protein vs Human": [protein_matrix[0][j] for j in range(n)], }, title=f"Conservation vs {species_names[0]} (DNA and Protein)", value_format=".0%", )) html_parts.append("
") await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) result = { "gene_name": gene_name, "description": scores_data["description"], "species": species_names, "scores": scores, "dna_identity_matrix": identity_matrix, "protein_identity_matrix": protein_matrix, } return json.dumps(result) # ------------------------------------------------------------------ # Task 4: Fold proteins with ESMFold # ------------------------------------------------------------------ @gpu_env.task(report=True) async def fold_proteins( comparison_json: str, max_length: int = 400, ) -> str: """Fold each species' translated protein with ESMFold for 3D comparison. Returns PDB strings and pLDDT confidence scores for each species. """ import torch import numpy as np from transformers import AutoTokenizer, EsmForProteinFolding comparison = json.loads(comparison_json) species_names = comparison["species"] scores = comparison["scores"] log.info("Loading ESMFold model...") device = "cuda" if torch.cuda.is_available() else "cpu" tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1") model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1", low_cpu_mem_usage=True) model = model.to(device) model.eval() structure_data = {} n = len(species_names) for idx, species in enumerate(species_names): protein = scores[species]["protein"] if len(protein) > max_length: log.info(f"Skipping {species} ({len(protein)} aa > {max_length} max)") continue log.info(f"ESMFold [{idx + 1}/{n}]: {species} ({len(protein)} aa)") await flyte.report.replace.aio(_wrap_report( f"

ESMFold - 3D Structure Prediction

" f"

Folding {species} ({idx + 1}/{n}): {len(protein)} residues...

" ), do_flush=True) inputs = tokenizer(protein, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): outputs = model(**inputs) pdb_str = _outputs_to_pdb(outputs, protein) plddt_raw = outputs.plddt[0].cpu().numpy() if plddt_raw.ndim == 2: plddt_raw = plddt_raw[-1] plddt = plddt_raw.flatten()[:len(protein)] if plddt.max() <= 1.0: plddt = plddt * 100 plddt_mean = float(np.mean(plddt)) structure_data[species] = { "pdb_str": pdb_str, "plddt_mean": round(plddt_mean, 1), "plddt_per_residue": [round(float(v), 1) for v in plddt[:len(protein)]], "protein_length": len(protein), } log.info(f" โ†’ mean pLDDT: {plddt_mean:.1f}") # Report with 3D viewers n_folded = len(structure_data) avg_plddt = sum(d["plddt_mean"] for d in structure_data.values()) / n_folded if n_folded else 0 threeDmol_script = '' stats_html = f"""

ESMFold - Cross-Species Structure Comparison

ESMFold predicts 3D structure directly from amino acid sequence. Comparing structures across species reveals which parts of the protein are structurally conserved (functional core) vs divergent (surface loops, species-specific adaptations).
{n_folded}
Structures
{avg_plddt:.1f}
Avg pLDDT
{comparison['gene_name']}
Gene
""" viewers_html = '
' for species, sdata in structure_data.items(): plddt_val = sdata["plddt_mean"] common = scores[species]["common_name"] if plddt_val >= 90: badge = 'Very High' elif plddt_val >= 70: badge = 'Confident' elif plddt_val >= 50: badge = 'Low' else: badge = 'Disordered' plddt_sparkline = _make_plddt_sparkline(sdata["plddt_per_residue"], width=300) pdb_escaped = sdata["pdb_str"].replace("\\", "\\\\").replace("`", "\\`").replace("$", "\\$") viewer_id = f"viewer_{hash(species) & 0xFFFFFF:06x}" viewers_html += f"""

{species} ({sdata['protein_length']} aa) {badge}

{common}

Mean pLDDT: {plddt_val:.1f} / 100
{plddt_sparkline}
█ >90 █ 70-90 █ 50-70 █ <50
""" viewers_html += "
" # pLDDT comparison bar chart plddt_chart = _make_bar_chart( list(structure_data.keys()), {"Mean pLDDT": [d["plddt_mean"] for d in structure_data.values()]}, title="Structure Confidence Comparison (pLDDT)", value_format=".1f", colors=["#0053d6"], ) report_html = f""" {threeDmol_script} {stats_html} {viewers_html}
{plddt_chart}
""" await flyte.report.replace.aio(_wrap_report(report_html), do_flush=True) return json.dumps(structure_data) # ------------------------------------------------------------------ # Task 5: Generate summary # ------------------------------------------------------------------ @cpu_env.task(report=True) async def generate_summary( comparison_json: str, structures_json: str, ) -> str: """Generate comprehensive cross-species summary.""" comparison = json.loads(comparison_json) structures = json.loads(structures_json) species = comparison["species"] scores = comparison["scores"] gene_name = comparison["gene_name"] dna_matrix = comparison["dna_identity_matrix"] protein_matrix = comparison["protein_identity_matrix"] html_parts = [ f"

{gene_name} - Cross-Species Evolution Summary

", f'
{comparison["description"]}
', ] # Key metrics # Average pairwise identity (exclude diagonal) n = len(species) dna_pairs = [dna_matrix[i][j] for i in range(n) for j in range(i + 1, n)] protein_pairs = [protein_matrix[i][j] for i in range(n) for j in range(i + 1, n)] avg_dna_id = sum(dna_pairs) / len(dna_pairs) if dna_pairs else 0 avg_protein_id = sum(protein_pairs) / len(protein_pairs) if protein_pairs else 0 avg_plddt = sum(d["plddt_mean"] for d in structures.values()) / len(structures) if structures else 0 html_parts.append('
') html_parts.append(f'
{n}
Species
') html_parts.append(f'
{avg_dna_id:.0%}
Avg DNA Identity
') html_parts.append(f'
{avg_protein_id:.0%}
Avg Protein Identity
') html_parts.append(f'
{avg_plddt:.1f}
Avg pLDDT
') html_parts.append(f'
{len(structures)}
Structures Folded
') html_parts.append("
") # Full comparison table html_parts.append("

Per-Species Detail

") html_parts.append( "" "" ) for sp in species: s = scores[sp] plddt = structures.get(sp, {}).get("plddt_mean", "N/A") plddt_str = f"{plddt:.1f}" if isinstance(plddt, float) else plddt html_parts.append( f'' f'' f'' f'' ) html_parts.append("
SpeciesScientific NameDNA (bp)Protein (aa)GC%Carbon LLpLDDT
{sp}{s["common_name"]}{s["length"]}{s["protein_length"]}{s["gc_content"]:.1%}{s["log_likelihood"]:.2f}{plddt_str}
") # GC content comparison html_parts.append('
') html_parts.append(_make_bar_chart( species, {"GC Content": [scores[s]["gc_content"] for s in species]}, title="GC Content Across Species", value_format=".2f", )) html_parts.append("
") # DNA phylogenetic tree html_parts.append("

Phylogenetic Relationships

") html_parts.append( '
' "Trees built from pairwise sequence identity using UPGMA clustering. " "Species that diverged more recently cluster together. DNA and protein trees " "may differ when synonymous mutations dominate." "
" ) html_parts.append('
') html_parts.append(_make_dendrogram( species, dna_matrix, title=f"{gene_name} - DNA Phylogenetic Tree", )) html_parts.append("
") html_parts.append('
') html_parts.append(_make_dendrogram( species, protein_matrix, title=f"{gene_name} - Protein Phylogenetic Tree", color="#059669", )) html_parts.append("
") await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) summary = { "gene_name": gene_name, "n_species": n, "avg_dna_identity": round(avg_dna_id, 4), "avg_protein_identity": round(avg_protein_id, 4), "avg_plddt": round(avg_plddt, 1), "n_structures": len(structures), } return json.dumps(summary) # ------------------------------------------------------------------ # Pipeline orchestrator # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @cpu_env.task(report=True) async def pipeline( gene_set: str = "insulin", model_name: str = "HuggingFaceBio/Carbon-3B", custom_json: str = "", ) -> tuple[str, str]: """ End-to-end cross-species gene comparison pipeline. Returns (comparison JSON, structures JSON). 1. Load homologous gene sequences across species 2. Score with Carbon genomic language model 3. Align sequences and compute pairwise similarity 4. Fold translated proteins with ESMFold 5. Generate comprehensive summary with phylogenetic trees """ log.info(f"Starting cross-species gene comparison pipeline (gene_set={gene_set})...") def _pipeline_progress(step: int, label: str) -> str: steps = [ "Load Genes", "Carbon Scoring", "Sequence Alignment", "ESMFold Structures", "Generate Summary", ] dots = "" for i, s in enumerate(steps): if i + 1 < step: icon = '✓' elif i + 1 == step: icon = '●' else: icon = '○' dots += f"{icon} {s}" return f"""

Cross-Species Gene Comparison

{dots}

{label}

""" # Stage 1 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(1, "Loading homologous gene sequences...")), do_flush=True, ) genes_dir = await load_genes(gene_set=gene_set, custom_json=custom_json) # Stage 2 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(2, "Scoring sequences with Carbon...")), do_flush=True, ) scores_json = await score_sequences(genes_dir=genes_dir, model_name=model_name) # Stage 3 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(3, "Aligning sequences with Needleman-Wunsch...")), do_flush=True, ) comparison_json = await align_and_compare(scores_json=scores_json, genes_dir=genes_dir) # Stage 4 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(4, "Folding proteins with ESMFold...")), do_flush=True, ) structures_json = await fold_proteins(comparison_json=comparison_json) # Stage 5 await flyte.report.replace.aio( _wrap_report(_pipeline_progress(5, "Generating summary report...")), do_flush=True, ) summary_json = await generate_summary( comparison_json=comparison_json, structures_json=structures_json, ) # Final report summary = json.loads(summary_json) comparison = json.loads(comparison_json) final_html = f"""

Pipeline Complete

{summary['gene_name']}
Gene
{summary['n_species']}
Species
{summary['avg_dna_identity']:.0%}
Avg DNA Identity
{summary['avg_protein_identity']:.0%}
Avg Protein Identity
{summary['avg_plddt']:.1f}
Avg pLDDT
{summary['n_structures']}
3D Structures
Gene: {summary['gene_name']} | Species: {', '.join(comparison['species'])} | Model: {model_name}
All 4 pipeline stages completed. View individual task reports for DNA/protein identity heatmaps, phylogenetic trees, interactive 3D protein structures with pLDDT confidence, Carbon log-likelihood scores, and evolutionary analysis.
""" await flyte.report.replace.aio(_wrap_report(final_html), do_flush=True) log.info("Pipeline complete.") return comparison_json, structures_json # {{/docs-fragment pipeline}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline) print(run.url) run.wait() CODE1 cd v2/tutorials/genomic_gene_comparison uv run --script genomic_gene_comparison.py CODE2 flyte run genomic_gene_comparison.py pipeline --gene_set hemoglobin ``` This example needs a GPU for Carbon and ESMFold. Open the run URL and check each task's report tab for heatmaps, dendrograms, and interactive 3D viewers. === PAGE: https://www.union.ai/docs/v2/union/tutorials/biotech-healthcare/genomic-variant-effect === Zero-shot pathogenicity scoring with HuggingFace Carbon and interactive VEP reports. # Genomic variant effect prediction > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/genomic_variant_effect). This tutorial demonstrates zero-shot variant effect prediction (VEP) with HuggingFace [Carbon](https://huggingface.co/HuggingFaceBio/Carbon-3B). The pipeline loads clinically relevant variants across genes such as BRCA2, TP53, CFTR, KRAS, and HBB, scores each mutation with a log-likelihood ratio, and produces rich HTML reports with DNA tracks, lollipop plots, confusion matrices, and ranked pathogenicity tables. Flyte provides: - **GPU-backed inference** for Carbon scoring with live progress reports. - **CPU analysis tasks** for visualization and accuracy metrics without holding a GPU. - **End-to-end orchestration** from variant loading through summary reporting. ## Define the task environments ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "torch>=2.9.0", # "transformers>=4.49.0", # "accelerate>=0.34.0", # "numpy", # ] # main = "pipeline" # params = "" # /// import json import logging import math import os import tempfile import flyte import flyte.io import flyte.report # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="genomic-variant-effect", pre=True) gpu_env = flyte.TaskEnvironment( name="genomic-variant-effect-gpu", image=main_img, resources=flyte.Resources(cpu=4, memory="24Gi", gpu=1), ) cpu_env = flyte.TaskEnvironment( name="genomic-variant-effect-cpu", image=main_img, resources=flyte.Resources(cpu=2, memory="6Gi"), depends_on=[gpu_env], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Default gene variants โ€” clinically relevant mutations # ------------------------------------------------------------------ # Each entry: gene name -> { "sequence": reference DNA, "variants": [{ "pos": 0-indexed, "ref": base, "alt": base, "name": "...", "known_effect": "..." }] } # Sequences are short windows (~120-200bp) around the variant site for tractable inference. DEFAULT_GENE_VARIANTS = { "BRCA2 (Breast Cancer)": { "description": "Tumor suppressor critical for DNA repair via homologous recombination. Mutations dramatically increase breast and ovarian cancer risk.", "sequence": "ATGGCCTCGAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAG", "variants": [ {"pos": 12, "ref": "A", "alt": "T", "name": "c.37A>T", "known_effect": "pathogenic", "clinical": "Nonsense mutation โ€” truncates protein early"}, {"pos": 18, "ref": "G", "alt": "A", "name": "c.55G>A", "known_effect": "benign", "clinical": "Synonymous โ€” no amino acid change"}, {"pos": 30, "ref": "C", "alt": "T", "name": "c.91C>T", "known_effect": "pathogenic", "clinical": "Missense in DNA-binding domain"}, {"pos": 45, "ref": "G", "alt": "C", "name": "c.136G>C", "known_effect": "uncertain", "clinical": "Variant of uncertain significance (VUS)"}, ], }, "TP53 (Tumor Suppressor)": { "description": "Guardian of the genome. Activates DNA repair, cell cycle arrest, and apoptosis. Mutated in >50% of human cancers.", "sequence": "ATGGAGGAGCCGCAGTCAGATCCTAGCGTGAGTTTGCACCCTTCAGAGACAGAAACCACTGGATTGGAGACTACTTCCTGAAACAACGTTCTGTCCCCCTTGCCGTCCCAAGCAATGGATGAT", "variants": [ {"pos": 15, "ref": "C", "alt": "T", "name": "R175H", "known_effect": "pathogenic", "clinical": "Hotspot โ€” gain-of-function, dominant negative. Most common TP53 mutation in cancer"}, {"pos": 36, "ref": "T", "alt": "C", "name": "P72R", "known_effect": "benign", "clinical": "Common polymorphism โ€” subtle effect on apoptosis efficiency"}, {"pos": 54, "ref": "C", "alt": "A", "name": "G245S", "known_effect": "pathogenic", "clinical": "Contact mutant โ€” disrupts DNA binding"}, {"pos": 72, "ref": "T", "alt": "G", "name": "R248W", "known_effect": "pathogenic", "clinical": "Structural mutant โ€” destabilizes DNA-binding loop"}, {"pos": 90, "ref": "C", "alt": "T", "name": "R273H", "known_effect": "pathogenic", "clinical": "Contact mutant โ€” directly contacts DNA bases"}, ], }, "CFTR (Cystic Fibrosis)": { "description": "Chloride channel protein. Mutations cause cystic fibrosis โ€” the most common lethal genetic disease in people of European descent.", "sequence": "ATGCAGAGGTCGCCTCTGGAAAAGGCCAGCGTTGTCTCCAAACTTTTTTTCAGCTGGACCAGACCAATTTTGAGGAAAGGATACAGACAGCGCCTGGAATTGTCAGACATATACCAAATCCCTTC", "variants": [ {"pos": 9, "ref": "G", "alt": "A", "name": "G85E", "known_effect": "pathogenic", "clinical": "Disrupts chloride channel processing"}, {"pos": 24, "ref": "C", "alt": "T", "name": "R117H", "known_effect": "pathogenic", "clinical": "Reduces channel conductance โ€” milder CF phenotype"}, {"pos": 48, "ref": "T", "alt": "C", "name": "I148T", "known_effect": "benign", "clinical": "Previously misclassified โ€” now known benign polymorphism"}, {"pos": 66, "ref": "A", "alt": "G", "name": "R334W", "known_effect": "pathogenic", "clinical": "Gating mutation โ€” channel opens less frequently"}, ], }, "KRAS (Oncogene)": { "description": "GTPase signal switch. KRAS mutations are the most common oncogenic driver โ€” found in ~25% of all human cancers, especially pancreatic, colorectal, and lung.", "sequence": "ATGACTGAATATAAACTTGTGGTAGTTGGAGCTGGTGGCGTAGGCAAGAGTGCCTTGACGATACAGCTAATTCAGAATCATTTTGTGGACGAATATGATCCAACAATAGAGGATTCCTACAGGAA", "variants": [ {"pos": 34, "ref": "G", "alt": "T", "name": "G12V", "known_effect": "pathogenic", "clinical": "Locks KRAS in active state โ€” constitutive proliferation signal"}, {"pos": 35, "ref": "G", "alt": "A", "name": "G12D", "known_effect": "pathogenic", "clinical": "Most common KRAS mutation in pancreatic cancer"}, {"pos": 37, "ref": "G", "alt": "T", "name": "G13D", "known_effect": "pathogenic", "clinical": "Constitutively active โ€” common in colorectal cancer"}, {"pos": 60, "ref": "C", "alt": "A", "name": "Q61K", "known_effect": "pathogenic", "clinical": "Impairs GTP hydrolysis โ€” locked ON state"}, ], }, "HBB (Sickle Cell)": { "description": "Beta-globin subunit of hemoglobin. The sickle cell mutation (E6V) is the most well-known single-base disease variant in humans.", "sequence": "ATGGTGCATCTGACTCCTGAGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTGGTCTACCCTTGGACCCAGAGG", "variants": [ {"pos": 17, "ref": "A", "alt": "T", "name": "E6V (HbS)", "known_effect": "pathogenic", "clinical": "THE sickle cell mutation โ€” causes hemoglobin polymerization under low O2"}, {"pos": 19, "ref": "G", "alt": "A", "name": "E6K (HbC)", "known_effect": "pathogenic", "clinical": "Hemoglobin C disease โ€” milder than sickle cell but causes crystal formation"}, {"pos": 36, "ref": "G", "alt": "A", "name": "E26K", "known_effect": "benign", "clinical": "Hemoglobin E โ€” most common Hb variant worldwide, mild effect"}, {"pos": 78, "ref": "C", "alt": "T", "name": "Q39X", "known_effect": "pathogenic", "clinical": "Nonsense โ€” causes beta-thalassemia (no functional beta-globin)"}, ], }, } # DNA base colors (classic genomics color scheme) BASE_COLORS = {"A": "#2ecc71", "T": "#e74c3c", "G": "#f39c12", "C": "#3498db"} BASE_COMPLEMENT = {"A": "T", "T": "A", "G": "C", "C": "G"} # Pathogenicity color scheme EFFECT_COLORS = { "pathogenic": "#dc2626", "benign": "#059669", "uncertain": "#f59e0b", } EFFECT_BADGES = { "pathogenic": "badge-danger", "benign": "badge-success", "uncertain": "badge-warning", } # ------------------------------------------------------------------ # Report styling โ€” genomics-themed deep blues and teals # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers # ------------------------------------------------------------------ def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 300, value_format: str = ".2f", ) -> str: """Generate an SVG grouped bar chart.""" if not labels: return "" default_colors = ["#2563eb", "#1e3a5f", "#3b82f6", "#60a5fa", "#93c5fd"] colors = colors or default_colors ml, mr, mt, mb = 70, 20, 40, 80 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_max = max(abs(v) for v in all_vals) if all_vals else 1 y_min = min(all_vals) if all_vals else 0 # For VEP scores (negative = more damaging), we need to handle negative values if y_min >= 0: y_min_plot = 0 y_max_plot = y_max * 1.15 or 1 else: y_max_plot = max(y_max * 1.15, 0.1) y_min_plot = y_min * 1.15 y_range = y_max_plot - y_min_plot or 1 n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - (v - y_min_plot) / y_range * ch svg = [ f'', f'', ] # Grid lines for i in range(6): y_tick = y_min_plot + y_range * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:{value_format}}' ) # Zero line if y_min_plot < 0 < y_max_plot: zy = sy(0) svg.append( f'' ) # Bars for gi, label in enumerate(labels): gx = ml + gi * group_width + gap for si, (name, vals) in enumerate(series.items()): color = colors[si % len(colors)] bx = gx + si * bar_width val = vals[gi] if val >= 0: by = sy(val) bh = sy(0) - by if y_min_plot < 0 else mt + ch - by else: by = sy(0) if y_min_plot < 0 else mt + ch bh = sy(val) - by svg.append( f'' ) text_y = by - 4 if val >= 0 else by + bh + 12 svg.append( f'' f'{val:{value_format}}' ) # Rotated group label lx = gx + n_series * bar_width / 2 svg.append( f'{label}' ) # Title if title: svg.append( f'{title}' ) # Legend if n_series > 1: lx = ml + cw - len(series) * 110 for si, name in enumerate(series): color = colors[si % len(colors)] svg.append( f'' ) svg.append( f'{name}' ) svg.append("") return "\n".join(svg) def _make_heatmap( matrix: list[list[float]], row_labels: list[str], col_labels: list[str], title: str = "", width: int = 700, height: int = 500, value_format: str = ".2f", diverging: bool = False, ) -> str: """Generate an SVG heatmap. If diverging=True, uses red-white-blue scale centered at 0.""" n_rows = len(matrix) n_cols = len(matrix[0]) if matrix else 0 if not n_rows or not n_cols: return "" show_values = n_rows <= 10 and n_cols <= 12 flat = [v for row in matrix for v in row] v_min = min(flat) v_max = max(flat) if diverging: abs_max = max(abs(v_min), abs(v_max)) or 1 def get_color(v): t = v / abs_max # -1 to 1 if t < 0: # White to red (negative = damaging) r = 255 g = int(255 * (1 + t)) b = int(255 * (1 + t)) else: # White to blue (positive = benign) r = int(255 * (1 - t)) g = int(255 * (1 - t)) b = 255 return f"rgb({r},{g},{b})" else: v_range = v_max - v_min or 1 def get_color(v): t = (v - v_min) / v_range r = int(255 - t * (255 - 30)) g = int(255 - t * (255 - 58)) b = int(255 - t * (255 - 95)) return f"rgb({r},{g},{b})" # Layout ml = max(140, max(len(l) for l in row_labels) * 7 + 20) if row_labels else 140 mr = 20 mt = 80 if col_labels else 40 mb = 30 cw = width - ml - mr ch = height - mt - mb cell_w = cw / n_cols cell_h = ch / n_rows svg = [ f'', f'', ] if title: svg.append( f'{title}' ) # Column labels (rotated) for j, label in enumerate(col_labels): cx = ml + j * cell_w + cell_w / 2 svg.append( f'{label}' ) # Row labels + cells for i, row_label in enumerate(row_labels): ry = mt + i * cell_h + cell_h / 2 svg.append( f'{row_label}' ) for j in range(n_cols): val = matrix[i][j] color = get_color(val) cx = ml + j * cell_w cy = mt + i * cell_h svg.append( f'' ) if show_values: if diverging: t = abs(val) / (max(abs(v_min), abs(v_max)) or 1) else: t = (val - v_min) / (v_max - v_min or 1) text_color = "#fff" if t > 0.55 else "#1a1a2e" font_size = min(10, int(cell_w / 4), int(cell_h / 2.5)) font_size = max(7, font_size) svg.append( f'{val:{value_format}}' ) svg.append("") return "\n".join(svg) def _make_dna_track( sequence: str, variants: list[dict], gene_name: str = "", width: int = 900, ) -> str: """Render a color-coded DNA sequence track with variant positions highlighted.""" chars_per_line = 60 char_w = 11 line_h = 22 label_w = 50 n_lines = (len(sequence) + chars_per_line - 1) // chars_per_line # Extra space for variant annotations variant_positions = {v["pos"] for v in variants} svg_h = n_lines * line_h + 60 svg = [ f'', f'', ] if gene_name: svg.append( f'{gene_name}' ) y_offset = 28 for line_idx in range(n_lines): start = line_idx * chars_per_line end = min(start + chars_per_line, len(sequence)) chunk = sequence[start:end] y = y_offset + line_idx * line_h # Position label svg.append( f'{start + 1}' ) for ci, base in enumerate(chunk): abs_pos = start + ci x = label_w + ci * char_w color = BASE_COLORS.get(base, "#6b7280") is_variant = abs_pos in variant_positions if is_variant: # Red highlight for variant positions svg.append( f'' ) # Small triangle marker above svg.append( f'' ) else: # Subtle background svg.append( f'' ) svg.append( f'{base}' ) # Spacer every 10 bases if (abs_pos + 1) % 10 == 0 and ci < len(chunk) - 1: svg.append( f'' ) # Legend ly = svg_h - 12 lx = label_w for base, color in BASE_COLORS.items(): svg.append(f'') svg.append(f'{base}') lx += 30 lx += 10 svg.append(f'') svg.append(f'Variant site') svg.append("") return "\n".join(svg) def _make_lollipop_plot( variants: list[dict], seq_length: int, title: str = "", width: int = 700, height: int = 200, ) -> str: """Generate a lollipop plot showing variant positions along a gene with effect scores.""" if not variants: return "" ml, mr, mt, mb = 50, 30, 40, 40 cw = width - ml - mr ch = height - mt - mb svg = [ f'', f'', ] if title: svg.append( f'{title}' ) # Gene track (horizontal bar) track_y = mt + ch * 0.7 svg.append( f'' ) # Position labels at ends svg.append( f'1' ) svg.append( f'{seq_length}' ) # Lollipops scores = [v.get("score", 0) for v in variants] max_score = max(abs(s) for s in scores) if scores else 1 for v in variants: pos = v["pos"] score = v.get("score", 0) effect = v.get("known_effect", "uncertain") color = EFFECT_COLORS.get(effect, "#6b7280") x = ml + (pos / max(seq_length - 1, 1)) * cw stem_h = max(20, abs(score) / max_score * (ch * 0.6)) circle_y = track_y - stem_h - 6 # Stem svg.append( f'' ) # Circle svg.append( f'' ) # Label svg.append( f'{v.get("name", "")}' ) # Legend lx = ml for effect, color in EFFECT_COLORS.items(): svg.append(f'') svg.append( f'' f'{effect.title()}' ) lx += len(effect) * 7 + 24 svg.append("") return "\n".join(svg) def _make_score_comparison_chart( gene_results: dict, width: int = 800, height: int = 350, ) -> str: """Generate a dot plot comparing VEP scores across all genes, colored by known effect.""" all_variants = [] for gene_name, gene_data in gene_results.items(): for v in gene_data["variants"]: all_variants.append({ "gene": gene_name.split("(")[0].strip(), "name": v["name"], "score": v.get("score", 0), "known_effect": v["known_effect"], }) if not all_variants: return "" ml, mr, mt, mb = 120, 30, 40, 30 cw = width - ml - mr ch = height - mt - mb scores = [v["score"] for v in all_variants] s_min, s_max = min(scores), max(scores) s_pad = (s_max - s_min) * 0.1 or 0.5 s_min -= s_pad s_max += s_pad s_range = s_max - s_min or 1 def sx(s): return ml + (s - s_min) / s_range * cw svg = [ f'', f'', f'' f'Variant Effect Scores โ€” All Genes', ] # Grid for i in range(6): gx = s_min + s_range * i / 5 px = sx(gx) svg.append( f'' ) svg.append( f'{gx:.2f}' ) # Zero line if s_min < 0 < s_max: zx = sx(0) svg.append( f'' ) # Rows per variant row_h = ch / max(len(all_variants), 1) for i, v in enumerate(all_variants): y = mt + i * row_h + row_h / 2 color = EFFECT_COLORS.get(v["known_effect"], "#6b7280") px = sx(v["score"]) # Label label = f'{v["gene"]} {v["name"]}' svg.append( f'{label}' ) # Connector line svg.append( f'' ) # Dot svg.append( f'' ) svg.append("") return "\n".join(svg) # ------------------------------------------------------------------ # Task 1: Load and validate gene variants # ------------------------------------------------------------------ @cpu_env.task(cache="auto") async def load_variants( variants_json: str = "", ) -> flyte.io.Dir: """Load gene variant definitions, validate sequences, and save to a temp directory.""" if variants_json: genes = json.loads(variants_json) else: genes = DEFAULT_GENE_VARIANTS # Validate valid_bases = set("ATGC") for gene_name, gene_data in genes.items(): seq = gene_data["sequence"].upper() invalid = set(seq) - valid_bases if invalid: log.warning(f"{gene_name}: invalid bases {invalid} โ€” removing them") seq = "".join(b for b in seq if b in valid_bases) gene_data["sequence"] = seq for v in gene_data["variants"]: pos = v["pos"] if pos < 0 or pos >= len(seq): log.warning(f"{gene_name} variant {v['name']}: position {pos} out of range [0, {len(seq)})") elif seq[pos] != v["ref"]: log.warning(f"{gene_name} variant {v['name']}: expected ref={v['ref']} at pos {pos}, found {seq[pos]}") total_variants = sum(len(g["variants"]) for g in genes.values()) log.info(f"Loaded {len(genes)} genes with {total_variants} variants") out_dir = tempfile.mkdtemp(prefix="genomic_vep_") with open(os.path.join(out_dir, "genes.json"), "w") as f: json.dump(genes, f) return await flyte.io.Dir.from_local(out_dir) # ------------------------------------------------------------------ # Task 2: Run Carbon model for variant effect scoring # ------------------------------------------------------------------ @gpu_env.task(report=True) async def score_variants( variants_dir: flyte.io.Dir, model_name: str = "HuggingFaceBio/Carbon-3B", ) -> str: """Score each variant using Carbon's log-likelihood ratio. For each variant, we compute: score = log P(alt_sequence) - log P(ref_sequence) A negative score means the model considers the variant less likely than the reference โ€” suggestive of a damaging/pathogenic effect. A score near zero means the model sees little difference (likely benign). """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer log.info(f"Loading Carbon model: {model_name}") # Load model device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cpu": log.warning("Running on CPU โ€” inference will be slow. GPU recommended for production.") tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_name, trust_remote_code=True, dtype=torch.bfloat16 if device == "cuda" else torch.float32, ).to(device) model.eval() # Load variants variants_path = await variants_dir.download() with open(os.path.join(variants_path, "genes.json")) as f: genes = json.load(f) results = {} total_variants = sum(len(g["variants"]) for g in genes.values()) scored = 0 progress_html = """

Carbon Variant Effect Scoring

Model: {model}
Device: {device}
Progress: {scored}/{total} variants scored
""" for gene_name, gene_data in genes.items(): ref_seq = gene_data["sequence"] gene_results = { "description": gene_data.get("description", ""), "sequence": ref_seq, "variants": [], } # Score reference sequence ref_prompt = f"{ref_seq}" ref_inputs = tokenizer(ref_prompt, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): ref_output = model(**ref_inputs, labels=ref_inputs["input_ids"]) ref_loss = ref_output.loss.item() ref_ll = -ref_loss * ref_inputs["input_ids"].shape[1] for variant in gene_data["variants"]: scored += 1 await flyte.report.replace.aio( _wrap_report(progress_html.format( model=model_name, device=device, scored=scored, total=total_variants )), do_flush=True, ) # Create mutant sequence pos = variant["pos"] alt_seq = ref_seq[:pos] + variant["alt"] + ref_seq[pos + 1:] # Score mutant alt_prompt = f"{alt_seq}" alt_inputs = tokenizer(alt_prompt, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): alt_output = model(**alt_inputs, labels=alt_inputs["input_ids"]) alt_loss = alt_output.loss.item() alt_ll = -alt_loss * alt_inputs["input_ids"].shape[1] # VEP score: positive = model prefers alt (likely benign), negative = model prefers ref (likely pathogenic) vep_score = alt_ll - ref_ll gene_results["variants"].append({ **variant, "score": round(vep_score, 4), "ref_ll": round(ref_ll, 4), "alt_ll": round(alt_ll, 4), }) log.info( f" {gene_name} | {variant['name']}: score={vep_score:.4f} " f"(known: {variant['known_effect']})" ) results[gene_name] = gene_results # Generate scoring report html_parts = [ "

Carbon Variant Effect Scoring

", '
', f'
{len(genes)}
Genes
', f'
{total_variants}
Variants Scored
', f'
{model_name.split("/")[-1]}
Model
', f'
{device.upper()}
Device
', "
", ] # Per-gene tables for gene_name, gene_data in results.items(): html_parts.append(f'

{gene_name}

') html_parts.append(f'
{gene_data["description"]}
') html_parts.append("") for v in gene_data["variants"]: badge = EFFECT_BADGES.get(v["known_effect"], "badge-info") direction = "damaging" if v["score"] < -0.1 else "neutral" if abs(v["score"]) <= 0.1 else "tolerated" html_parts.append( f'' f'' f'' f'' f'' f'' f'' f'' ) html_parts.append("
VariantRefAltVEP ScoreKnown EffectClinical
{v["name"]}{v["ref"]}{v["alt"]}{v["score"]:.4f} ({direction}){v["known_effect"]}{v.get("clinical", "")}
") await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) return json.dumps(results) # ------------------------------------------------------------------ # Task 3: Analyze and visualize variant effects # ------------------------------------------------------------------ @cpu_env.task(report=True) async def analyze_effects( scores_json: str, variants_dir: flyte.io.Dir, ) -> str: """Analyze VEP scores: classification accuracy, gene-level summaries, and rich visualizations.""" results = json.loads(scores_json) variants_path = await variants_dir.download() with open(os.path.join(variants_path, "genes.json")) as f: genes = json.load(f) html_parts = ["

Variant Effect Analysis

"] # ------------------------------------------------------------------ # Overall accuracy: does the model's score direction match known labels? # ------------------------------------------------------------------ all_variants = [] correct = 0 total_known = 0 true_pos = 0 false_pos = 0 true_neg = 0 false_neg = 0 for gene_name, gene_data in results.items(): for v in gene_data["variants"]: all_variants.append({**v, "gene": gene_name}) if v["known_effect"] in ("pathogenic", "benign"): total_known += 1 predicted_pathogenic = v["score"] < -0.05 actual_pathogenic = v["known_effect"] == "pathogenic" if predicted_pathogenic == actual_pathogenic: correct += 1 if predicted_pathogenic and actual_pathogenic: true_pos += 1 elif predicted_pathogenic and not actual_pathogenic: false_pos += 1 elif not predicted_pathogenic and actual_pathogenic: false_neg += 1 else: true_neg += 1 accuracy = correct / total_known if total_known else 0 precision = true_pos / (true_pos + false_pos) if (true_pos + false_pos) else 0 recall = true_pos / (true_pos + false_neg) if (true_pos + false_neg) else 0 html_parts.append('
') html_parts.append(f'
{accuracy:.0%}
Direction Accuracy
') html_parts.append(f'
{precision:.0%}
Precision (Pathogenic)
') html_parts.append(f'
{recall:.0%}
Recall (Pathogenic)
') html_parts.append(f'
{len(all_variants)}
Total Variants
') html_parts.append("
") html_parts.append( '
' "How to read VEP scores: Negative scores mean Carbon considers the variant " "less likely than the reference sequence โ€” suggestive of a damaging effect. Scores near " "zero indicate the model sees little difference (likely benign). The magnitude indicates " "confidence." "
" ) # ------------------------------------------------------------------ # Cross-gene score comparison dot plot # ------------------------------------------------------------------ html_parts.append('
') html_parts.append(_make_score_comparison_chart(results)) html_parts.append("
") # ------------------------------------------------------------------ # Per-gene visualizations # ------------------------------------------------------------------ for gene_name, gene_data in results.items(): short_name = gene_name.split("(")[0].strip() html_parts.append(f'

{gene_name}

') html_parts.append(f'
{gene_data["description"]}
') # DNA track with variant positions highlighted html_parts.append('
') html_parts.append(_make_dna_track( gene_data["sequence"], gene_data["variants"], gene_name=f"{short_name} Reference Sequence", )) html_parts.append("
") # Lollipop plot html_parts.append('
') html_parts.append(_make_lollipop_plot( gene_data["variants"], len(gene_data["sequence"]), title=f"{short_name} โ€” Variant Positions & Effect Scores", )) html_parts.append("
") # Score bar chart for this gene variant_names = [v["name"] for v in gene_data["variants"]] variant_scores = [v["score"] for v in gene_data["variants"]] html_parts.append('
') html_parts.append(_make_bar_chart( variant_names, {"VEP Score": variant_scores}, title=f"{short_name} โ€” Log-Likelihood Ratio Scores", colors=[EFFECT_COLORS.get(v["known_effect"], "#6b7280") for v in gene_data["variants"]], value_format=".3f", )) html_parts.append("
") # Variant detail cards for v in gene_data["variants"]: badge = EFFECT_BADGES.get(v["known_effect"], "badge-info") score_color = "#dc2626" if v["score"] < -0.1 else "#059669" if v["score"] > 0.05 else "#f59e0b" html_parts.append( f'
' f'
' f'{v["name"]}' f'{v["known_effect"]}' f'
' f'
' f'
Ref base: ' f'{v["ref"]}
' f'
Alt base: ' f'{v["alt"]}
' f'
VEP Score: ' f'{v["score"]:.4f}
' f'
' f'
{v.get("clinical", "")}
' f'
' ) # ------------------------------------------------------------------ # Confusion matrix as heatmap # ------------------------------------------------------------------ html_parts.append("

Classification Performance

") html_parts.append( '
' "Using a simple threshold (score < -0.05 = predicted pathogenic). " "This is zero-shot โ€” no training on these specific variants." "
" ) conf_matrix = [[true_pos, false_neg], [false_pos, true_neg]] html_parts.append('
') html_parts.append(_make_heatmap( conf_matrix, ["Actual Pathogenic", "Actual Benign"], ["Predicted Pathogenic", "Predicted Benign"], title="Confusion Matrix (Known Variants Only)", value_format=".0f", width=400, height=300, )) html_parts.append("
") # ------------------------------------------------------------------ # Score distribution by known effect # ------------------------------------------------------------------ html_parts.append("

Score Distribution by Known Effect

") pathogenic_scores = [v["score"] for v in all_variants if v["known_effect"] == "pathogenic"] benign_scores = [v["score"] for v in all_variants if v["known_effect"] == "benign"] uncertain_scores = [v["score"] for v in all_variants if v["known_effect"] == "uncertain"] stats_html = '
' for label, scores, color in [ ("Pathogenic", pathogenic_scores, "#dc2626"), ("Benign", benign_scores, "#059669"), ("Uncertain", uncertain_scores, "#f59e0b"), ]: if scores: mean_s = sum(scores) / len(scores) min_s = min(scores) max_s = max(scores) stats_html += ( f'
' f'{label} (n={len(scores)})
' f'Mean: {mean_s:.4f}
' f'Range: [{min_s:.4f}, {max_s:.4f}]' f'
' ) stats_html += "
" html_parts.append(stats_html) # Summary analysis = { "total_variants": len(all_variants), "total_known": total_known, "accuracy": round(accuracy, 4), "precision": round(precision, 4), "recall": round(recall, 4), "true_pos": true_pos, "false_pos": false_pos, "true_neg": true_neg, "false_neg": false_neg, "pathogenic_mean_score": round(sum(pathogenic_scores) / len(pathogenic_scores), 4) if pathogenic_scores else None, "benign_mean_score": round(sum(benign_scores) / len(benign_scores), 4) if benign_scores else None, } await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) return json.dumps(analysis) # ------------------------------------------------------------------ # Task 4: Generate comprehensive summary report # ------------------------------------------------------------------ @cpu_env.task(report=True) async def generate_summary( scores_json: str, analysis_json: str, ) -> str: """Generate the final summary report combining all results.""" results = json.loads(scores_json) analysis = json.loads(analysis_json) html_parts = [ "

Genomic Variant Effect Prediction โ€” Summary

", '
' "This pipeline uses HuggingFace Carbon, an autoregressive genomic foundation model " "trained on 1 trillion tokens of DNA sequence, to perform zero-shot variant effect " "prediction. No fine-tuning or labeled training data was used โ€” the model scores " "variants purely based on its learned understanding of DNA sequence grammar." "
", ] # Key metrics html_parts.append('
') html_parts.append(f'
{len(results)}
Genes Analyzed
') html_parts.append(f'
{analysis["total_variants"]}
Variants Scored
') html_parts.append(f'
{analysis["accuracy"]:.0%}
Direction Accuracy
') html_parts.append(f'
{analysis["precision"]:.0%}
Precision
') html_parts.append(f'
{analysis["recall"]:.0%}
Recall
') html_parts.append("
") # Gene summary table html_parts.append("

Per-Gene Summary

") html_parts.append( "" "" ) for gene_name, gene_data in results.items(): variants = gene_data["variants"] scores = [v["score"] for v in variants] mean_score = sum(scores) / len(scores) if scores else 0 n_path = sum(1 for v in variants if v["known_effect"] == "pathogenic") n_benign = sum(1 for v in variants if v["known_effect"] == "benign") n_unc = sum(1 for v in variants if v["known_effect"] == "uncertain") short = gene_name.split("(")[0].strip() html_parts.append( f"" f"" f'' f'' f'' ) html_parts.append("
GeneVariantsMean ScorePathogenicBenignUncertain
{short}{len(variants)}{mean_score:.4f}{n_path}{n_benign}{n_unc}
") # Cross-gene heatmap: gene x metric gene_names = [g.split("(")[0].strip() for g in results.keys()] metrics = ["Mean Score", "Min Score", "Max Score", "# Variants"] matrix = [] for gene_data in results.values(): scores = [v["score"] for v in gene_data["variants"]] matrix.append([ sum(scores) / len(scores) if scores else 0, min(scores) if scores else 0, max(scores) if scores else 0, len(scores), ]) html_parts.append("

Gene-Level Metrics

") html_parts.append('
') html_parts.append(_make_heatmap( matrix, gene_names, metrics, title="Gene-Level VEP Score Summary", value_format=".2f", width=600, height=350, )) html_parts.append("
") # All variants ranked by score (most damaging first) html_parts.append("

All Variants Ranked by Impact

") all_vars_sorted = [] for gene_name, gene_data in results.items(): for v in gene_data["variants"]: all_vars_sorted.append({**v, "gene": gene_name.split("(")[0].strip()}) all_vars_sorted.sort(key=lambda x: x["score"]) html_parts.append( "" "" ) for i, v in enumerate(all_vars_sorted): badge = EFFECT_BADGES.get(v["known_effect"], "badge-info") score_color = "#dc2626" if v["score"] < -0.1 else "#059669" if v["score"] > 0.05 else "#f59e0b" html_parts.append( f'' f'' f'' f'' ) html_parts.append("
#GeneVariantScoreKnownClinical Significance
{i + 1}{v["gene"]}{v["name"]}{v["score"]:.4f}{v["known_effect"]}{v.get("clinical", "")}
") # Method note html_parts.append( '
' "Method: Zero-shot variant effect prediction using log-likelihood ratio scoring. " "For each variant, we compute score = log P(mutant sequence | Carbon) - log P(reference sequence | Carbon). " "Negative scores indicate the model considers the mutant less probable than the reference, " "which correlates with pathogenicity. This approach requires no fine-tuning and generalizes " "across genes and variant types.

" "Limitations: These are short sequence windows โ€” real clinical VEP would use longer " "genomic context (Carbon supports up to 786kbp). The threshold for pathogenicity classification " "(-0.05) is a simple heuristic; clinical use requires calibrated thresholds per gene." "
" ) await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) return json.dumps({"status": "complete", "analysis": analysis}) # ------------------------------------------------------------------ # Pipeline orchestrator # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @cpu_env.task(report=True) async def pipeline( variants_json: str = "", model_name: str = "HuggingFaceBio/Carbon-3B", ) -> tuple[str, str]: """ End-to-end genomic variant effect prediction pipeline. Returns (scores JSON, analysis JSON). 1. Load and validate gene variants 2. Score variants with Carbon (log-likelihood ratio) 3. Analyze effects โ€” accuracy, visualizations, classification 4. Generate comprehensive summary report """ log.info("Starting genomic variant effect prediction pipeline...") def _pipeline_progress(step: int, label: str) -> str: steps = [ "Load Variants", "Carbon Scoring", "Analyze Effects", "Generate Summary", ] dots = "" for i, s in enumerate(steps): if i + 1 < step: icon = '✓' elif i + 1 == step: icon = '●' else: icon = '○' dots += f"{icon} {s}" return f"""

Genomic Variant Effect Prediction

{dots}

{label}

""" # Stage 1: Load variants await flyte.report.replace.aio( _wrap_report(_pipeline_progress(1, "Loading and validating gene variants...")), do_flush=True, ) var_dir = await load_variants(variants_json=variants_json) # Stage 2: Score with Carbon await flyte.report.replace.aio( _wrap_report(_pipeline_progress(2, "Running Carbon model for variant effect scoring...")), do_flush=True, ) scores_json = await score_variants(variants_dir=var_dir, model_name=model_name) # Stage 3: Analyze effects await flyte.report.replace.aio( _wrap_report(_pipeline_progress(3, "Analyzing variant effects and generating visualizations...")), do_flush=True, ) analysis_json = await analyze_effects(scores_json=scores_json, variants_dir=var_dir) # Stage 4: Summary await flyte.report.replace.aio( _wrap_report(_pipeline_progress(4, "Generating comprehensive summary report...")), do_flush=True, ) summary_json = await generate_summary(scores_json=scores_json, analysis_json=analysis_json) # Final pipeline report analysis = json.loads(analysis_json) results = json.loads(scores_json) final_html = f"""

Pipeline Complete

{len(results)}
Genes Analyzed
{analysis['total_variants']}
Variants Scored
{analysis['accuracy']:.0%}
Direction Accuracy
{analysis['precision']:.0%}
Precision
{analysis['recall']:.0%}
Recall
Model: HuggingFace Carbon | Method: Zero-shot log-likelihood ratio scoring | Genes: {', '.join(g.split('(')[0].strip() for g in results.keys())}
All 4 pipeline stages completed successfully. View individual task reports for detailed visualizations including DNA sequence tracks, variant lollipop plots, VEP score charts, confusion matrices, and ranked variant tables.
""" await flyte.report.replace.aio(_wrap_report(final_html), do_flush=True) log.info("Pipeline complete.") return scores_json, analysis_json # {{/docs-fragment pipeline}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_variant_effect/genomic_variant_effect.py* ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "torch>=2.9.0", # "transformers>=4.49.0", # "accelerate>=0.34.0", # "numpy", # ] # /// ``` ## Orchestrate the pipeline The `pipeline` task loads variants, scores them with Carbon, analyzes classification accuracy against known labels, and generates a summary report. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "torch>=2.9.0", # "transformers>=4.49.0", # "accelerate>=0.34.0", # "numpy", # ] # main = "pipeline" # params = "" # /// import json import logging import math import os import tempfile import flyte import flyte.io import flyte.report # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="genomic-variant-effect", pre=True) gpu_env = flyte.TaskEnvironment( name="genomic-variant-effect-gpu", image=main_img, resources=flyte.Resources(cpu=4, memory="24Gi", gpu=1), ) cpu_env = flyte.TaskEnvironment( name="genomic-variant-effect-cpu", image=main_img, resources=flyte.Resources(cpu=2, memory="6Gi"), depends_on=[gpu_env], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Default gene variants โ€” clinically relevant mutations # ------------------------------------------------------------------ # Each entry: gene name -> { "sequence": reference DNA, "variants": [{ "pos": 0-indexed, "ref": base, "alt": base, "name": "...", "known_effect": "..." }] } # Sequences are short windows (~120-200bp) around the variant site for tractable inference. DEFAULT_GENE_VARIANTS = { "BRCA2 (Breast Cancer)": { "description": "Tumor suppressor critical for DNA repair via homologous recombination. Mutations dramatically increase breast and ovarian cancer risk.", "sequence": "ATGGCCTCGAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAGCAG", "variants": [ {"pos": 12, "ref": "A", "alt": "T", "name": "c.37A>T", "known_effect": "pathogenic", "clinical": "Nonsense mutation โ€” truncates protein early"}, {"pos": 18, "ref": "G", "alt": "A", "name": "c.55G>A", "known_effect": "benign", "clinical": "Synonymous โ€” no amino acid change"}, {"pos": 30, "ref": "C", "alt": "T", "name": "c.91C>T", "known_effect": "pathogenic", "clinical": "Missense in DNA-binding domain"}, {"pos": 45, "ref": "G", "alt": "C", "name": "c.136G>C", "known_effect": "uncertain", "clinical": "Variant of uncertain significance (VUS)"}, ], }, "TP53 (Tumor Suppressor)": { "description": "Guardian of the genome. Activates DNA repair, cell cycle arrest, and apoptosis. Mutated in >50% of human cancers.", "sequence": "ATGGAGGAGCCGCAGTCAGATCCTAGCGTGAGTTTGCACCCTTCAGAGACAGAAACCACTGGATTGGAGACTACTTCCTGAAACAACGTTCTGTCCCCCTTGCCGTCCCAAGCAATGGATGAT", "variants": [ {"pos": 15, "ref": "C", "alt": "T", "name": "R175H", "known_effect": "pathogenic", "clinical": "Hotspot โ€” gain-of-function, dominant negative. Most common TP53 mutation in cancer"}, {"pos": 36, "ref": "T", "alt": "C", "name": "P72R", "known_effect": "benign", "clinical": "Common polymorphism โ€” subtle effect on apoptosis efficiency"}, {"pos": 54, "ref": "C", "alt": "A", "name": "G245S", "known_effect": "pathogenic", "clinical": "Contact mutant โ€” disrupts DNA binding"}, {"pos": 72, "ref": "T", "alt": "G", "name": "R248W", "known_effect": "pathogenic", "clinical": "Structural mutant โ€” destabilizes DNA-binding loop"}, {"pos": 90, "ref": "C", "alt": "T", "name": "R273H", "known_effect": "pathogenic", "clinical": "Contact mutant โ€” directly contacts DNA bases"}, ], }, "CFTR (Cystic Fibrosis)": { "description": "Chloride channel protein. Mutations cause cystic fibrosis โ€” the most common lethal genetic disease in people of European descent.", "sequence": "ATGCAGAGGTCGCCTCTGGAAAAGGCCAGCGTTGTCTCCAAACTTTTTTTCAGCTGGACCAGACCAATTTTGAGGAAAGGATACAGACAGCGCCTGGAATTGTCAGACATATACCAAATCCCTTC", "variants": [ {"pos": 9, "ref": "G", "alt": "A", "name": "G85E", "known_effect": "pathogenic", "clinical": "Disrupts chloride channel processing"}, {"pos": 24, "ref": "C", "alt": "T", "name": "R117H", "known_effect": "pathogenic", "clinical": "Reduces channel conductance โ€” milder CF phenotype"}, {"pos": 48, "ref": "T", "alt": "C", "name": "I148T", "known_effect": "benign", "clinical": "Previously misclassified โ€” now known benign polymorphism"}, {"pos": 66, "ref": "A", "alt": "G", "name": "R334W", "known_effect": "pathogenic", "clinical": "Gating mutation โ€” channel opens less frequently"}, ], }, "KRAS (Oncogene)": { "description": "GTPase signal switch. KRAS mutations are the most common oncogenic driver โ€” found in ~25% of all human cancers, especially pancreatic, colorectal, and lung.", "sequence": "ATGACTGAATATAAACTTGTGGTAGTTGGAGCTGGTGGCGTAGGCAAGAGTGCCTTGACGATACAGCTAATTCAGAATCATTTTGTGGACGAATATGATCCAACAATAGAGGATTCCTACAGGAA", "variants": [ {"pos": 34, "ref": "G", "alt": "T", "name": "G12V", "known_effect": "pathogenic", "clinical": "Locks KRAS in active state โ€” constitutive proliferation signal"}, {"pos": 35, "ref": "G", "alt": "A", "name": "G12D", "known_effect": "pathogenic", "clinical": "Most common KRAS mutation in pancreatic cancer"}, {"pos": 37, "ref": "G", "alt": "T", "name": "G13D", "known_effect": "pathogenic", "clinical": "Constitutively active โ€” common in colorectal cancer"}, {"pos": 60, "ref": "C", "alt": "A", "name": "Q61K", "known_effect": "pathogenic", "clinical": "Impairs GTP hydrolysis โ€” locked ON state"}, ], }, "HBB (Sickle Cell)": { "description": "Beta-globin subunit of hemoglobin. The sickle cell mutation (E6V) is the most well-known single-base disease variant in humans.", "sequence": "ATGGTGCATCTGACTCCTGAGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTGGTCTACCCTTGGACCCAGAGG", "variants": [ {"pos": 17, "ref": "A", "alt": "T", "name": "E6V (HbS)", "known_effect": "pathogenic", "clinical": "THE sickle cell mutation โ€” causes hemoglobin polymerization under low O2"}, {"pos": 19, "ref": "G", "alt": "A", "name": "E6K (HbC)", "known_effect": "pathogenic", "clinical": "Hemoglobin C disease โ€” milder than sickle cell but causes crystal formation"}, {"pos": 36, "ref": "G", "alt": "A", "name": "E26K", "known_effect": "benign", "clinical": "Hemoglobin E โ€” most common Hb variant worldwide, mild effect"}, {"pos": 78, "ref": "C", "alt": "T", "name": "Q39X", "known_effect": "pathogenic", "clinical": "Nonsense โ€” causes beta-thalassemia (no functional beta-globin)"}, ], }, } # DNA base colors (classic genomics color scheme) BASE_COLORS = {"A": "#2ecc71", "T": "#e74c3c", "G": "#f39c12", "C": "#3498db"} BASE_COMPLEMENT = {"A": "T", "T": "A", "G": "C", "C": "G"} # Pathogenicity color scheme EFFECT_COLORS = { "pathogenic": "#dc2626", "benign": "#059669", "uncertain": "#f59e0b", } EFFECT_BADGES = { "pathogenic": "badge-danger", "benign": "badge-success", "uncertain": "badge-warning", } # ------------------------------------------------------------------ # Report styling โ€” genomics-themed deep blues and teals # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers # ------------------------------------------------------------------ def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 300, value_format: str = ".2f", ) -> str: """Generate an SVG grouped bar chart.""" if not labels: return "" default_colors = ["#2563eb", "#1e3a5f", "#3b82f6", "#60a5fa", "#93c5fd"] colors = colors or default_colors ml, mr, mt, mb = 70, 20, 40, 80 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_max = max(abs(v) for v in all_vals) if all_vals else 1 y_min = min(all_vals) if all_vals else 0 # For VEP scores (negative = more damaging), we need to handle negative values if y_min >= 0: y_min_plot = 0 y_max_plot = y_max * 1.15 or 1 else: y_max_plot = max(y_max * 1.15, 0.1) y_min_plot = y_min * 1.15 y_range = y_max_plot - y_min_plot or 1 n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - (v - y_min_plot) / y_range * ch svg = [ f'', f'', ] # Grid lines for i in range(6): y_tick = y_min_plot + y_range * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:{value_format}}' ) # Zero line if y_min_plot < 0 < y_max_plot: zy = sy(0) svg.append( f'' ) # Bars for gi, label in enumerate(labels): gx = ml + gi * group_width + gap for si, (name, vals) in enumerate(series.items()): color = colors[si % len(colors)] bx = gx + si * bar_width val = vals[gi] if val >= 0: by = sy(val) bh = sy(0) - by if y_min_plot < 0 else mt + ch - by else: by = sy(0) if y_min_plot < 0 else mt + ch bh = sy(val) - by svg.append( f'' ) text_y = by - 4 if val >= 0 else by + bh + 12 svg.append( f'' f'{val:{value_format}}' ) # Rotated group label lx = gx + n_series * bar_width / 2 svg.append( f'{label}' ) # Title if title: svg.append( f'{title}' ) # Legend if n_series > 1: lx = ml + cw - len(series) * 110 for si, name in enumerate(series): color = colors[si % len(colors)] svg.append( f'' ) svg.append( f'{name}' ) svg.append("") return "\n".join(svg) def _make_heatmap( matrix: list[list[float]], row_labels: list[str], col_labels: list[str], title: str = "", width: int = 700, height: int = 500, value_format: str = ".2f", diverging: bool = False, ) -> str: """Generate an SVG heatmap. If diverging=True, uses red-white-blue scale centered at 0.""" n_rows = len(matrix) n_cols = len(matrix[0]) if matrix else 0 if not n_rows or not n_cols: return "" show_values = n_rows <= 10 and n_cols <= 12 flat = [v for row in matrix for v in row] v_min = min(flat) v_max = max(flat) if diverging: abs_max = max(abs(v_min), abs(v_max)) or 1 def get_color(v): t = v / abs_max # -1 to 1 if t < 0: # White to red (negative = damaging) r = 255 g = int(255 * (1 + t)) b = int(255 * (1 + t)) else: # White to blue (positive = benign) r = int(255 * (1 - t)) g = int(255 * (1 - t)) b = 255 return f"rgb({r},{g},{b})" else: v_range = v_max - v_min or 1 def get_color(v): t = (v - v_min) / v_range r = int(255 - t * (255 - 30)) g = int(255 - t * (255 - 58)) b = int(255 - t * (255 - 95)) return f"rgb({r},{g},{b})" # Layout ml = max(140, max(len(l) for l in row_labels) * 7 + 20) if row_labels else 140 mr = 20 mt = 80 if col_labels else 40 mb = 30 cw = width - ml - mr ch = height - mt - mb cell_w = cw / n_cols cell_h = ch / n_rows svg = [ f'', f'', ] if title: svg.append( f'{title}' ) # Column labels (rotated) for j, label in enumerate(col_labels): cx = ml + j * cell_w + cell_w / 2 svg.append( f'{label}' ) # Row labels + cells for i, row_label in enumerate(row_labels): ry = mt + i * cell_h + cell_h / 2 svg.append( f'{row_label}' ) for j in range(n_cols): val = matrix[i][j] color = get_color(val) cx = ml + j * cell_w cy = mt + i * cell_h svg.append( f'' ) if show_values: if diverging: t = abs(val) / (max(abs(v_min), abs(v_max)) or 1) else: t = (val - v_min) / (v_max - v_min or 1) text_color = "#fff" if t > 0.55 else "#1a1a2e" font_size = min(10, int(cell_w / 4), int(cell_h / 2.5)) font_size = max(7, font_size) svg.append( f'{val:{value_format}}' ) svg.append("") return "\n".join(svg) def _make_dna_track( sequence: str, variants: list[dict], gene_name: str = "", width: int = 900, ) -> str: """Render a color-coded DNA sequence track with variant positions highlighted.""" chars_per_line = 60 char_w = 11 line_h = 22 label_w = 50 n_lines = (len(sequence) + chars_per_line - 1) // chars_per_line # Extra space for variant annotations variant_positions = {v["pos"] for v in variants} svg_h = n_lines * line_h + 60 svg = [ f'', f'', ] if gene_name: svg.append( f'{gene_name}' ) y_offset = 28 for line_idx in range(n_lines): start = line_idx * chars_per_line end = min(start + chars_per_line, len(sequence)) chunk = sequence[start:end] y = y_offset + line_idx * line_h # Position label svg.append( f'{start + 1}' ) for ci, base in enumerate(chunk): abs_pos = start + ci x = label_w + ci * char_w color = BASE_COLORS.get(base, "#6b7280") is_variant = abs_pos in variant_positions if is_variant: # Red highlight for variant positions svg.append( f'' ) # Small triangle marker above svg.append( f'' ) else: # Subtle background svg.append( f'' ) svg.append( f'{base}' ) # Spacer every 10 bases if (abs_pos + 1) % 10 == 0 and ci < len(chunk) - 1: svg.append( f'' ) # Legend ly = svg_h - 12 lx = label_w for base, color in BASE_COLORS.items(): svg.append(f'') svg.append(f'{base}') lx += 30 lx += 10 svg.append(f'') svg.append(f'Variant site') svg.append("") return "\n".join(svg) def _make_lollipop_plot( variants: list[dict], seq_length: int, title: str = "", width: int = 700, height: int = 200, ) -> str: """Generate a lollipop plot showing variant positions along a gene with effect scores.""" if not variants: return "" ml, mr, mt, mb = 50, 30, 40, 40 cw = width - ml - mr ch = height - mt - mb svg = [ f'', f'', ] if title: svg.append( f'{title}' ) # Gene track (horizontal bar) track_y = mt + ch * 0.7 svg.append( f'' ) # Position labels at ends svg.append( f'1' ) svg.append( f'{seq_length}' ) # Lollipops scores = [v.get("score", 0) for v in variants] max_score = max(abs(s) for s in scores) if scores else 1 for v in variants: pos = v["pos"] score = v.get("score", 0) effect = v.get("known_effect", "uncertain") color = EFFECT_COLORS.get(effect, "#6b7280") x = ml + (pos / max(seq_length - 1, 1)) * cw stem_h = max(20, abs(score) / max_score * (ch * 0.6)) circle_y = track_y - stem_h - 6 # Stem svg.append( f'' ) # Circle svg.append( f'' ) # Label svg.append( f'{v.get("name", "")}' ) # Legend lx = ml for effect, color in EFFECT_COLORS.items(): svg.append(f'') svg.append( f'' f'{effect.title()}' ) lx += len(effect) * 7 + 24 svg.append("") return "\n".join(svg) def _make_score_comparison_chart( gene_results: dict, width: int = 800, height: int = 350, ) -> str: """Generate a dot plot comparing VEP scores across all genes, colored by known effect.""" all_variants = [] for gene_name, gene_data in gene_results.items(): for v in gene_data["variants"]: all_variants.append({ "gene": gene_name.split("(")[0].strip(), "name": v["name"], "score": v.get("score", 0), "known_effect": v["known_effect"], }) if not all_variants: return "" ml, mr, mt, mb = 120, 30, 40, 30 cw = width - ml - mr ch = height - mt - mb scores = [v["score"] for v in all_variants] s_min, s_max = min(scores), max(scores) s_pad = (s_max - s_min) * 0.1 or 0.5 s_min -= s_pad s_max += s_pad s_range = s_max - s_min or 1 def sx(s): return ml + (s - s_min) / s_range * cw svg = [ f'', f'', f'' f'Variant Effect Scores โ€” All Genes', ] # Grid for i in range(6): gx = s_min + s_range * i / 5 px = sx(gx) svg.append( f'' ) svg.append( f'{gx:.2f}' ) # Zero line if s_min < 0 < s_max: zx = sx(0) svg.append( f'' ) # Rows per variant row_h = ch / max(len(all_variants), 1) for i, v in enumerate(all_variants): y = mt + i * row_h + row_h / 2 color = EFFECT_COLORS.get(v["known_effect"], "#6b7280") px = sx(v["score"]) # Label label = f'{v["gene"]} {v["name"]}' svg.append( f'{label}' ) # Connector line svg.append( f'' ) # Dot svg.append( f'' ) svg.append("") return "\n".join(svg) # ------------------------------------------------------------------ # Task 1: Load and validate gene variants # ------------------------------------------------------------------ @cpu_env.task(cache="auto") async def load_variants( variants_json: str = "", ) -> flyte.io.Dir: """Load gene variant definitions, validate sequences, and save to a temp directory.""" if variants_json: genes = json.loads(variants_json) else: genes = DEFAULT_GENE_VARIANTS # Validate valid_bases = set("ATGC") for gene_name, gene_data in genes.items(): seq = gene_data["sequence"].upper() invalid = set(seq) - valid_bases if invalid: log.warning(f"{gene_name}: invalid bases {invalid} โ€” removing them") seq = "".join(b for b in seq if b in valid_bases) gene_data["sequence"] = seq for v in gene_data["variants"]: pos = v["pos"] if pos < 0 or pos >= len(seq): log.warning(f"{gene_name} variant {v['name']}: position {pos} out of range [0, {len(seq)})") elif seq[pos] != v["ref"]: log.warning(f"{gene_name} variant {v['name']}: expected ref={v['ref']} at pos {pos}, found {seq[pos]}") total_variants = sum(len(g["variants"]) for g in genes.values()) log.info(f"Loaded {len(genes)} genes with {total_variants} variants") out_dir = tempfile.mkdtemp(prefix="genomic_vep_") with open(os.path.join(out_dir, "genes.json"), "w") as f: json.dump(genes, f) return await flyte.io.Dir.from_local(out_dir) # ------------------------------------------------------------------ # Task 2: Run Carbon model for variant effect scoring # ------------------------------------------------------------------ @gpu_env.task(report=True) async def score_variants( variants_dir: flyte.io.Dir, model_name: str = "HuggingFaceBio/Carbon-3B", ) -> str: """Score each variant using Carbon's log-likelihood ratio. For each variant, we compute: score = log P(alt_sequence) - log P(ref_sequence) A negative score means the model considers the variant less likely than the reference โ€” suggestive of a damaging/pathogenic effect. A score near zero means the model sees little difference (likely benign). """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer log.info(f"Loading Carbon model: {model_name}") # Load model device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cpu": log.warning("Running on CPU โ€” inference will be slow. GPU recommended for production.") tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_name, trust_remote_code=True, dtype=torch.bfloat16 if device == "cuda" else torch.float32, ).to(device) model.eval() # Load variants variants_path = await variants_dir.download() with open(os.path.join(variants_path, "genes.json")) as f: genes = json.load(f) results = {} total_variants = sum(len(g["variants"]) for g in genes.values()) scored = 0 progress_html = """

Carbon Variant Effect Scoring

Model: {model}
Device: {device}
Progress: {scored}/{total} variants scored
""" for gene_name, gene_data in genes.items(): ref_seq = gene_data["sequence"] gene_results = { "description": gene_data.get("description", ""), "sequence": ref_seq, "variants": [], } # Score reference sequence ref_prompt = f"{ref_seq}" ref_inputs = tokenizer(ref_prompt, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): ref_output = model(**ref_inputs, labels=ref_inputs["input_ids"]) ref_loss = ref_output.loss.item() ref_ll = -ref_loss * ref_inputs["input_ids"].shape[1] for variant in gene_data["variants"]: scored += 1 await flyte.report.replace.aio( _wrap_report(progress_html.format( model=model_name, device=device, scored=scored, total=total_variants )), do_flush=True, ) # Create mutant sequence pos = variant["pos"] alt_seq = ref_seq[:pos] + variant["alt"] + ref_seq[pos + 1:] # Score mutant alt_prompt = f"{alt_seq}" alt_inputs = tokenizer(alt_prompt, return_tensors="pt", add_special_tokens=False).to(device) with torch.no_grad(): alt_output = model(**alt_inputs, labels=alt_inputs["input_ids"]) alt_loss = alt_output.loss.item() alt_ll = -alt_loss * alt_inputs["input_ids"].shape[1] # VEP score: positive = model prefers alt (likely benign), negative = model prefers ref (likely pathogenic) vep_score = alt_ll - ref_ll gene_results["variants"].append({ **variant, "score": round(vep_score, 4), "ref_ll": round(ref_ll, 4), "alt_ll": round(alt_ll, 4), }) log.info( f" {gene_name} | {variant['name']}: score={vep_score:.4f} " f"(known: {variant['known_effect']})" ) results[gene_name] = gene_results # Generate scoring report html_parts = [ "

Carbon Variant Effect Scoring

", '
', f'
{len(genes)}
Genes
', f'
{total_variants}
Variants Scored
', f'
{model_name.split("/")[-1]}
Model
', f'
{device.upper()}
Device
', "
", ] # Per-gene tables for gene_name, gene_data in results.items(): html_parts.append(f'

{gene_name}

') html_parts.append(f'
{gene_data["description"]}
') html_parts.append("") for v in gene_data["variants"]: badge = EFFECT_BADGES.get(v["known_effect"], "badge-info") direction = "damaging" if v["score"] < -0.1 else "neutral" if abs(v["score"]) <= 0.1 else "tolerated" html_parts.append( f'' f'' f'' f'' f'' f'' f'' f'' ) html_parts.append("
VariantRefAltVEP ScoreKnown EffectClinical
{v["name"]}{v["ref"]}{v["alt"]}{v["score"]:.4f} ({direction}){v["known_effect"]}{v.get("clinical", "")}
") await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) return json.dumps(results) # ------------------------------------------------------------------ # Task 3: Analyze and visualize variant effects # ------------------------------------------------------------------ @cpu_env.task(report=True) async def analyze_effects( scores_json: str, variants_dir: flyte.io.Dir, ) -> str: """Analyze VEP scores: classification accuracy, gene-level summaries, and rich visualizations.""" results = json.loads(scores_json) variants_path = await variants_dir.download() with open(os.path.join(variants_path, "genes.json")) as f: genes = json.load(f) html_parts = ["

Variant Effect Analysis

"] # ------------------------------------------------------------------ # Overall accuracy: does the model's score direction match known labels? # ------------------------------------------------------------------ all_variants = [] correct = 0 total_known = 0 true_pos = 0 false_pos = 0 true_neg = 0 false_neg = 0 for gene_name, gene_data in results.items(): for v in gene_data["variants"]: all_variants.append({**v, "gene": gene_name}) if v["known_effect"] in ("pathogenic", "benign"): total_known += 1 predicted_pathogenic = v["score"] < -0.05 actual_pathogenic = v["known_effect"] == "pathogenic" if predicted_pathogenic == actual_pathogenic: correct += 1 if predicted_pathogenic and actual_pathogenic: true_pos += 1 elif predicted_pathogenic and not actual_pathogenic: false_pos += 1 elif not predicted_pathogenic and actual_pathogenic: false_neg += 1 else: true_neg += 1 accuracy = correct / total_known if total_known else 0 precision = true_pos / (true_pos + false_pos) if (true_pos + false_pos) else 0 recall = true_pos / (true_pos + false_neg) if (true_pos + false_neg) else 0 html_parts.append('
') html_parts.append(f'
{accuracy:.0%}
Direction Accuracy
') html_parts.append(f'
{precision:.0%}
Precision (Pathogenic)
') html_parts.append(f'
{recall:.0%}
Recall (Pathogenic)
') html_parts.append(f'
{len(all_variants)}
Total Variants
') html_parts.append("
") html_parts.append( '
' "How to read VEP scores: Negative scores mean Carbon considers the variant " "less likely than the reference sequence โ€” suggestive of a damaging effect. Scores near " "zero indicate the model sees little difference (likely benign). The magnitude indicates " "confidence." "
" ) # ------------------------------------------------------------------ # Cross-gene score comparison dot plot # ------------------------------------------------------------------ html_parts.append('
') html_parts.append(_make_score_comparison_chart(results)) html_parts.append("
") # ------------------------------------------------------------------ # Per-gene visualizations # ------------------------------------------------------------------ for gene_name, gene_data in results.items(): short_name = gene_name.split("(")[0].strip() html_parts.append(f'

{gene_name}

') html_parts.append(f'
{gene_data["description"]}
') # DNA track with variant positions highlighted html_parts.append('
') html_parts.append(_make_dna_track( gene_data["sequence"], gene_data["variants"], gene_name=f"{short_name} Reference Sequence", )) html_parts.append("
") # Lollipop plot html_parts.append('
') html_parts.append(_make_lollipop_plot( gene_data["variants"], len(gene_data["sequence"]), title=f"{short_name} โ€” Variant Positions & Effect Scores", )) html_parts.append("
") # Score bar chart for this gene variant_names = [v["name"] for v in gene_data["variants"]] variant_scores = [v["score"] for v in gene_data["variants"]] html_parts.append('
') html_parts.append(_make_bar_chart( variant_names, {"VEP Score": variant_scores}, title=f"{short_name} โ€” Log-Likelihood Ratio Scores", colors=[EFFECT_COLORS.get(v["known_effect"], "#6b7280") for v in gene_data["variants"]], value_format=".3f", )) html_parts.append("
") # Variant detail cards for v in gene_data["variants"]: badge = EFFECT_BADGES.get(v["known_effect"], "badge-info") score_color = "#dc2626" if v["score"] < -0.1 else "#059669" if v["score"] > 0.05 else "#f59e0b" html_parts.append( f'
' f'
' f'{v["name"]}' f'{v["known_effect"]}' f'
' f'
' f'
Ref base: ' f'{v["ref"]}
' f'
Alt base: ' f'{v["alt"]}
' f'
VEP Score: ' f'{v["score"]:.4f}
' f'
' f'
{v.get("clinical", "")}
' f'
' ) # ------------------------------------------------------------------ # Confusion matrix as heatmap # ------------------------------------------------------------------ html_parts.append("

Classification Performance

") html_parts.append( '
' "Using a simple threshold (score < -0.05 = predicted pathogenic). " "This is zero-shot โ€” no training on these specific variants." "
" ) conf_matrix = [[true_pos, false_neg], [false_pos, true_neg]] html_parts.append('
') html_parts.append(_make_heatmap( conf_matrix, ["Actual Pathogenic", "Actual Benign"], ["Predicted Pathogenic", "Predicted Benign"], title="Confusion Matrix (Known Variants Only)", value_format=".0f", width=400, height=300, )) html_parts.append("
") # ------------------------------------------------------------------ # Score distribution by known effect # ------------------------------------------------------------------ html_parts.append("

Score Distribution by Known Effect

") pathogenic_scores = [v["score"] for v in all_variants if v["known_effect"] == "pathogenic"] benign_scores = [v["score"] for v in all_variants if v["known_effect"] == "benign"] uncertain_scores = [v["score"] for v in all_variants if v["known_effect"] == "uncertain"] stats_html = '
' for label, scores, color in [ ("Pathogenic", pathogenic_scores, "#dc2626"), ("Benign", benign_scores, "#059669"), ("Uncertain", uncertain_scores, "#f59e0b"), ]: if scores: mean_s = sum(scores) / len(scores) min_s = min(scores) max_s = max(scores) stats_html += ( f'
' f'{label} (n={len(scores)})
' f'Mean: {mean_s:.4f}
' f'Range: [{min_s:.4f}, {max_s:.4f}]' f'
' ) stats_html += "
" html_parts.append(stats_html) # Summary analysis = { "total_variants": len(all_variants), "total_known": total_known, "accuracy": round(accuracy, 4), "precision": round(precision, 4), "recall": round(recall, 4), "true_pos": true_pos, "false_pos": false_pos, "true_neg": true_neg, "false_neg": false_neg, "pathogenic_mean_score": round(sum(pathogenic_scores) / len(pathogenic_scores), 4) if pathogenic_scores else None, "benign_mean_score": round(sum(benign_scores) / len(benign_scores), 4) if benign_scores else None, } await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) return json.dumps(analysis) # ------------------------------------------------------------------ # Task 4: Generate comprehensive summary report # ------------------------------------------------------------------ @cpu_env.task(report=True) async def generate_summary( scores_json: str, analysis_json: str, ) -> str: """Generate the final summary report combining all results.""" results = json.loads(scores_json) analysis = json.loads(analysis_json) html_parts = [ "

Genomic Variant Effect Prediction โ€” Summary

", '
' "This pipeline uses HuggingFace Carbon, an autoregressive genomic foundation model " "trained on 1 trillion tokens of DNA sequence, to perform zero-shot variant effect " "prediction. No fine-tuning or labeled training data was used โ€” the model scores " "variants purely based on its learned understanding of DNA sequence grammar." "
", ] # Key metrics html_parts.append('
') html_parts.append(f'
{len(results)}
Genes Analyzed
') html_parts.append(f'
{analysis["total_variants"]}
Variants Scored
') html_parts.append(f'
{analysis["accuracy"]:.0%}
Direction Accuracy
') html_parts.append(f'
{analysis["precision"]:.0%}
Precision
') html_parts.append(f'
{analysis["recall"]:.0%}
Recall
') html_parts.append("
") # Gene summary table html_parts.append("

Per-Gene Summary

") html_parts.append( "" "" ) for gene_name, gene_data in results.items(): variants = gene_data["variants"] scores = [v["score"] for v in variants] mean_score = sum(scores) / len(scores) if scores else 0 n_path = sum(1 for v in variants if v["known_effect"] == "pathogenic") n_benign = sum(1 for v in variants if v["known_effect"] == "benign") n_unc = sum(1 for v in variants if v["known_effect"] == "uncertain") short = gene_name.split("(")[0].strip() html_parts.append( f"" f"" f'' f'' f'' ) html_parts.append("
GeneVariantsMean ScorePathogenicBenignUncertain
{short}{len(variants)}{mean_score:.4f}{n_path}{n_benign}{n_unc}
") # Cross-gene heatmap: gene x metric gene_names = [g.split("(")[0].strip() for g in results.keys()] metrics = ["Mean Score", "Min Score", "Max Score", "# Variants"] matrix = [] for gene_data in results.values(): scores = [v["score"] for v in gene_data["variants"]] matrix.append([ sum(scores) / len(scores) if scores else 0, min(scores) if scores else 0, max(scores) if scores else 0, len(scores), ]) html_parts.append("

Gene-Level Metrics

") html_parts.append('
') html_parts.append(_make_heatmap( matrix, gene_names, metrics, title="Gene-Level VEP Score Summary", value_format=".2f", width=600, height=350, )) html_parts.append("
") # All variants ranked by score (most damaging first) html_parts.append("

All Variants Ranked by Impact

") all_vars_sorted = [] for gene_name, gene_data in results.items(): for v in gene_data["variants"]: all_vars_sorted.append({**v, "gene": gene_name.split("(")[0].strip()}) all_vars_sorted.sort(key=lambda x: x["score"]) html_parts.append( "" "" ) for i, v in enumerate(all_vars_sorted): badge = EFFECT_BADGES.get(v["known_effect"], "badge-info") score_color = "#dc2626" if v["score"] < -0.1 else "#059669" if v["score"] > 0.05 else "#f59e0b" html_parts.append( f'' f'' f'' f'' ) html_parts.append("
#GeneVariantScoreKnownClinical Significance
{i + 1}{v["gene"]}{v["name"]}{v["score"]:.4f}{v["known_effect"]}{v.get("clinical", "")}
") # Method note html_parts.append( '
' "Method: Zero-shot variant effect prediction using log-likelihood ratio scoring. " "For each variant, we compute score = log P(mutant sequence | Carbon) - log P(reference sequence | Carbon). " "Negative scores indicate the model considers the mutant less probable than the reference, " "which correlates with pathogenicity. This approach requires no fine-tuning and generalizes " "across genes and variant types.

" "Limitations: These are short sequence windows โ€” real clinical VEP would use longer " "genomic context (Carbon supports up to 786kbp). The threshold for pathogenicity classification " "(-0.05) is a simple heuristic; clinical use requires calibrated thresholds per gene." "
" ) await flyte.report.replace.aio(_wrap_report("\n".join(html_parts)), do_flush=True) return json.dumps({"status": "complete", "analysis": analysis}) # ------------------------------------------------------------------ # Pipeline orchestrator # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @cpu_env.task(report=True) async def pipeline( variants_json: str = "", model_name: str = "HuggingFaceBio/Carbon-3B", ) -> tuple[str, str]: """ End-to-end genomic variant effect prediction pipeline. Returns (scores JSON, analysis JSON). 1. Load and validate gene variants 2. Score variants with Carbon (log-likelihood ratio) 3. Analyze effects โ€” accuracy, visualizations, classification 4. Generate comprehensive summary report """ log.info("Starting genomic variant effect prediction pipeline...") def _pipeline_progress(step: int, label: str) -> str: steps = [ "Load Variants", "Carbon Scoring", "Analyze Effects", "Generate Summary", ] dots = "" for i, s in enumerate(steps): if i + 1 < step: icon = '✓' elif i + 1 == step: icon = '●' else: icon = '○' dots += f"{icon} {s}" return f"""

Genomic Variant Effect Prediction

{dots}

{label}

""" # Stage 1: Load variants await flyte.report.replace.aio( _wrap_report(_pipeline_progress(1, "Loading and validating gene variants...")), do_flush=True, ) var_dir = await load_variants(variants_json=variants_json) # Stage 2: Score with Carbon await flyte.report.replace.aio( _wrap_report(_pipeline_progress(2, "Running Carbon model for variant effect scoring...")), do_flush=True, ) scores_json = await score_variants(variants_dir=var_dir, model_name=model_name) # Stage 3: Analyze effects await flyte.report.replace.aio( _wrap_report(_pipeline_progress(3, "Analyzing variant effects and generating visualizations...")), do_flush=True, ) analysis_json = await analyze_effects(scores_json=scores_json, variants_dir=var_dir) # Stage 4: Summary await flyte.report.replace.aio( _wrap_report(_pipeline_progress(4, "Generating comprehensive summary report...")), do_flush=True, ) summary_json = await generate_summary(scores_json=scores_json, analysis_json=analysis_json) # Final pipeline report analysis = json.loads(analysis_json) results = json.loads(scores_json) final_html = f"""

Pipeline Complete

{len(results)}
Genes Analyzed
{analysis['total_variants']}
Variants Scored
{analysis['accuracy']:.0%}
Direction Accuracy
{analysis['precision']:.0%}
Precision
{analysis['recall']:.0%}
Recall
Model: HuggingFace Carbon | Method: Zero-shot log-likelihood ratio scoring | Genes: {', '.join(g.split('(')[0].strip() for g in results.keys())}
All 4 pipeline stages completed successfully. View individual task reports for detailed visualizations including DNA sequence tracks, variant lollipop plots, VEP score charts, confusion matrices, and ranked variant tables.
""" await flyte.report.replace.aio(_wrap_report(final_html), do_flush=True) log.info("Pipeline complete.") return scores_json, analysis_json # {{/docs-fragment pipeline}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/genomic_variant_effect/genomic_variant_effect.py* ## Run the workflow From the [example directory](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/genomic_variant_effect): ``` cd v2/tutorials/genomic_variant_effect uv run --script genomic_variant_effect.py ``` Use a smaller Carbon model for faster iteration: ``` flyte run genomic_variant_effect.py pipeline --model_name HuggingFaceBio/Carbon-500M ``` Negative VEP scores indicate the model prefers the reference allele over the alternate, a signal correlated with pathogenicity in this zero-shot setup. === PAGE: https://www.union.ai/docs/v2/union/tutorials/biotech-healthcare/drug-molecule-screening === Agentic virtual screening with RDKit stage tools, Lipinski filters, and ranked drug-likeness reports. # Drug molecule screening agent > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/drug_molecule_screening). This tutorial builds an **agentic** virtual drug-screening workflow on Flyte. A medicinal-chemistry agent interprets your therapeutic goal in plain language, derives screening criteria, and composes durable RDKit stage tasks, while the scientific core (property computation, Lipinski filters, Tanimoto similarity, ranking, and HTML reports) stays in trusted, deterministic tools. The pattern follows how cheminformatics agents like ChemCrow and PharmAgents are built: **the LLM plans and reflects; RDKit computes.** Flyte provides: - **Flyte-native agent orchestration** via `flyte.ai.agents.Agent` (see **Agents > Build an agent > Flyte-native agents**) - **Typed agent tool I/O**: Flyte 2.5.4+ passes `flyte.io.Dir`, `File`, and `DataFrame` between agent tool calls so the LLM can compose multi-step pipelines directly - **Cached molecule loading** so repeated runs skip re-parsing SMILES - **Report-enabled stage tasks** that stream property charts, similarity matrices, and candidate spotlights as each step completes - **Hybrid iteration**: the agent re-runs `screen_candidates` and `generate_report` with adjusted criteria when the funnel is too narrow, reusing cached `molecule_dir` and `properties_json` > [!NOTE] Prerequisites > Create an Anthropic API key secret (the key name must match the `TaskEnvironment`): > > ``` > flyte create secret internal-anthropic-api-key --value > ``` > > See **Tasks > Configure tasks > Secrets** for scoping and file-based secrets. ## Define the task environment The pipeline runs on CPU with RDKit, LiteLLM, and system libraries for 2D structure rendering. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.5.4", # "litellm", # "rdkit", # "numpy", # "scikit-learn", # "pillow", # ] # main = "pipeline" # params = "" # /// """Virtual drug molecule screening โ€” compute properties, apply Lipinski filters, rank candidates.""" import base64 import io import json import logging import math import os import tempfile import flyte import flyte.io import flyte.report from flyte.ai.agents import Agent, tool MODEL = os.getenv("DRUG_SCREENING_MODEL", "claude-haiku-4-5") # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="drug-molecule-screening", pre=True).with_apt_packages( "libxrender1", "libxext6", "libexpat1", ) env = flyte.TaskEnvironment( name="drug-molecule-screening", image=main_img, resources=flyte.Resources(cpu=2, memory="6Gi"), secrets=[ flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Default molecule library โ€” real SMILES for well-known drugs # ------------------------------------------------------------------ DEFAULT_MOLECULES = { "Aspirin": "CC(=O)OC1=CC=CC=C1C(=O)O", "Ibuprofen": "CC(C)CC1=CC=C(C=C1)C(C)C(=O)O", "Caffeine": "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", "Penicillin G": "CC1(C(N2C(S1)C(C2=O)NC(=O)CC3=CC=CC=C3)C(=O)O)C", "Metformin": "CN(C)C(=N)NC(=N)N", "Paracetamol": "CC(=O)NC1=CC=C(C=C1)O", "Diazepam": "ClC1=CC2=C(C=C1)N(C(=O)CN=C2C3=CC=CC=C3)C", "Omeprazole": "CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=CC=CC=C3N2", "Atorvastatin": "CC(C)C1=C(C(=C(N1CCC(CC(CC(=O)O)O)O)C2=CC=C(C=C2)F)C3=CC=CC=C3)C(=O)NC4=CC=CC=C4", "Methotrexate": "CN(CC1=CN=C2N=C(N=C(N)C2=N1)N)C3=CC=C(C=C3)C(=O)NC(CCC(=O)O)C(=O)O", "Doxorubicin": "CC1C(C(CC(O1)OC2CC(CC3=C2C(=C4C(=C3O)C(=O)C5=C(C4=O)C(=CC=C5)OC)O)(C(=O)CO)O)N)O", "Tamoxifen": "CCC(=C(C1=CC=CC=C1)C2=CC=C(C=C2)OCCN(C)C)C3=CC=CC=C3", "Lopinavir": "CC1=C(C(=CC=C1)C)OCC(=O)NC(CC2=CC=CC=C2)C(CC(CC3=CC=CC=C3)NC(=O)C(C(C)C)N4CCCNC4=O)O", "Remdesivir": "CCC(CC)COC(=O)C(C)NP(=O)(OCC1C(C(C(O1)C2=CC=C3N2N=CN=C3N)O)O)OC4=CC=CC=C4", "Erlotinib": "COCCOC1=CC2=C(C=C1OCCOC)C(=NC=N2)NC3=CC=CC(=C3)C#C", } # ------------------------------------------------------------------ # Report styling โ€” pharma blue/cyan theme # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: """Wrap HTML content with report styling.""" return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers # ------------------------------------------------------------------ def _mol_to_data_uri(mol, size: tuple[int, int] = (300, 300)) -> str: """Convert an RDKit molecule to a PNG base64 data URI.""" from rdkit.Chem import Draw img = Draw.MolToImage(mol, size=size) buf = io.BytesIO() img.save(buf, format="PNG") b64 = base64.b64encode(buf.getvalue()).decode() return f"data:image/png;base64,{b64}" def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 340, y_max_cap: float | None = None, horizontal: bool = False, value_fmt: str = ".1f", ) -> str: """Generate an SVG grouped bar chart. Args: labels: Category labels. series: Dict mapping series name to list of values. title: Chart title. colors: Colors for each series. width/height: SVG dimensions. y_max_cap: Cap the y-axis at this value. horizontal: If True, draw horizontal bars. value_fmt: Format string for value labels. Returns: SVG string. """ if not labels: return "" default_colors = ["#0891b2", "#0e4f6e", "#06d6a0", "#a5f3fc", "#155e75"] colors = colors or default_colors if horizontal: return _make_horizontal_bar_chart(labels, series, title, colors, width, height, value_fmt) ml, mr, mt, mb = 60, 20, 40, 60 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_max = max(all_vals) if all_vals else 1 y_max_plot = y_max * 1.15 or 1 if y_max_cap is not None: y_max_plot = min(y_max_plot, y_max_cap) or y_max_cap n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - (v / y_max_plot) * ch svg = [ f'', f'', ] # Grid lines for i in range(6): y_tick = y_max_plot * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:{value_fmt}}' ) # Axes svg.append( f'' ) svg.append( f'' ) # Bars for gi, label in enumerate(labels): gx = ml + gi * group_width + gap for si, (name, vals) in enumerate(series.items()): color = colors[si % len(colors)] bx = gx + si * bar_width val = vals[gi] by = sy(val) bh = mt + ch - by svg.append( f'' ) svg.append( f'' f'{val:{value_fmt}}' ) # Truncate long labels disp_label = label if len(label) <= 12 else label[:10] + ".." svg.append( f'' f'{disp_label}' ) # Title if title: svg.append( f'{title}' ) # Legend if n_series > 1: lx = ml + cw - len(series) * 100 for si, name in enumerate(series): color = colors[si % len(colors)] svg.append( f'' ) svg.append( f'{name}' ) svg.append("") return "\n".join(svg) def _make_horizontal_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 400, value_fmt: str = ".1f", ) -> str: """Generate an SVG horizontal bar chart (sorted).""" default_colors = ["#0891b2", "#0e4f6e", "#06d6a0"] colors = colors or default_colors n = len(labels) row_height = max(22, min(35, (height - 80) // max(n, 1))) actual_height = max(height, 80 + n * row_height) ml, mr, mt, mb = 120, 60, 40, 20 cw = width - ml - mr ch = actual_height - mt - mb # Use first series first_key = list(series.keys())[0] vals = series[first_key] x_max = max(vals) * 1.15 if vals else 1 svg = [ f'', f'', ] if title: svg.append( f'{title}' ) bar_h = row_height * 0.65 for i, (label, val) in enumerate(zip(labels, vals)): y = mt + i * row_height bw = (val / x_max) * cw if x_max else 0 color = colors[i % len(colors)] # Label disp = label if len(label) <= 14 else label[:12] + ".." svg.append( f'{disp}' ) # Bar svg.append( f'' ) # Value svg.append( f'{val:{value_fmt}}' ) svg.append("") return "\n".join(svg) def _make_heatmap( matrix: list[list[float]], row_labels: list[str], col_labels: list[str], title: str = "", color_scale: str = "cyan", width: int = 700, height: int = 500, value_fmt: str = ".2f", ) -> str: """Generate an SVG heatmap. Args: matrix: 2D list of values (rows x cols). row_labels: Labels for rows. col_labels: Labels for columns. title: Chart title. color_scale: Color scheme ("cyan", "red", "green"). width/height: SVG dimensions. value_fmt: Format string for cell values. Returns: SVG string. """ if not matrix or not matrix[0]: return "" n_rows = len(matrix) n_cols = len(matrix[0]) ml, mr, mt, mb = 110, 20, 70, 20 cw = width - ml - mr ch = height - mt - mb cell_w = cw / n_cols cell_h = ch / n_rows # Flatten to find range flat = [v for row in matrix for v in row] v_min = min(flat) v_max = max(flat) v_range = v_max - v_min or 1 def color_for(v): t = (v - v_min) / v_range if color_scale == "cyan": # White to deep teal r = int(255 - t * (255 - 14)) g = int(255 - t * (255 - 79)) b = int(255 - t * (255 - 110)) elif color_scale == "red": r = int(255 - t * 50) g = int(255 - t * 200) b = int(255 - t * 200) else: # green r = int(255 - t * 200) g = int(255 - t * 50) b = int(255 - t * 200) return f"rgb({r},{g},{b})" svg = [ f'', f'', ] if title: svg.append( f'{title}' ) # Column labels (rotated) for ci, label in enumerate(col_labels): x = ml + ci * cell_w + cell_w / 2 disp = label if len(label) <= 12 else label[:10] + ".." svg.append( f'{disp}' ) # Row labels + cells for ri, (row_label, row_vals) in enumerate(zip(row_labels, matrix)): y = mt + ri * cell_h disp = row_label if len(row_label) <= 14 else row_label[:12] + ".." svg.append( f'{disp}' ) for ci, val in enumerate(row_vals): x = ml + ci * cell_w fill = color_for(val) svg.append( f'' ) # Text color: dark on light, light on dark t = (val - v_min) / v_range txt_color = "#fff" if t > 0.55 else "#1a1a2e" # Only show text if cells are large enough if cell_w > 30 and cell_h > 18: svg.append( f'' f'{val:{value_fmt}}' ) svg.append("") return "\n".join(svg) def _make_scatter_plot( points: list[dict], x_label: str = "MW", y_label: str = "LogP", title: str = "", reference_lines: list[dict] | None = None, width: int = 700, height: int = 400, ) -> str: """Generate an SVG scatter plot. Args: points: List of dicts with "x", "y", "label" keys. x_label/y_label: Axis labels. title: Chart title. reference_lines: List of dicts with "axis" ("x"/"y"), "value", "label". width/height: SVG dimensions. Returns: SVG string. """ if not points: return "" ml, mr, mt, mb = 60, 30, 40, 50 cw = width - ml - mr ch = height - mt - mb x_vals = [p["x"] for p in points] y_vals = [p["y"] for p in points] x_min, x_max = min(x_vals) * 0.9, max(x_vals) * 1.1 y_min, y_max = min(y_vals) - 1, max(y_vals) + 1 # Extend ranges to include reference lines if reference_lines: for rl in reference_lines: if rl["axis"] == "x": x_max = max(x_max, rl["value"] * 1.1) else: y_max = max(y_max, rl["value"] * 1.1) x_range = x_max - x_min or 1 y_range = y_max - y_min or 1 def sx(v): return ml + (v - x_min) / x_range * cw def sy(v): return mt + ch - (v - y_min) / y_range * ch svg = [ f'', f'', ] # Grid for i in range(6): y_tick = y_min + y_range * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:.1f}' ) for i in range(6): x_tick = x_min + x_range * i / 5 px = sx(x_tick) svg.append( f'{x_tick:.0f}' ) # Axes svg.append( f'' ) svg.append( f'' ) # Reference lines (Lipinski boundaries) if reference_lines: for rl in reference_lines: if rl["axis"] == "x": px = sx(rl["value"]) svg.append( f'' ) svg.append( f'{rl["label"]}' ) else: py = sy(rl["value"]) svg.append( f'' ) svg.append( f'{rl["label"]}' ) # Drug-like zone shading (MW<=500 and LogP<=5 quadrant) if reference_lines: mw_line = next((rl for rl in reference_lines if rl["axis"] == "x"), None) logp_line = next((rl for rl in reference_lines if rl["axis"] == "y"), None) if mw_line and logp_line: zx1 = sx(x_min) zx2 = sx(min(mw_line["value"], x_max)) zy1 = sy(min(logp_line["value"], y_max)) zy2 = sy(y_min) svg.append( f'' ) svg.append( f'Drug-like Zone' ) # Points point_colors = ["#0891b2", "#0e4f6e", "#06d6a0", "#155e75", "#0284c7", "#059669", "#0d9488", "#0369a1", "#047857", "#115e59", "#0c4a6e", "#064e3b", "#1e3a5f", "#134e4a", "#075985"] for i, pt in enumerate(points): px, py = sx(pt["x"]), sy(pt["y"]) color = point_colors[i % len(point_colors)] svg.append( f'' ) # Label offset to avoid overlap offset_x = 8 offset_y = -8 if i % 2 == 0 else 14 label = pt["label"] if len(pt["label"]) <= 12 else pt["label"][:10] + ".." svg.append( f'{label}' ) # Title if title: svg.append( f'{title}' ) # Axis labels if x_label: svg.append( f'{x_label}' ) if y_label: svg.append( f'{y_label}' ) svg.append("") return "\n".join(svg) def _make_funnel( stages: list[dict], title: str = "", width: int = 600, height: int = 400, ) -> str: """Generate an SVG funnel visualization. Args: stages: List of dicts with "label", "count", "total" keys. title: Chart title. width/height: SVG dimensions. Returns: SVG string. """ if not stages: return "" n = len(stages) mt = 50 mb = 20 available_h = height - mt - mb stage_h = available_h / n cx = width / 2 # Color gradient from light cyan to deep teal colors = [] for i in range(n): t = i / max(n - 1, 1) r = int(207 - t * (207 - 14)) g = int(250 - t * (250 - 79)) b = int(254 - t * (254 - 110)) colors.append(f"rgb({r},{g},{b})") svg = [ f'', f'', ] if title: svg.append( f'{title}' ) max_count = stages[0]["count"] if stages else 1 max_width = width * 0.75 for i, stage in enumerate(stages): y_top = mt + i * stage_h y_bot = y_top + stage_h # Width proportional to count w_top = max_width * (stage["count"] / max_count) if i == 0 else prev_w_bot if i < n - 1: w_bot = max_width * (stages[i + 1]["count"] / max_count) else: w_bot = max_width * (stage["count"] / max_count) * 0.7 prev_w_bot = w_bot # Trapezoid x1_top = cx - w_top / 2 x2_top = cx + w_top / 2 x1_bot = cx - w_bot / 2 x2_bot = cx + w_bot / 2 svg.append( f'' ) # Text: dark on light, white on dark t = i / max(n - 1, 1) txt_color = "#0e4f6e" if t < 0.5 else "#fff" y_mid = (y_top + y_bot) / 2 svg.append( f'{stage["label"]}' ) svg.append( f'' f'{stage["count"]} / {stage["total"]}' ) svg.append("") return "\n".join(svg) # ------------------------------------------------------------------ # Task 1: Load and validate molecules # ------------------------------------------------------------------ @tool @env.task(cache="auto") async def load_molecules( molecules_json: str = "", ) -> flyte.io.Dir: """Parse SMILES strings, validate with RDKit, generate 2D depictions. Args: molecules_json: JSON string mapping molecule names to SMILES. Defaults to a curated library of ~15 well-known drugs. Returns: flyte.io.Dir containing molecule data (JSON + PNG depictions). Pass this directory to compute_properties and generate_report. """ from rdkit import Chem from rdkit.Chem import Draw if molecules_json.strip(): molecules = json.loads(molecules_json) else: molecules = DEFAULT_MOLECULES out_dir = tempfile.mkdtemp(prefix="mol_library_") results = [] valid_count = 0 invalid_count = 0 log.info(f"Parsing {len(molecules)} molecules...") for name, smiles in molecules.items(): mol = Chem.MolFromSmiles(smiles) if mol is None: log.warning(f" [INVALID] {name}: {smiles}") invalid_count += 1 continue valid_count += 1 # Generate 2D depiction as PNG img = Draw.MolToImage(mol, size=(300, 300)) img_path = os.path.join(out_dir, f"{name.replace(' ', '_')}.png") img.save(img_path) results.append({ "name": name, "smiles": smiles, "valid": True, "image_file": os.path.basename(img_path), }) # Save molecule manifest manifest = { "total": len(molecules), "valid": valid_count, "invalid": invalid_count, "molecules": results, } manifest_path = os.path.join(out_dir, "manifest.json") with open(manifest_path, "w") as f: json.dump(manifest, f, indent=2) log.info(f"Loaded {valid_count} valid molecules ({invalid_count} invalid)") return await flyte.io.Dir.from_local(out_dir) # ------------------------------------------------------------------ # Task 2: Compute physicochemical properties # ------------------------------------------------------------------ @tool @env.task(report=True) async def compute_properties( molecule_dir: flyte.io.Dir, ) -> str: """Compute drug-likeness properties for all molecules. Computes MW, LogP, HBD, HBA, TPSA, rotatable bonds, formal charge, ring count, QED, and Lipinski Rule of Five compliance. Args: molecule_dir: Directory from load_molecules. Returns: JSON string with all computed properties. Pass to screen_candidates and generate_report. """ from rdkit import Chem from rdkit.Chem import Descriptors, Lipinski from rdkit.Chem.QED import qed # --- Loading report --- await flyte.report.replace.aio( _wrap_report("

Computing Molecular Properties...

" "

Analyzing physicochemical descriptors for all molecules.

"), do_flush=True, ) mol_dir = await molecule_dir.download() with open(os.path.join(mol_dir, "manifest.json")) as f: manifest = json.load(f) molecules_data = [] lipinski_pass = 0 for mol_info in manifest["molecules"]: mol = Chem.MolFromSmiles(mol_info["smiles"]) if mol is None: continue mw = Descriptors.MolWt(mol) logp = Descriptors.MolLogP(mol) hbd = Lipinski.NumHDonors(mol) hba = Lipinski.NumHAcceptors(mol) tpsa = Descriptors.TPSA(mol) rotatable = Lipinski.NumRotatableBonds(mol) formal_charge = Chem.GetFormalCharge(mol) num_rings = Lipinski.RingCount(mol) qed_score = qed(mol) # Lipinski Rule of Five lipinski = { "mw_ok": mw <= 500, "logp_ok": logp <= 5, "hbd_ok": hbd <= 5, "hba_ok": hba <= 10, } lipinski_all = all(lipinski.values()) if lipinski_all: lipinski_pass += 1 # Read image for data URI img_path = os.path.join(mol_dir, mol_info["image_file"]) data_uri = "" if os.path.exists(img_path): with open(img_path, "rb") as img_f: b64 = base64.b64encode(img_f.read()).decode() data_uri = f"data:image/png;base64,{b64}" molecules_data.append({ "name": mol_info["name"], "smiles": mol_info["smiles"], "mw": round(mw, 2), "logp": round(logp, 2), "hbd": hbd, "hba": hba, "tpsa": round(tpsa, 2), "rotatable_bonds": rotatable, "formal_charge": formal_charge, "num_rings": num_rings, "qed": round(qed_score, 4), "lipinski": lipinski, "lipinski_pass": lipinski_all, "image_data_uri": data_uri, }) total = len(molecules_data) avg_mw = sum(m["mw"] for m in molecules_data) / total if total else 0 avg_logp = sum(m["logp"] for m in molecules_data) / total if total else 0 lipinski_rate = lipinski_pass / total * 100 if total else 0 # ---- Build report ---- html_parts = [] # Header html_parts.append("

Molecular Properties Analysis

") # Stat grid html_parts.append('
') for val, label in [ (str(total), "Total Molecules"), (f"{lipinski_rate:.0f}%", "Lipinski Pass Rate"), (f"{avg_mw:.1f}", "Avg. MW (Da)"), (f"{avg_logp:.2f}", "Avg. LogP"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # Molecule gallery html_parts.append("

Molecule Library

") html_parts.append('
') for m in molecules_data: if m["image_data_uri"]: badge_class = "badge-success" if m["lipinski_pass"] else "badge-danger" badge_text = "Lipinski Pass" if m["lipinski_pass"] else "Lipinski Fail" html_parts.append( f'
' f'' f'
{m["name"]}
' f'
MW: {m["mw"]:.1f} | LogP: {m["logp"]:.2f}
' f'
{badge_text}
' f'
' ) html_parts.append("
") # MW bar chart (horizontal, sorted) sorted_by_mw = sorted(molecules_data, key=lambda m: m["mw"], reverse=True) mw_labels = [m["name"] for m in sorted_by_mw] mw_vals = [m["mw"] for m in sorted_by_mw] mw_chart = _make_bar_chart( mw_labels, {"MW (Da)": mw_vals}, title="Molecular Weight Distribution", horizontal=True, width=700, height=max(300, len(mw_labels) * 30 + 80), value_fmt=".1f", ) html_parts.append("

Molecular Weight

") html_parts.append(f'
{mw_chart}
') # LogP vs MW scatter plot scatter_points = [ {"x": m["mw"], "y": m["logp"], "label": m["name"]} for m in molecules_data ] scatter_chart = _make_scatter_plot( scatter_points, x_label="Molecular Weight (Da)", y_label="LogP", title="LogP vs. Molecular Weight (Lipinski Boundaries)", reference_lines=[ {"axis": "x", "value": 500, "label": "MW = 500"}, {"axis": "y", "value": 5, "label": "LogP = 5"}, ], width=700, height=420, ) html_parts.append("

Lipinski Space

") html_parts.append(f'
{scatter_chart}
') # Property heatmap (molecules x properties) prop_names = ["MW", "LogP", "HBD", "HBA", "TPSA", "Rot. Bonds"] # Normalize each property to 0-1 for heatmap raw_matrix = [] for m in molecules_data: raw_matrix.append([m["mw"], m["logp"], m["hbd"], m["hba"], m["tpsa"], m["rotatable_bonds"]]) # Normalize per column n_props = len(prop_names) col_min = [min(row[c] for row in raw_matrix) for c in range(n_props)] col_max = [max(row[c] for row in raw_matrix) for c in range(n_props)] norm_matrix = [] for row in raw_matrix: norm_row = [] for c in range(n_props): rng = col_max[c] - col_min[c] norm_row.append((row[c] - col_min[c]) / rng if rng else 0.5) norm_matrix.append(norm_row) heatmap_labels = [m["name"] for m in molecules_data] heatmap = _make_heatmap( norm_matrix, heatmap_labels, prop_names, title="Normalized Property Heatmap", color_scale="cyan", width=700, height=max(400, len(heatmap_labels) * 28 + 100), ) html_parts.append("

Property Heatmap

") html_parts.append(f'
{heatmap}
') # Lipinski compliance table html_parts.append("

Lipinski Rule of Five Compliance

") html_parts.append("" "" "") for m in molecules_data: lip = m["lipinski"] def _badge(ok): if ok: return 'Pass' return 'Fail' overall_badge = _badge(m["lipinski_pass"]) html_parts.append( f'' f'' f'' f'' f'' f'' ) html_parts.append("
MoleculeMW ≤ 500LogP ≤ 5HBD ≤ 5HBA ≤ 10Overall
{m["name"]}{_badge(lip["mw_ok"])}{_badge(lip["logp_ok"])}{_badge(lip["hbd_ok"])}{_badge(lip["hba_ok"])}{overall_badge}
") # QED bar chart sorted_by_qed = sorted(molecules_data, key=lambda m: m["qed"], reverse=True) qed_labels = [m["name"] for m in sorted_by_qed] qed_vals = [m["qed"] for m in sorted_by_qed] qed_chart = _make_bar_chart( qed_labels, {"QED Score": qed_vals}, title="Drug-likeness (QED Score)", horizontal=True, width=700, height=max(300, len(qed_labels) * 30 + 80), value_fmt=".3f", colors=["#06d6a0"], ) html_parts.append("

Drug-likeness (QED)

") html_parts.append(f'
{qed_chart}
') # Flush full report await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) # Return properties as JSON (strip image data URIs to reduce size) output = { "total": total, "lipinski_pass_count": lipinski_pass, "lipinski_pass_rate": round(lipinski_rate, 2), "avg_mw": round(avg_mw, 2), "avg_logp": round(avg_logp, 2), "molecules": [ {k: v for k, v in m.items() if k != "image_data_uri"} for m in molecules_data ], } return json.dumps(output) # ------------------------------------------------------------------ # Task 3: Screen candidates against target profile # ------------------------------------------------------------------ @tool @env.task(report=True) async def screen_candidates( properties_json: str, target_profile: str = "", ) -> str: """Screen molecules against a target drug profile and rank candidates. Scores each molecule on how well it matches the target profile, computes pairwise Tanimoto similarity, and produces a ranked list. Args: properties_json: JSON from compute_properties. target_profile: JSON string with desired property ranges (e.g. {"mw": [150, 500], "logp": [-0.5, 5.0]}). Returns: JSON string with ranked_molecules, similarity_matrix, similarity_labels, funnel, and target_profile. Pass the full return value verbatim to generate_report along with molecule_dir and properties_json. """ from rdkit import Chem, DataStructs from rdkit.Chem import AllChem await flyte.report.replace.aio( _wrap_report("

Screening Candidates...

" "

Evaluating molecules against the target drug profile.

"), do_flush=True, ) props = json.loads(properties_json) molecules = props["molecules"] # Default target profile if target_profile.strip(): profile = json.loads(target_profile) else: profile = { "mw": [150, 500], "logp": [-0.5, 5.0], "hbd": [0, 5], "hba": [0, 10], "tpsa": [20, 140], } # --- Screening --- funnel_total = len(molecules) pass_mw = 0 pass_logp = 0 pass_lipinski = 0 final_candidates = 0 scored = [] for m in molecules: score = 0 max_score = 0 criteria = {} # Check each profile criterion checks = [ ("mw", m["mw"]), ("logp", m["logp"]), ("hbd", m["hbd"]), ("hba", m["hba"]), ("tpsa", m["tpsa"]), ] for key, val in checks: if key in profile: lo, hi = profile[key] max_score += 1 in_range = lo <= val <= hi criteria[key] = in_range if in_range: score += 1 # Bonus: closer to midpoint = higher score mid = (lo + hi) / 2 rng = (hi - lo) / 2 dist = abs(val - mid) / rng if rng else 0 score += max(0, 0.5 * (1 - dist)) # QED bonus score += m["qed"] * 2 max_score += 2 # Lipinski bonus if m["lipinski_pass"]: score += 1 max_score += 1 normalized_score = score / max_score if max_score else 0 # Funnel tracking โ€” cascading filter (each stage requires passing the previous) mw_ok = criteria.get("mw", True) logp_ok = criteria.get("logp", True) if mw_ok: pass_mw += 1 if logp_ok: pass_logp += 1 if m["lipinski_pass"]: pass_lipinski += 1 if all(criteria.values()): final_candidates += 1 scored.append({ **m, "screening_score": round(normalized_score, 4), "criteria_met": criteria, "all_criteria_met": all(criteria.values()), }) # Sort by score descending scored.sort(key=lambda m: m["screening_score"], reverse=True) # --- Tanimoto similarity matrix --- fps = [] valid_names = [] for m in scored: mol = Chem.MolFromSmiles(m["smiles"]) if mol: fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048) fps.append(fp) valid_names.append(m["name"]) similarity_matrix = [] for i in range(len(fps)): row = [] for j in range(len(fps)): sim = DataStructs.TanimotoSimilarity(fps[i], fps[j]) row.append(round(sim, 3)) similarity_matrix.append(row) # ---- Build report ---- html_parts = [] html_parts.append("

Candidate Screening Results

") # Stat grid html_parts.append('
') for val, label in [ (str(funnel_total), "Total Screened"), (str(pass_lipinski), "Lipinski Passes"), (str(final_candidates), "All Criteria Met"), (f"{scored[0]['screening_score']:.3f}" if scored else "N/A", "Top Score"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # Screening funnel funnel_stages = [ {"label": "Total Molecules", "count": funnel_total, "total": funnel_total}, {"label": "Pass MW Filter", "count": pass_mw, "total": funnel_total}, {"label": "Pass LogP Filter", "count": pass_logp, "total": funnel_total}, {"label": "Lipinski Compliant", "count": pass_lipinski, "total": funnel_total}, {"label": "All Criteria Met", "count": final_candidates, "total": funnel_total}, ] funnel_svg = _make_funnel( funnel_stages, title="Screening Funnel", width=600, height=380, ) html_parts.append("

Screening Funnel

") html_parts.append(f'
{funnel_svg}
') # Ranked candidates table html_parts.append("

Ranked Candidates

") html_parts.append( "" "" ) for rank, m in enumerate(scored, 1): lip_badge = ('Pass' if m["lipinski_pass"] else 'Fail') crit_badge = ('Pass' if m["all_criteria_met"] else 'Fail') # Highlight top 3 row_style = ' style="background:#ecfeff;font-weight:600;"' if rank <= 3 else "" html_parts.append( f"" f"" f"" f"" ) html_parts.append("
RankMoleculeScoreMWLogPQEDLipinskiAll Criteria
{rank}{m['name']}{m['screening_score']:.3f}{m['mw']:.1f}{m['logp']:.2f}{m['qed']:.3f}{lip_badge}{crit_badge}
") # Top 5 candidate cards with structures html_parts.append("

Top 5 Candidates

") html_parts.append('
') for m in scored[:5]: mol = Chem.MolFromSmiles(m["smiles"]) img_uri = _mol_to_data_uri(mol, size=(250, 250)) if mol else "" badge_class = "badge-success" if m["all_criteria_met"] else "badge-info" badge_text = "All Criteria Met" if m["all_criteria_met"] else "Partial Match" html_parts.append( f'
' f'' f'
{m["name"]}
' f'
Score: {m["screening_score"]:.3f}
' f'
MW: {m["mw"]:.1f} | LogP: {m["logp"]:.2f} | QED: {m["qed"]:.3f}
' f'
{badge_text}
' f'
' ) html_parts.append("
") # Tanimoto similarity heatmap if similarity_matrix: sim_heatmap = _make_heatmap( similarity_matrix, valid_names, valid_names, title="Pairwise Tanimoto Similarity (Morgan Fingerprints)", color_scale="cyan", width=700, height=max(500, len(valid_names) * 32 + 100), ) html_parts.append("

Chemical Similarity

") html_parts.append(f'
{sim_heatmap}
') await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) output = { "ranked_molecules": scored, "similarity_matrix": similarity_matrix, "similarity_labels": valid_names, "funnel": funnel_stages, "target_profile": profile, } return json.dumps(output) def _parse_screening_json(screening_json: str) -> dict: """Parse screening JSON from screen_candidates, with safe defaults. The agent must pass the exact tool return value. Partial or hand-built JSON is tolerated for optional similarity fields only. """ screening = json.loads(screening_json) if "ranked_molecules" not in screening: raise ValueError( "screening_json must be the exact JSON string returned by " "screen_candidates (missing 'ranked_molecules'). Do not construct, " "truncate, or summarize tool output." ) screening.setdefault("similarity_matrix", []) screening.setdefault("similarity_labels", []) return screening # ------------------------------------------------------------------ # Task 4: Generate final comprehensive report # ------------------------------------------------------------------ @tool @env.task(report=True) async def generate_report( molecule_dir: flyte.io.Dir, properties_json: str, screening_json: str, ) -> str: """Generate a comprehensive drug screening report. Produces an executive summary, top candidate spotlight cards, property distributions, chemical diversity analysis, and final recommendation. Args: molecule_dir: Directory from load_molecules. properties_json: JSON from compute_properties. screening_json: Exact verbatim JSON string returned by screen_candidates (must include ranked_molecules, similarity_matrix, similarity_labels). Do not construct or summarize this payload yourself. Returns: JSON summary with total_screened, lipinski_passes, all_criteria_met, top_candidate, top_score, and top_3 ranked molecules. """ from rdkit import Chem await flyte.report.replace.aio( _wrap_report("

Generating Final Report...

"), do_flush=True, ) props = json.loads(properties_json) screening = _parse_screening_json(screening_json) ranked = screening["ranked_molecules"] sim_matrix = screening["similarity_matrix"] sim_labels = screening["similarity_labels"] total = props["total"] lipinski_pass = props["lipinski_pass_count"] all_criteria = sum(1 for m in ranked if m["all_criteria_met"]) top = ranked[0] if ranked else None html_parts = [] # --- Executive Summary --- html_parts.append("

Drug Molecule Screening Report

") top_name = top["name"] if top else "N/A" top_score = f'{top["screening_score"]:.3f}' if top else "N/A" html_parts.append( f'
' f'

Executive Summary

' f'

' f'{total} molecules were screened against the target drug profile. ' f'{lipinski_pass} passed Lipinski\'s Rule of Five, and ' f'{all_criteria} met all screening criteria. ' f'The top candidate is {top_name} ' f'with a screening score of {top_score}.

' f'
' ) # Stat grid html_parts.append('
') for val, label in [ (str(total), "Molecules Screened"), (str(lipinski_pass), "Lipinski Passes"), (str(all_criteria), "All Criteria Met"), (top_score, "Top Score"), (f'{props["avg_mw"]:.0f} Da', "Avg. Molecular Weight"), (f'{props["avg_logp"]:.2f}', "Avg. LogP"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # --- Top 3 Candidate Spotlights --- html_parts.append("

Top Candidate Spotlights

") for rank, m in enumerate(ranked[:3], 1): mol = Chem.MolFromSmiles(m["smiles"]) img_uri = _mol_to_data_uri(mol, size=(300, 300)) if mol else "" medal = ["gold", "silver", "#cd7f32"][rank - 1] medal_emoji = ["1st", "2nd", "3rd"][rank - 1] lip_badges = "" for rule, key in [("MW", "mw_ok"), ("LogP", "logp_ok"), ("HBD", "hbd_ok"), ("HBA", "hba_ok")]: ok = m["lipinski"].get(key, False) cls = "badge-success" if ok else "badge-danger" lip_badges += f'{rule} ' html_parts.append( f'
' f'
' f'
{medal_emoji}
' f'' f'
{m["name"]}
' f'
' f'
' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'
SMILES{m["smiles"]}
Screening Score{m["screening_score"]:.3f}
Molecular Weight{m["mw"]:.1f} Da
LogP{m["logp"]:.2f}
H-Bond Donors{m["hbd"]}
H-Bond Acceptors{m["hba"]}
TPSA{m["tpsa"]:.1f} A²
Rotatable Bonds{m["rotatable_bonds"]}
QED{m["qed"]:.4f}
Lipinski Compliance{lip_badges}
' f'
' f'
' ) # --- Property Distribution (box-plot style as bars with min/max/median) --- html_parts.append("

Property Distributions

") prop_keys = [("mw", "Molecular Weight (Da)"), ("logp", "LogP"), ("tpsa", "TPSA"), ("qed", "QED Score")] for key, label in prop_keys: vals = sorted([m[key] for m in ranked]) n = len(vals) if n == 0: continue v_min = vals[0] v_max = vals[-1] median = vals[n // 2] if n % 2 == 1 else (vals[n // 2 - 1] + vals[n // 2]) / 2 q1 = vals[n // 4] if n >= 4 else v_min q3 = vals[3 * n // 4] if n >= 4 else v_max # Simple horizontal box-plot as SVG box_w = 500 box_h = 50 margin_l = 10 v_range = v_max - v_min or 1 def sx(v): return margin_l + ((v - v_min) / v_range) * (box_w - 2 * margin_l) box_svg = ( f'' f'' # Whisker line f'' # Min whisker f'' # Max whisker f'' # IQR box f'' # Median line f'' # Labels f'{v_min:.1f}' f'{median:.1f}' f'{v_max:.1f}' f'' ) html_parts.append( f'
{label}' f'
{box_svg}
' ) # --- Chemical Diversity --- html_parts.append("

Chemical Diversity Analysis

") if sim_matrix and len(sim_matrix) > 1: # Compute average pairwise similarity (off-diagonal) n_mols = len(sim_matrix) off_diag = [] for i in range(n_mols): for j in range(i + 1, n_mols): off_diag.append(sim_matrix[i][j]) avg_sim = sum(off_diag) / len(off_diag) if off_diag else 0 max_sim = max(off_diag) if off_diag else 0 min_sim = min(off_diag) if off_diag else 0 # Find most similar pair best_i, best_j = 0, 1 best_val = 0 for i in range(n_mols): for j in range(i + 1, n_mols): if sim_matrix[i][j] > best_val: best_val = sim_matrix[i][j] best_i, best_j = i, j html_parts.append('
') html_parts.append( f'
{avg_sim:.3f}
' f'
Avg. Pairwise Similarity
' ) html_parts.append( f'
{min_sim:.3f}
' f'
Min Similarity
' ) html_parts.append( f'
{max_sim:.3f}
' f'
Max Similarity
' ) html_parts.append("
") diversity_text = "highly diverse" if avg_sim < 0.3 else "moderately diverse" if avg_sim < 0.5 else "relatively similar" html_parts.append( f'
' f'The library is {diversity_text} (avg. Tanimoto = {avg_sim:.3f}). ' f'The most similar pair is {sim_labels[best_i]} and ' f'{sim_labels[best_j]} (similarity = {best_val:.3f}).
' ) # --- Recommendation --- html_parts.append("

Recommendation

") if top: html_parts.append( f'
' f'

Top Candidate: {top["name"]}

' f'

Based on the virtual screening analysis, {top["name"]} ' f'achieved the highest composite screening score of {top["screening_score"]:.3f}. ' ) reasons = [] if top["lipinski_pass"]: reasons.append("full Lipinski Rule of Five compliance") if top["qed"] > 0.5: reasons.append(f"high drug-likeness (QED = {top['qed']:.3f})") if top.get("all_criteria_met"): reasons.append("all target profile criteria met") if top["mw"] <= 500: reasons.append(f"favorable molecular weight ({top['mw']:.1f} Da)") if reasons: html_parts.append( f'This candidate stands out due to: {", ".join(reasons)}.

' ) else: html_parts.append("

") # Runner-up mentions if len(ranked) >= 2: html_parts.append( f'

Runner-up candidates: ' ) runners = [] for m in ranked[1:4]: runners.append(f'{m["name"]} (score: {m["screening_score"]:.3f})') html_parts.append(", ".join(runners) + ".

") html_parts.append("
") # Final note html_parts.append( '
' "This is a virtual screening analysis. All candidates should undergo " "further computational validation (molecular dynamics, docking) and " "experimental testing before advancing to clinical trials.
" ) await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) # JSON summary summary = { "total_screened": total, "lipinski_passes": lipinski_pass, "all_criteria_met": all_criteria, "top_candidate": top["name"] if top else None, "top_score": top["screening_score"] if top else None, "top_3": [ {"name": m["name"], "score": m["screening_score"]} for m in ranked[:3] ], } return json.dumps(summary) # ------------------------------------------------------------------ # Agent # ------------------------------------------------------------------ # {{docs-fragment agent}} SCREENING_AGENT_INSTRUCTIONS = """\ You are a medicinal chemistry screening strategist. You orchestrate a virtual \ screening pipeline using durable Flyte tools. You NEVER invent molecular \ properties โ€” only RDKit tools compute them. Workflow: 1. If target_profile is not provided in the user message, derive a JSON \ target_profile from the therapeutic brief. Valid keys: mw, logp, hbd, hba, tpsa \ (each [min, max]). Ground choices in oral bioavailability / kinase / CNS rules \ as appropriate to the brief. 2. First pass (always): load_molecules โ†’ compute_properties โ†’ \ screen_candidates โ†’ generate_report. Pass tool outputs between steps exactly \ (molecule_dir from load_molecules into compute_properties and generate_report; \ properties_json from compute_properties into screen_candidates and \ generate_report; screening_json must be the complete, unmodified string \ returned by screen_candidates โ€” never rebuild or summarize JSON yourself). 3. Read the JSON summary returned by generate_report. Reflect: - If all_criteria_met == 0: relax exactly ONE profile bound by ~10โ€“20% \ and re-run screen_candidates then generate_report only, reusing the same \ molecule_dir and properties_json from the first pass. - If all molecules pass but diversity is a stated goal: note high similarity \ in your summary; do not re-run unless brief asks for stricter filters. - Maximum ONE rescreen iteration. 4. Finish with plain text: top candidate, rationale tied to computed metrics \ from the tool JSON, funnel interpretation, and suggested next steps (docking, \ ADMET lab tests). If the user supplies an explicit target_profile JSON, use it as-is. Do NOT ask the user for SMILES or molecule lists when molecules_json is empty โ€” \ the default library is loaded automatically. """ screening_agent = Agent( name="drug-screening-agent", instructions=SCREENING_AGENT_INSTRUCTIONS, model=MODEL, tools=[ load_molecules, compute_properties, screen_candidates, generate_report, ], max_turns=12, ) # {{/docs-fragment agent}} # ------------------------------------------------------------------ # Pipeline # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @env.task(report=True) async def pipeline( brief: str = "Screen the default drug library for orally bioavailable small molecules.", molecules_json: str = "", target_profile: str = "", ) -> str: """Agentic virtual drug molecule screening pipeline. A medicinal-chemistry agent interprets the screening brief, derives or applies a target profile, orchestrates the RDKit screening stages, and optionally re-screens when funnel results are too narrow. Args: brief: Natural-language therapeutic goal (e.g. oral kinase inhibitors, CNS-penetrant small molecules). molecules_json: JSON mapping molecule names to SMILES strings. Defaults to a curated library of ~15 well-known drugs. target_profile: Optional JSON with desired property ranges that overrides agent-derived criteria (e.g. {"mw": [150, 500], "logp": [-0.5, 5]}). Returns: Agent summary with screening rationale and key results. """ prompt_parts = [ f"Screening brief: {brief}", 'Use molecules_json="" for the built-in default library unless provided below.', "Compose the four stage tools in order: load_molecules โ†’ compute_properties " "โ†’ screen_candidates โ†’ generate_report. Pass each tool's full return value " "verbatim to the next step (especially screening_json). Re-run " "screen_candidates and generate_report at most once if the funnel is too narrow.", ] if molecules_json.strip(): prompt_parts.append(f"molecules_json: {molecules_json}") if target_profile.strip(): prompt_parts.append(f"Use this target_profile exactly: {target_profile}") result = await screening_agent.run.aio("\n".join(prompt_parts)) return result.summary or result.error or "" # {{/docs-fragment pipeline}} # ------------------------------------------------------------------ # Rescreen demo โ€” tight profile + explicit rescreen instructions # ------------------------------------------------------------------ # Initial profile is deliberately strict (narrow MW + low LogP cap) so # all_criteria_met is typically 0 on the default library; the brief then # forces a single rescreen with a widened LogP window. RESCREEN_DEMO_TARGET_PROFILE = ( '{"mw": [150, 200], "logp": [-0.5, 1.0], "hbd": [0, 1], ' '"hba": [0, 3], "tpsa": [20, 45]}' ) RESCREEN_DEMO_TARGET_PROFILE_RESCREEN = ( '{"mw": [150, 200], "logp": [-0.5, 3.5], "hbd": [0, 1], ' '"hba": [0, 3], "tpsa": [20, 45]}' ) RESCREEN_DEMO_BRIEF = f"""\ Two-round agentic screening demo on the default library. **Round 1 (strict profile):** load_molecules โ†’ compute_properties โ†’ \ screen_candidates โ†’ generate_report using the initial target_profile exactly. **Round 2 (required โ€” do not skip):** call screen_candidates then generate_report \ again, reusing the same molecule_dir and properties_json from round 1, with this \ relaxed target_profile (wider LogP window only): \ {RESCREEN_DEMO_TARGET_PROFILE_RESCREEN} Pass every tool return value verbatim to the next step. After both rounds, \ summarize how the funnel and top candidates changed between round 1 and round 2.""" # {{docs-fragment rescreen_demo}} @env.task(report=True) async def rescreen_demo() -> str: """Example run with a two-round execution graph (rescreen). Round 1 uses a strict CNS-like profile; round 2 always re-runs screen_candidates and generate_report with a widened LogP window, reusing cached molecule_dir and properties_json. """ return await pipeline( brief=RESCREEN_DEMO_BRIEF, target_profile=RESCREEN_DEMO_TARGET_PROFILE, ) # {{/docs-fragment rescreen_demo}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/drug_molecule_screening/drug_molecule_screening.py* ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.5.4", # "litellm", # "rdkit", # "numpy", # "scikit-learn", # "pillow", # ] # /// ``` ## Define the screening agent The agent receives a natural-language brief and composes four stage tools in order. Each tool is a durable Flyte task. `compute_properties`, `screen_candidates`, and `generate_report` each declare `report=True` and have their own report in the Flyte UI. `load_molecules` is a cached task without a report. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.5.4", # "litellm", # "rdkit", # "numpy", # "scikit-learn", # "pillow", # ] # main = "pipeline" # params = "" # /// """Virtual drug molecule screening โ€” compute properties, apply Lipinski filters, rank candidates.""" import base64 import io import json import logging import math import os import tempfile import flyte import flyte.io import flyte.report from flyte.ai.agents import Agent, tool MODEL = os.getenv("DRUG_SCREENING_MODEL", "claude-haiku-4-5") # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="drug-molecule-screening", pre=True).with_apt_packages( "libxrender1", "libxext6", "libexpat1", ) env = flyte.TaskEnvironment( name="drug-molecule-screening", image=main_img, resources=flyte.Resources(cpu=2, memory="6Gi"), secrets=[ flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Default molecule library โ€” real SMILES for well-known drugs # ------------------------------------------------------------------ DEFAULT_MOLECULES = { "Aspirin": "CC(=O)OC1=CC=CC=C1C(=O)O", "Ibuprofen": "CC(C)CC1=CC=C(C=C1)C(C)C(=O)O", "Caffeine": "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", "Penicillin G": "CC1(C(N2C(S1)C(C2=O)NC(=O)CC3=CC=CC=C3)C(=O)O)C", "Metformin": "CN(C)C(=N)NC(=N)N", "Paracetamol": "CC(=O)NC1=CC=C(C=C1)O", "Diazepam": "ClC1=CC2=C(C=C1)N(C(=O)CN=C2C3=CC=CC=C3)C", "Omeprazole": "CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=CC=CC=C3N2", "Atorvastatin": "CC(C)C1=C(C(=C(N1CCC(CC(CC(=O)O)O)O)C2=CC=C(C=C2)F)C3=CC=CC=C3)C(=O)NC4=CC=CC=C4", "Methotrexate": "CN(CC1=CN=C2N=C(N=C(N)C2=N1)N)C3=CC=C(C=C3)C(=O)NC(CCC(=O)O)C(=O)O", "Doxorubicin": "CC1C(C(CC(O1)OC2CC(CC3=C2C(=C4C(=C3O)C(=O)C5=C(C4=O)C(=CC=C5)OC)O)(C(=O)CO)O)N)O", "Tamoxifen": "CCC(=C(C1=CC=CC=C1)C2=CC=C(C=C2)OCCN(C)C)C3=CC=CC=C3", "Lopinavir": "CC1=C(C(=CC=C1)C)OCC(=O)NC(CC2=CC=CC=C2)C(CC(CC3=CC=CC=C3)NC(=O)C(C(C)C)N4CCCNC4=O)O", "Remdesivir": "CCC(CC)COC(=O)C(C)NP(=O)(OCC1C(C(C(O1)C2=CC=C3N2N=CN=C3N)O)O)OC4=CC=CC=C4", "Erlotinib": "COCCOC1=CC2=C(C=C1OCCOC)C(=NC=N2)NC3=CC=CC(=C3)C#C", } # ------------------------------------------------------------------ # Report styling โ€” pharma blue/cyan theme # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: """Wrap HTML content with report styling.""" return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers # ------------------------------------------------------------------ def _mol_to_data_uri(mol, size: tuple[int, int] = (300, 300)) -> str: """Convert an RDKit molecule to a PNG base64 data URI.""" from rdkit.Chem import Draw img = Draw.MolToImage(mol, size=size) buf = io.BytesIO() img.save(buf, format="PNG") b64 = base64.b64encode(buf.getvalue()).decode() return f"data:image/png;base64,{b64}" def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 340, y_max_cap: float | None = None, horizontal: bool = False, value_fmt: str = ".1f", ) -> str: """Generate an SVG grouped bar chart. Args: labels: Category labels. series: Dict mapping series name to list of values. title: Chart title. colors: Colors for each series. width/height: SVG dimensions. y_max_cap: Cap the y-axis at this value. horizontal: If True, draw horizontal bars. value_fmt: Format string for value labels. Returns: SVG string. """ if not labels: return "" default_colors = ["#0891b2", "#0e4f6e", "#06d6a0", "#a5f3fc", "#155e75"] colors = colors or default_colors if horizontal: return _make_horizontal_bar_chart(labels, series, title, colors, width, height, value_fmt) ml, mr, mt, mb = 60, 20, 40, 60 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_max = max(all_vals) if all_vals else 1 y_max_plot = y_max * 1.15 or 1 if y_max_cap is not None: y_max_plot = min(y_max_plot, y_max_cap) or y_max_cap n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - (v / y_max_plot) * ch svg = [ f'', f'', ] # Grid lines for i in range(6): y_tick = y_max_plot * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:{value_fmt}}' ) # Axes svg.append( f'' ) svg.append( f'' ) # Bars for gi, label in enumerate(labels): gx = ml + gi * group_width + gap for si, (name, vals) in enumerate(series.items()): color = colors[si % len(colors)] bx = gx + si * bar_width val = vals[gi] by = sy(val) bh = mt + ch - by svg.append( f'' ) svg.append( f'' f'{val:{value_fmt}}' ) # Truncate long labels disp_label = label if len(label) <= 12 else label[:10] + ".." svg.append( f'' f'{disp_label}' ) # Title if title: svg.append( f'{title}' ) # Legend if n_series > 1: lx = ml + cw - len(series) * 100 for si, name in enumerate(series): color = colors[si % len(colors)] svg.append( f'' ) svg.append( f'{name}' ) svg.append("") return "\n".join(svg) def _make_horizontal_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 400, value_fmt: str = ".1f", ) -> str: """Generate an SVG horizontal bar chart (sorted).""" default_colors = ["#0891b2", "#0e4f6e", "#06d6a0"] colors = colors or default_colors n = len(labels) row_height = max(22, min(35, (height - 80) // max(n, 1))) actual_height = max(height, 80 + n * row_height) ml, mr, mt, mb = 120, 60, 40, 20 cw = width - ml - mr ch = actual_height - mt - mb # Use first series first_key = list(series.keys())[0] vals = series[first_key] x_max = max(vals) * 1.15 if vals else 1 svg = [ f'', f'', ] if title: svg.append( f'{title}' ) bar_h = row_height * 0.65 for i, (label, val) in enumerate(zip(labels, vals)): y = mt + i * row_height bw = (val / x_max) * cw if x_max else 0 color = colors[i % len(colors)] # Label disp = label if len(label) <= 14 else label[:12] + ".." svg.append( f'{disp}' ) # Bar svg.append( f'' ) # Value svg.append( f'{val:{value_fmt}}' ) svg.append("") return "\n".join(svg) def _make_heatmap( matrix: list[list[float]], row_labels: list[str], col_labels: list[str], title: str = "", color_scale: str = "cyan", width: int = 700, height: int = 500, value_fmt: str = ".2f", ) -> str: """Generate an SVG heatmap. Args: matrix: 2D list of values (rows x cols). row_labels: Labels for rows. col_labels: Labels for columns. title: Chart title. color_scale: Color scheme ("cyan", "red", "green"). width/height: SVG dimensions. value_fmt: Format string for cell values. Returns: SVG string. """ if not matrix or not matrix[0]: return "" n_rows = len(matrix) n_cols = len(matrix[0]) ml, mr, mt, mb = 110, 20, 70, 20 cw = width - ml - mr ch = height - mt - mb cell_w = cw / n_cols cell_h = ch / n_rows # Flatten to find range flat = [v for row in matrix for v in row] v_min = min(flat) v_max = max(flat) v_range = v_max - v_min or 1 def color_for(v): t = (v - v_min) / v_range if color_scale == "cyan": # White to deep teal r = int(255 - t * (255 - 14)) g = int(255 - t * (255 - 79)) b = int(255 - t * (255 - 110)) elif color_scale == "red": r = int(255 - t * 50) g = int(255 - t * 200) b = int(255 - t * 200) else: # green r = int(255 - t * 200) g = int(255 - t * 50) b = int(255 - t * 200) return f"rgb({r},{g},{b})" svg = [ f'', f'', ] if title: svg.append( f'{title}' ) # Column labels (rotated) for ci, label in enumerate(col_labels): x = ml + ci * cell_w + cell_w / 2 disp = label if len(label) <= 12 else label[:10] + ".." svg.append( f'{disp}' ) # Row labels + cells for ri, (row_label, row_vals) in enumerate(zip(row_labels, matrix)): y = mt + ri * cell_h disp = row_label if len(row_label) <= 14 else row_label[:12] + ".." svg.append( f'{disp}' ) for ci, val in enumerate(row_vals): x = ml + ci * cell_w fill = color_for(val) svg.append( f'' ) # Text color: dark on light, light on dark t = (val - v_min) / v_range txt_color = "#fff" if t > 0.55 else "#1a1a2e" # Only show text if cells are large enough if cell_w > 30 and cell_h > 18: svg.append( f'' f'{val:{value_fmt}}' ) svg.append("") return "\n".join(svg) def _make_scatter_plot( points: list[dict], x_label: str = "MW", y_label: str = "LogP", title: str = "", reference_lines: list[dict] | None = None, width: int = 700, height: int = 400, ) -> str: """Generate an SVG scatter plot. Args: points: List of dicts with "x", "y", "label" keys. x_label/y_label: Axis labels. title: Chart title. reference_lines: List of dicts with "axis" ("x"/"y"), "value", "label". width/height: SVG dimensions. Returns: SVG string. """ if not points: return "" ml, mr, mt, mb = 60, 30, 40, 50 cw = width - ml - mr ch = height - mt - mb x_vals = [p["x"] for p in points] y_vals = [p["y"] for p in points] x_min, x_max = min(x_vals) * 0.9, max(x_vals) * 1.1 y_min, y_max = min(y_vals) - 1, max(y_vals) + 1 # Extend ranges to include reference lines if reference_lines: for rl in reference_lines: if rl["axis"] == "x": x_max = max(x_max, rl["value"] * 1.1) else: y_max = max(y_max, rl["value"] * 1.1) x_range = x_max - x_min or 1 y_range = y_max - y_min or 1 def sx(v): return ml + (v - x_min) / x_range * cw def sy(v): return mt + ch - (v - y_min) / y_range * ch svg = [ f'', f'', ] # Grid for i in range(6): y_tick = y_min + y_range * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:.1f}' ) for i in range(6): x_tick = x_min + x_range * i / 5 px = sx(x_tick) svg.append( f'{x_tick:.0f}' ) # Axes svg.append( f'' ) svg.append( f'' ) # Reference lines (Lipinski boundaries) if reference_lines: for rl in reference_lines: if rl["axis"] == "x": px = sx(rl["value"]) svg.append( f'' ) svg.append( f'{rl["label"]}' ) else: py = sy(rl["value"]) svg.append( f'' ) svg.append( f'{rl["label"]}' ) # Drug-like zone shading (MW<=500 and LogP<=5 quadrant) if reference_lines: mw_line = next((rl for rl in reference_lines if rl["axis"] == "x"), None) logp_line = next((rl for rl in reference_lines if rl["axis"] == "y"), None) if mw_line and logp_line: zx1 = sx(x_min) zx2 = sx(min(mw_line["value"], x_max)) zy1 = sy(min(logp_line["value"], y_max)) zy2 = sy(y_min) svg.append( f'' ) svg.append( f'Drug-like Zone' ) # Points point_colors = ["#0891b2", "#0e4f6e", "#06d6a0", "#155e75", "#0284c7", "#059669", "#0d9488", "#0369a1", "#047857", "#115e59", "#0c4a6e", "#064e3b", "#1e3a5f", "#134e4a", "#075985"] for i, pt in enumerate(points): px, py = sx(pt["x"]), sy(pt["y"]) color = point_colors[i % len(point_colors)] svg.append( f'' ) # Label offset to avoid overlap offset_x = 8 offset_y = -8 if i % 2 == 0 else 14 label = pt["label"] if len(pt["label"]) <= 12 else pt["label"][:10] + ".." svg.append( f'{label}' ) # Title if title: svg.append( f'{title}' ) # Axis labels if x_label: svg.append( f'{x_label}' ) if y_label: svg.append( f'{y_label}' ) svg.append("") return "\n".join(svg) def _make_funnel( stages: list[dict], title: str = "", width: int = 600, height: int = 400, ) -> str: """Generate an SVG funnel visualization. Args: stages: List of dicts with "label", "count", "total" keys. title: Chart title. width/height: SVG dimensions. Returns: SVG string. """ if not stages: return "" n = len(stages) mt = 50 mb = 20 available_h = height - mt - mb stage_h = available_h / n cx = width / 2 # Color gradient from light cyan to deep teal colors = [] for i in range(n): t = i / max(n - 1, 1) r = int(207 - t * (207 - 14)) g = int(250 - t * (250 - 79)) b = int(254 - t * (254 - 110)) colors.append(f"rgb({r},{g},{b})") svg = [ f'', f'', ] if title: svg.append( f'{title}' ) max_count = stages[0]["count"] if stages else 1 max_width = width * 0.75 for i, stage in enumerate(stages): y_top = mt + i * stage_h y_bot = y_top + stage_h # Width proportional to count w_top = max_width * (stage["count"] / max_count) if i == 0 else prev_w_bot if i < n - 1: w_bot = max_width * (stages[i + 1]["count"] / max_count) else: w_bot = max_width * (stage["count"] / max_count) * 0.7 prev_w_bot = w_bot # Trapezoid x1_top = cx - w_top / 2 x2_top = cx + w_top / 2 x1_bot = cx - w_bot / 2 x2_bot = cx + w_bot / 2 svg.append( f'' ) # Text: dark on light, white on dark t = i / max(n - 1, 1) txt_color = "#0e4f6e" if t < 0.5 else "#fff" y_mid = (y_top + y_bot) / 2 svg.append( f'{stage["label"]}' ) svg.append( f'' f'{stage["count"]} / {stage["total"]}' ) svg.append("") return "\n".join(svg) # ------------------------------------------------------------------ # Task 1: Load and validate molecules # ------------------------------------------------------------------ @tool @env.task(cache="auto") async def load_molecules( molecules_json: str = "", ) -> flyte.io.Dir: """Parse SMILES strings, validate with RDKit, generate 2D depictions. Args: molecules_json: JSON string mapping molecule names to SMILES. Defaults to a curated library of ~15 well-known drugs. Returns: flyte.io.Dir containing molecule data (JSON + PNG depictions). Pass this directory to compute_properties and generate_report. """ from rdkit import Chem from rdkit.Chem import Draw if molecules_json.strip(): molecules = json.loads(molecules_json) else: molecules = DEFAULT_MOLECULES out_dir = tempfile.mkdtemp(prefix="mol_library_") results = [] valid_count = 0 invalid_count = 0 log.info(f"Parsing {len(molecules)} molecules...") for name, smiles in molecules.items(): mol = Chem.MolFromSmiles(smiles) if mol is None: log.warning(f" [INVALID] {name}: {smiles}") invalid_count += 1 continue valid_count += 1 # Generate 2D depiction as PNG img = Draw.MolToImage(mol, size=(300, 300)) img_path = os.path.join(out_dir, f"{name.replace(' ', '_')}.png") img.save(img_path) results.append({ "name": name, "smiles": smiles, "valid": True, "image_file": os.path.basename(img_path), }) # Save molecule manifest manifest = { "total": len(molecules), "valid": valid_count, "invalid": invalid_count, "molecules": results, } manifest_path = os.path.join(out_dir, "manifest.json") with open(manifest_path, "w") as f: json.dump(manifest, f, indent=2) log.info(f"Loaded {valid_count} valid molecules ({invalid_count} invalid)") return await flyte.io.Dir.from_local(out_dir) # ------------------------------------------------------------------ # Task 2: Compute physicochemical properties # ------------------------------------------------------------------ @tool @env.task(report=True) async def compute_properties( molecule_dir: flyte.io.Dir, ) -> str: """Compute drug-likeness properties for all molecules. Computes MW, LogP, HBD, HBA, TPSA, rotatable bonds, formal charge, ring count, QED, and Lipinski Rule of Five compliance. Args: molecule_dir: Directory from load_molecules. Returns: JSON string with all computed properties. Pass to screen_candidates and generate_report. """ from rdkit import Chem from rdkit.Chem import Descriptors, Lipinski from rdkit.Chem.QED import qed # --- Loading report --- await flyte.report.replace.aio( _wrap_report("

Computing Molecular Properties...

" "

Analyzing physicochemical descriptors for all molecules.

"), do_flush=True, ) mol_dir = await molecule_dir.download() with open(os.path.join(mol_dir, "manifest.json")) as f: manifest = json.load(f) molecules_data = [] lipinski_pass = 0 for mol_info in manifest["molecules"]: mol = Chem.MolFromSmiles(mol_info["smiles"]) if mol is None: continue mw = Descriptors.MolWt(mol) logp = Descriptors.MolLogP(mol) hbd = Lipinski.NumHDonors(mol) hba = Lipinski.NumHAcceptors(mol) tpsa = Descriptors.TPSA(mol) rotatable = Lipinski.NumRotatableBonds(mol) formal_charge = Chem.GetFormalCharge(mol) num_rings = Lipinski.RingCount(mol) qed_score = qed(mol) # Lipinski Rule of Five lipinski = { "mw_ok": mw <= 500, "logp_ok": logp <= 5, "hbd_ok": hbd <= 5, "hba_ok": hba <= 10, } lipinski_all = all(lipinski.values()) if lipinski_all: lipinski_pass += 1 # Read image for data URI img_path = os.path.join(mol_dir, mol_info["image_file"]) data_uri = "" if os.path.exists(img_path): with open(img_path, "rb") as img_f: b64 = base64.b64encode(img_f.read()).decode() data_uri = f"data:image/png;base64,{b64}" molecules_data.append({ "name": mol_info["name"], "smiles": mol_info["smiles"], "mw": round(mw, 2), "logp": round(logp, 2), "hbd": hbd, "hba": hba, "tpsa": round(tpsa, 2), "rotatable_bonds": rotatable, "formal_charge": formal_charge, "num_rings": num_rings, "qed": round(qed_score, 4), "lipinski": lipinski, "lipinski_pass": lipinski_all, "image_data_uri": data_uri, }) total = len(molecules_data) avg_mw = sum(m["mw"] for m in molecules_data) / total if total else 0 avg_logp = sum(m["logp"] for m in molecules_data) / total if total else 0 lipinski_rate = lipinski_pass / total * 100 if total else 0 # ---- Build report ---- html_parts = [] # Header html_parts.append("

Molecular Properties Analysis

") # Stat grid html_parts.append('
') for val, label in [ (str(total), "Total Molecules"), (f"{lipinski_rate:.0f}%", "Lipinski Pass Rate"), (f"{avg_mw:.1f}", "Avg. MW (Da)"), (f"{avg_logp:.2f}", "Avg. LogP"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # Molecule gallery html_parts.append("

Molecule Library

") html_parts.append('
') for m in molecules_data: if m["image_data_uri"]: badge_class = "badge-success" if m["lipinski_pass"] else "badge-danger" badge_text = "Lipinski Pass" if m["lipinski_pass"] else "Lipinski Fail" html_parts.append( f'
' f'' f'
{m["name"]}
' f'
MW: {m["mw"]:.1f} | LogP: {m["logp"]:.2f}
' f'
{badge_text}
' f'
' ) html_parts.append("
") # MW bar chart (horizontal, sorted) sorted_by_mw = sorted(molecules_data, key=lambda m: m["mw"], reverse=True) mw_labels = [m["name"] for m in sorted_by_mw] mw_vals = [m["mw"] for m in sorted_by_mw] mw_chart = _make_bar_chart( mw_labels, {"MW (Da)": mw_vals}, title="Molecular Weight Distribution", horizontal=True, width=700, height=max(300, len(mw_labels) * 30 + 80), value_fmt=".1f", ) html_parts.append("

Molecular Weight

") html_parts.append(f'
{mw_chart}
') # LogP vs MW scatter plot scatter_points = [ {"x": m["mw"], "y": m["logp"], "label": m["name"]} for m in molecules_data ] scatter_chart = _make_scatter_plot( scatter_points, x_label="Molecular Weight (Da)", y_label="LogP", title="LogP vs. Molecular Weight (Lipinski Boundaries)", reference_lines=[ {"axis": "x", "value": 500, "label": "MW = 500"}, {"axis": "y", "value": 5, "label": "LogP = 5"}, ], width=700, height=420, ) html_parts.append("

Lipinski Space

") html_parts.append(f'
{scatter_chart}
') # Property heatmap (molecules x properties) prop_names = ["MW", "LogP", "HBD", "HBA", "TPSA", "Rot. Bonds"] # Normalize each property to 0-1 for heatmap raw_matrix = [] for m in molecules_data: raw_matrix.append([m["mw"], m["logp"], m["hbd"], m["hba"], m["tpsa"], m["rotatable_bonds"]]) # Normalize per column n_props = len(prop_names) col_min = [min(row[c] for row in raw_matrix) for c in range(n_props)] col_max = [max(row[c] for row in raw_matrix) for c in range(n_props)] norm_matrix = [] for row in raw_matrix: norm_row = [] for c in range(n_props): rng = col_max[c] - col_min[c] norm_row.append((row[c] - col_min[c]) / rng if rng else 0.5) norm_matrix.append(norm_row) heatmap_labels = [m["name"] for m in molecules_data] heatmap = _make_heatmap( norm_matrix, heatmap_labels, prop_names, title="Normalized Property Heatmap", color_scale="cyan", width=700, height=max(400, len(heatmap_labels) * 28 + 100), ) html_parts.append("

Property Heatmap

") html_parts.append(f'
{heatmap}
') # Lipinski compliance table html_parts.append("

Lipinski Rule of Five Compliance

") html_parts.append("" "" "") for m in molecules_data: lip = m["lipinski"] def _badge(ok): if ok: return 'Pass' return 'Fail' overall_badge = _badge(m["lipinski_pass"]) html_parts.append( f'' f'' f'' f'' f'' f'' ) html_parts.append("
MoleculeMW ≤ 500LogP ≤ 5HBD ≤ 5HBA ≤ 10Overall
{m["name"]}{_badge(lip["mw_ok"])}{_badge(lip["logp_ok"])}{_badge(lip["hbd_ok"])}{_badge(lip["hba_ok"])}{overall_badge}
") # QED bar chart sorted_by_qed = sorted(molecules_data, key=lambda m: m["qed"], reverse=True) qed_labels = [m["name"] for m in sorted_by_qed] qed_vals = [m["qed"] for m in sorted_by_qed] qed_chart = _make_bar_chart( qed_labels, {"QED Score": qed_vals}, title="Drug-likeness (QED Score)", horizontal=True, width=700, height=max(300, len(qed_labels) * 30 + 80), value_fmt=".3f", colors=["#06d6a0"], ) html_parts.append("

Drug-likeness (QED)

") html_parts.append(f'
{qed_chart}
') # Flush full report await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) # Return properties as JSON (strip image data URIs to reduce size) output = { "total": total, "lipinski_pass_count": lipinski_pass, "lipinski_pass_rate": round(lipinski_rate, 2), "avg_mw": round(avg_mw, 2), "avg_logp": round(avg_logp, 2), "molecules": [ {k: v for k, v in m.items() if k != "image_data_uri"} for m in molecules_data ], } return json.dumps(output) # ------------------------------------------------------------------ # Task 3: Screen candidates against target profile # ------------------------------------------------------------------ @tool @env.task(report=True) async def screen_candidates( properties_json: str, target_profile: str = "", ) -> str: """Screen molecules against a target drug profile and rank candidates. Scores each molecule on how well it matches the target profile, computes pairwise Tanimoto similarity, and produces a ranked list. Args: properties_json: JSON from compute_properties. target_profile: JSON string with desired property ranges (e.g. {"mw": [150, 500], "logp": [-0.5, 5.0]}). Returns: JSON string with ranked_molecules, similarity_matrix, similarity_labels, funnel, and target_profile. Pass the full return value verbatim to generate_report along with molecule_dir and properties_json. """ from rdkit import Chem, DataStructs from rdkit.Chem import AllChem await flyte.report.replace.aio( _wrap_report("

Screening Candidates...

" "

Evaluating molecules against the target drug profile.

"), do_flush=True, ) props = json.loads(properties_json) molecules = props["molecules"] # Default target profile if target_profile.strip(): profile = json.loads(target_profile) else: profile = { "mw": [150, 500], "logp": [-0.5, 5.0], "hbd": [0, 5], "hba": [0, 10], "tpsa": [20, 140], } # --- Screening --- funnel_total = len(molecules) pass_mw = 0 pass_logp = 0 pass_lipinski = 0 final_candidates = 0 scored = [] for m in molecules: score = 0 max_score = 0 criteria = {} # Check each profile criterion checks = [ ("mw", m["mw"]), ("logp", m["logp"]), ("hbd", m["hbd"]), ("hba", m["hba"]), ("tpsa", m["tpsa"]), ] for key, val in checks: if key in profile: lo, hi = profile[key] max_score += 1 in_range = lo <= val <= hi criteria[key] = in_range if in_range: score += 1 # Bonus: closer to midpoint = higher score mid = (lo + hi) / 2 rng = (hi - lo) / 2 dist = abs(val - mid) / rng if rng else 0 score += max(0, 0.5 * (1 - dist)) # QED bonus score += m["qed"] * 2 max_score += 2 # Lipinski bonus if m["lipinski_pass"]: score += 1 max_score += 1 normalized_score = score / max_score if max_score else 0 # Funnel tracking โ€” cascading filter (each stage requires passing the previous) mw_ok = criteria.get("mw", True) logp_ok = criteria.get("logp", True) if mw_ok: pass_mw += 1 if logp_ok: pass_logp += 1 if m["lipinski_pass"]: pass_lipinski += 1 if all(criteria.values()): final_candidates += 1 scored.append({ **m, "screening_score": round(normalized_score, 4), "criteria_met": criteria, "all_criteria_met": all(criteria.values()), }) # Sort by score descending scored.sort(key=lambda m: m["screening_score"], reverse=True) # --- Tanimoto similarity matrix --- fps = [] valid_names = [] for m in scored: mol = Chem.MolFromSmiles(m["smiles"]) if mol: fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048) fps.append(fp) valid_names.append(m["name"]) similarity_matrix = [] for i in range(len(fps)): row = [] for j in range(len(fps)): sim = DataStructs.TanimotoSimilarity(fps[i], fps[j]) row.append(round(sim, 3)) similarity_matrix.append(row) # ---- Build report ---- html_parts = [] html_parts.append("

Candidate Screening Results

") # Stat grid html_parts.append('
') for val, label in [ (str(funnel_total), "Total Screened"), (str(pass_lipinski), "Lipinski Passes"), (str(final_candidates), "All Criteria Met"), (f"{scored[0]['screening_score']:.3f}" if scored else "N/A", "Top Score"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # Screening funnel funnel_stages = [ {"label": "Total Molecules", "count": funnel_total, "total": funnel_total}, {"label": "Pass MW Filter", "count": pass_mw, "total": funnel_total}, {"label": "Pass LogP Filter", "count": pass_logp, "total": funnel_total}, {"label": "Lipinski Compliant", "count": pass_lipinski, "total": funnel_total}, {"label": "All Criteria Met", "count": final_candidates, "total": funnel_total}, ] funnel_svg = _make_funnel( funnel_stages, title="Screening Funnel", width=600, height=380, ) html_parts.append("

Screening Funnel

") html_parts.append(f'
{funnel_svg}
') # Ranked candidates table html_parts.append("

Ranked Candidates

") html_parts.append( "" "" ) for rank, m in enumerate(scored, 1): lip_badge = ('Pass' if m["lipinski_pass"] else 'Fail') crit_badge = ('Pass' if m["all_criteria_met"] else 'Fail') # Highlight top 3 row_style = ' style="background:#ecfeff;font-weight:600;"' if rank <= 3 else "" html_parts.append( f"" f"" f"" f"" ) html_parts.append("
RankMoleculeScoreMWLogPQEDLipinskiAll Criteria
{rank}{m['name']}{m['screening_score']:.3f}{m['mw']:.1f}{m['logp']:.2f}{m['qed']:.3f}{lip_badge}{crit_badge}
") # Top 5 candidate cards with structures html_parts.append("

Top 5 Candidates

") html_parts.append('
') for m in scored[:5]: mol = Chem.MolFromSmiles(m["smiles"]) img_uri = _mol_to_data_uri(mol, size=(250, 250)) if mol else "" badge_class = "badge-success" if m["all_criteria_met"] else "badge-info" badge_text = "All Criteria Met" if m["all_criteria_met"] else "Partial Match" html_parts.append( f'
' f'' f'
{m["name"]}
' f'
Score: {m["screening_score"]:.3f}
' f'
MW: {m["mw"]:.1f} | LogP: {m["logp"]:.2f} | QED: {m["qed"]:.3f}
' f'
{badge_text}
' f'
' ) html_parts.append("
") # Tanimoto similarity heatmap if similarity_matrix: sim_heatmap = _make_heatmap( similarity_matrix, valid_names, valid_names, title="Pairwise Tanimoto Similarity (Morgan Fingerprints)", color_scale="cyan", width=700, height=max(500, len(valid_names) * 32 + 100), ) html_parts.append("

Chemical Similarity

") html_parts.append(f'
{sim_heatmap}
') await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) output = { "ranked_molecules": scored, "similarity_matrix": similarity_matrix, "similarity_labels": valid_names, "funnel": funnel_stages, "target_profile": profile, } return json.dumps(output) def _parse_screening_json(screening_json: str) -> dict: """Parse screening JSON from screen_candidates, with safe defaults. The agent must pass the exact tool return value. Partial or hand-built JSON is tolerated for optional similarity fields only. """ screening = json.loads(screening_json) if "ranked_molecules" not in screening: raise ValueError( "screening_json must be the exact JSON string returned by " "screen_candidates (missing 'ranked_molecules'). Do not construct, " "truncate, or summarize tool output." ) screening.setdefault("similarity_matrix", []) screening.setdefault("similarity_labels", []) return screening # ------------------------------------------------------------------ # Task 4: Generate final comprehensive report # ------------------------------------------------------------------ @tool @env.task(report=True) async def generate_report( molecule_dir: flyte.io.Dir, properties_json: str, screening_json: str, ) -> str: """Generate a comprehensive drug screening report. Produces an executive summary, top candidate spotlight cards, property distributions, chemical diversity analysis, and final recommendation. Args: molecule_dir: Directory from load_molecules. properties_json: JSON from compute_properties. screening_json: Exact verbatim JSON string returned by screen_candidates (must include ranked_molecules, similarity_matrix, similarity_labels). Do not construct or summarize this payload yourself. Returns: JSON summary with total_screened, lipinski_passes, all_criteria_met, top_candidate, top_score, and top_3 ranked molecules. """ from rdkit import Chem await flyte.report.replace.aio( _wrap_report("

Generating Final Report...

"), do_flush=True, ) props = json.loads(properties_json) screening = _parse_screening_json(screening_json) ranked = screening["ranked_molecules"] sim_matrix = screening["similarity_matrix"] sim_labels = screening["similarity_labels"] total = props["total"] lipinski_pass = props["lipinski_pass_count"] all_criteria = sum(1 for m in ranked if m["all_criteria_met"]) top = ranked[0] if ranked else None html_parts = [] # --- Executive Summary --- html_parts.append("

Drug Molecule Screening Report

") top_name = top["name"] if top else "N/A" top_score = f'{top["screening_score"]:.3f}' if top else "N/A" html_parts.append( f'
' f'

Executive Summary

' f'

' f'{total} molecules were screened against the target drug profile. ' f'{lipinski_pass} passed Lipinski\'s Rule of Five, and ' f'{all_criteria} met all screening criteria. ' f'The top candidate is {top_name} ' f'with a screening score of {top_score}.

' f'
' ) # Stat grid html_parts.append('
') for val, label in [ (str(total), "Molecules Screened"), (str(lipinski_pass), "Lipinski Passes"), (str(all_criteria), "All Criteria Met"), (top_score, "Top Score"), (f'{props["avg_mw"]:.0f} Da', "Avg. Molecular Weight"), (f'{props["avg_logp"]:.2f}', "Avg. LogP"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # --- Top 3 Candidate Spotlights --- html_parts.append("

Top Candidate Spotlights

") for rank, m in enumerate(ranked[:3], 1): mol = Chem.MolFromSmiles(m["smiles"]) img_uri = _mol_to_data_uri(mol, size=(300, 300)) if mol else "" medal = ["gold", "silver", "#cd7f32"][rank - 1] medal_emoji = ["1st", "2nd", "3rd"][rank - 1] lip_badges = "" for rule, key in [("MW", "mw_ok"), ("LogP", "logp_ok"), ("HBD", "hbd_ok"), ("HBA", "hba_ok")]: ok = m["lipinski"].get(key, False) cls = "badge-success" if ok else "badge-danger" lip_badges += f'{rule} ' html_parts.append( f'
' f'
' f'
{medal_emoji}
' f'' f'
{m["name"]}
' f'
' f'
' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'
SMILES{m["smiles"]}
Screening Score{m["screening_score"]:.3f}
Molecular Weight{m["mw"]:.1f} Da
LogP{m["logp"]:.2f}
H-Bond Donors{m["hbd"]}
H-Bond Acceptors{m["hba"]}
TPSA{m["tpsa"]:.1f} A²
Rotatable Bonds{m["rotatable_bonds"]}
QED{m["qed"]:.4f}
Lipinski Compliance{lip_badges}
' f'
' f'
' ) # --- Property Distribution (box-plot style as bars with min/max/median) --- html_parts.append("

Property Distributions

") prop_keys = [("mw", "Molecular Weight (Da)"), ("logp", "LogP"), ("tpsa", "TPSA"), ("qed", "QED Score")] for key, label in prop_keys: vals = sorted([m[key] for m in ranked]) n = len(vals) if n == 0: continue v_min = vals[0] v_max = vals[-1] median = vals[n // 2] if n % 2 == 1 else (vals[n // 2 - 1] + vals[n // 2]) / 2 q1 = vals[n // 4] if n >= 4 else v_min q3 = vals[3 * n // 4] if n >= 4 else v_max # Simple horizontal box-plot as SVG box_w = 500 box_h = 50 margin_l = 10 v_range = v_max - v_min or 1 def sx(v): return margin_l + ((v - v_min) / v_range) * (box_w - 2 * margin_l) box_svg = ( f'' f'' # Whisker line f'' # Min whisker f'' # Max whisker f'' # IQR box f'' # Median line f'' # Labels f'{v_min:.1f}' f'{median:.1f}' f'{v_max:.1f}' f'' ) html_parts.append( f'
{label}' f'
{box_svg}
' ) # --- Chemical Diversity --- html_parts.append("

Chemical Diversity Analysis

") if sim_matrix and len(sim_matrix) > 1: # Compute average pairwise similarity (off-diagonal) n_mols = len(sim_matrix) off_diag = [] for i in range(n_mols): for j in range(i + 1, n_mols): off_diag.append(sim_matrix[i][j]) avg_sim = sum(off_diag) / len(off_diag) if off_diag else 0 max_sim = max(off_diag) if off_diag else 0 min_sim = min(off_diag) if off_diag else 0 # Find most similar pair best_i, best_j = 0, 1 best_val = 0 for i in range(n_mols): for j in range(i + 1, n_mols): if sim_matrix[i][j] > best_val: best_val = sim_matrix[i][j] best_i, best_j = i, j html_parts.append('
') html_parts.append( f'
{avg_sim:.3f}
' f'
Avg. Pairwise Similarity
' ) html_parts.append( f'
{min_sim:.3f}
' f'
Min Similarity
' ) html_parts.append( f'
{max_sim:.3f}
' f'
Max Similarity
' ) html_parts.append("
") diversity_text = "highly diverse" if avg_sim < 0.3 else "moderately diverse" if avg_sim < 0.5 else "relatively similar" html_parts.append( f'
' f'The library is {diversity_text} (avg. Tanimoto = {avg_sim:.3f}). ' f'The most similar pair is {sim_labels[best_i]} and ' f'{sim_labels[best_j]} (similarity = {best_val:.3f}).
' ) # --- Recommendation --- html_parts.append("

Recommendation

") if top: html_parts.append( f'
' f'

Top Candidate: {top["name"]}

' f'

Based on the virtual screening analysis, {top["name"]} ' f'achieved the highest composite screening score of {top["screening_score"]:.3f}. ' ) reasons = [] if top["lipinski_pass"]: reasons.append("full Lipinski Rule of Five compliance") if top["qed"] > 0.5: reasons.append(f"high drug-likeness (QED = {top['qed']:.3f})") if top.get("all_criteria_met"): reasons.append("all target profile criteria met") if top["mw"] <= 500: reasons.append(f"favorable molecular weight ({top['mw']:.1f} Da)") if reasons: html_parts.append( f'This candidate stands out due to: {", ".join(reasons)}.

' ) else: html_parts.append("

") # Runner-up mentions if len(ranked) >= 2: html_parts.append( f'

Runner-up candidates: ' ) runners = [] for m in ranked[1:4]: runners.append(f'{m["name"]} (score: {m["screening_score"]:.3f})') html_parts.append(", ".join(runners) + ".

") html_parts.append("
") # Final note html_parts.append( '
' "This is a virtual screening analysis. All candidates should undergo " "further computational validation (molecular dynamics, docking) and " "experimental testing before advancing to clinical trials.
" ) await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) # JSON summary summary = { "total_screened": total, "lipinski_passes": lipinski_pass, "all_criteria_met": all_criteria, "top_candidate": top["name"] if top else None, "top_score": top["screening_score"] if top else None, "top_3": [ {"name": m["name"], "score": m["screening_score"]} for m in ranked[:3] ], } return json.dumps(summary) # ------------------------------------------------------------------ # Agent # ------------------------------------------------------------------ # {{docs-fragment agent}} SCREENING_AGENT_INSTRUCTIONS = """\ You are a medicinal chemistry screening strategist. You orchestrate a virtual \ screening pipeline using durable Flyte tools. You NEVER invent molecular \ properties โ€” only RDKit tools compute them. Workflow: 1. If target_profile is not provided in the user message, derive a JSON \ target_profile from the therapeutic brief. Valid keys: mw, logp, hbd, hba, tpsa \ (each [min, max]). Ground choices in oral bioavailability / kinase / CNS rules \ as appropriate to the brief. 2. First pass (always): load_molecules โ†’ compute_properties โ†’ \ screen_candidates โ†’ generate_report. Pass tool outputs between steps exactly \ (molecule_dir from load_molecules into compute_properties and generate_report; \ properties_json from compute_properties into screen_candidates and \ generate_report; screening_json must be the complete, unmodified string \ returned by screen_candidates โ€” never rebuild or summarize JSON yourself). 3. Read the JSON summary returned by generate_report. Reflect: - If all_criteria_met == 0: relax exactly ONE profile bound by ~10โ€“20% \ and re-run screen_candidates then generate_report only, reusing the same \ molecule_dir and properties_json from the first pass. - If all molecules pass but diversity is a stated goal: note high similarity \ in your summary; do not re-run unless brief asks for stricter filters. - Maximum ONE rescreen iteration. 4. Finish with plain text: top candidate, rationale tied to computed metrics \ from the tool JSON, funnel interpretation, and suggested next steps (docking, \ ADMET lab tests). If the user supplies an explicit target_profile JSON, use it as-is. Do NOT ask the user for SMILES or molecule lists when molecules_json is empty โ€” \ the default library is loaded automatically. """ screening_agent = Agent( name="drug-screening-agent", instructions=SCREENING_AGENT_INSTRUCTIONS, model=MODEL, tools=[ load_molecules, compute_properties, screen_candidates, generate_report, ], max_turns=12, ) # {{/docs-fragment agent}} # ------------------------------------------------------------------ # Pipeline # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @env.task(report=True) async def pipeline( brief: str = "Screen the default drug library for orally bioavailable small molecules.", molecules_json: str = "", target_profile: str = "", ) -> str: """Agentic virtual drug molecule screening pipeline. A medicinal-chemistry agent interprets the screening brief, derives or applies a target profile, orchestrates the RDKit screening stages, and optionally re-screens when funnel results are too narrow. Args: brief: Natural-language therapeutic goal (e.g. oral kinase inhibitors, CNS-penetrant small molecules). molecules_json: JSON mapping molecule names to SMILES strings. Defaults to a curated library of ~15 well-known drugs. target_profile: Optional JSON with desired property ranges that overrides agent-derived criteria (e.g. {"mw": [150, 500], "logp": [-0.5, 5]}). Returns: Agent summary with screening rationale and key results. """ prompt_parts = [ f"Screening brief: {brief}", 'Use molecules_json="" for the built-in default library unless provided below.', "Compose the four stage tools in order: load_molecules โ†’ compute_properties " "โ†’ screen_candidates โ†’ generate_report. Pass each tool's full return value " "verbatim to the next step (especially screening_json). Re-run " "screen_candidates and generate_report at most once if the funnel is too narrow.", ] if molecules_json.strip(): prompt_parts.append(f"molecules_json: {molecules_json}") if target_profile.strip(): prompt_parts.append(f"Use this target_profile exactly: {target_profile}") result = await screening_agent.run.aio("\n".join(prompt_parts)) return result.summary or result.error or "" # {{/docs-fragment pipeline}} # ------------------------------------------------------------------ # Rescreen demo โ€” tight profile + explicit rescreen instructions # ------------------------------------------------------------------ # Initial profile is deliberately strict (narrow MW + low LogP cap) so # all_criteria_met is typically 0 on the default library; the brief then # forces a single rescreen with a widened LogP window. RESCREEN_DEMO_TARGET_PROFILE = ( '{"mw": [150, 200], "logp": [-0.5, 1.0], "hbd": [0, 1], ' '"hba": [0, 3], "tpsa": [20, 45]}' ) RESCREEN_DEMO_TARGET_PROFILE_RESCREEN = ( '{"mw": [150, 200], "logp": [-0.5, 3.5], "hbd": [0, 1], ' '"hba": [0, 3], "tpsa": [20, 45]}' ) RESCREEN_DEMO_BRIEF = f"""\ Two-round agentic screening demo on the default library. **Round 1 (strict profile):** load_molecules โ†’ compute_properties โ†’ \ screen_candidates โ†’ generate_report using the initial target_profile exactly. **Round 2 (required โ€” do not skip):** call screen_candidates then generate_report \ again, reusing the same molecule_dir and properties_json from round 1, with this \ relaxed target_profile (wider LogP window only): \ {RESCREEN_DEMO_TARGET_PROFILE_RESCREEN} Pass every tool return value verbatim to the next step. After both rounds, \ summarize how the funnel and top candidates changed between round 1 and round 2.""" # {{docs-fragment rescreen_demo}} @env.task(report=True) async def rescreen_demo() -> str: """Example run with a two-round execution graph (rescreen). Round 1 uses a strict CNS-like profile; round 2 always re-runs screen_candidates and generate_report with a widened LogP window, reusing cached molecule_dir and properties_json. """ return await pipeline( brief=RESCREEN_DEMO_BRIEF, target_profile=RESCREEN_DEMO_TARGET_PROFILE, ) # {{/docs-fragment rescreen_demo}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/drug_molecule_screening/drug_molecule_screening.py* ## Run the agentic pipeline The `pipeline` task delegates to the screening agent: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.5.4", # "litellm", # "rdkit", # "numpy", # "scikit-learn", # "pillow", # ] # main = "pipeline" # params = "" # /// """Virtual drug molecule screening โ€” compute properties, apply Lipinski filters, rank candidates.""" import base64 import io import json import logging import math import os import tempfile import flyte import flyte.io import flyte.report from flyte.ai.agents import Agent, tool MODEL = os.getenv("DRUG_SCREENING_MODEL", "claude-haiku-4-5") # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="drug-molecule-screening", pre=True).with_apt_packages( "libxrender1", "libxext6", "libexpat1", ) env = flyte.TaskEnvironment( name="drug-molecule-screening", image=main_img, resources=flyte.Resources(cpu=2, memory="6Gi"), secrets=[ flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Default molecule library โ€” real SMILES for well-known drugs # ------------------------------------------------------------------ DEFAULT_MOLECULES = { "Aspirin": "CC(=O)OC1=CC=CC=C1C(=O)O", "Ibuprofen": "CC(C)CC1=CC=C(C=C1)C(C)C(=O)O", "Caffeine": "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", "Penicillin G": "CC1(C(N2C(S1)C(C2=O)NC(=O)CC3=CC=CC=C3)C(=O)O)C", "Metformin": "CN(C)C(=N)NC(=N)N", "Paracetamol": "CC(=O)NC1=CC=C(C=C1)O", "Diazepam": "ClC1=CC2=C(C=C1)N(C(=O)CN=C2C3=CC=CC=C3)C", "Omeprazole": "CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=CC=CC=C3N2", "Atorvastatin": "CC(C)C1=C(C(=C(N1CCC(CC(CC(=O)O)O)O)C2=CC=C(C=C2)F)C3=CC=CC=C3)C(=O)NC4=CC=CC=C4", "Methotrexate": "CN(CC1=CN=C2N=C(N=C(N)C2=N1)N)C3=CC=C(C=C3)C(=O)NC(CCC(=O)O)C(=O)O", "Doxorubicin": "CC1C(C(CC(O1)OC2CC(CC3=C2C(=C4C(=C3O)C(=O)C5=C(C4=O)C(=CC=C5)OC)O)(C(=O)CO)O)N)O", "Tamoxifen": "CCC(=C(C1=CC=CC=C1)C2=CC=C(C=C2)OCCN(C)C)C3=CC=CC=C3", "Lopinavir": "CC1=C(C(=CC=C1)C)OCC(=O)NC(CC2=CC=CC=C2)C(CC(CC3=CC=CC=C3)NC(=O)C(C(C)C)N4CCCNC4=O)O", "Remdesivir": "CCC(CC)COC(=O)C(C)NP(=O)(OCC1C(C(C(O1)C2=CC=C3N2N=CN=C3N)O)O)OC4=CC=CC=C4", "Erlotinib": "COCCOC1=CC2=C(C=C1OCCOC)C(=NC=N2)NC3=CC=CC(=C3)C#C", } # ------------------------------------------------------------------ # Report styling โ€” pharma blue/cyan theme # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: """Wrap HTML content with report styling.""" return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers # ------------------------------------------------------------------ def _mol_to_data_uri(mol, size: tuple[int, int] = (300, 300)) -> str: """Convert an RDKit molecule to a PNG base64 data URI.""" from rdkit.Chem import Draw img = Draw.MolToImage(mol, size=size) buf = io.BytesIO() img.save(buf, format="PNG") b64 = base64.b64encode(buf.getvalue()).decode() return f"data:image/png;base64,{b64}" def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 340, y_max_cap: float | None = None, horizontal: bool = False, value_fmt: str = ".1f", ) -> str: """Generate an SVG grouped bar chart. Args: labels: Category labels. series: Dict mapping series name to list of values. title: Chart title. colors: Colors for each series. width/height: SVG dimensions. y_max_cap: Cap the y-axis at this value. horizontal: If True, draw horizontal bars. value_fmt: Format string for value labels. Returns: SVG string. """ if not labels: return "" default_colors = ["#0891b2", "#0e4f6e", "#06d6a0", "#a5f3fc", "#155e75"] colors = colors or default_colors if horizontal: return _make_horizontal_bar_chart(labels, series, title, colors, width, height, value_fmt) ml, mr, mt, mb = 60, 20, 40, 60 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_max = max(all_vals) if all_vals else 1 y_max_plot = y_max * 1.15 or 1 if y_max_cap is not None: y_max_plot = min(y_max_plot, y_max_cap) or y_max_cap n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - (v / y_max_plot) * ch svg = [ f'', f'', ] # Grid lines for i in range(6): y_tick = y_max_plot * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:{value_fmt}}' ) # Axes svg.append( f'' ) svg.append( f'' ) # Bars for gi, label in enumerate(labels): gx = ml + gi * group_width + gap for si, (name, vals) in enumerate(series.items()): color = colors[si % len(colors)] bx = gx + si * bar_width val = vals[gi] by = sy(val) bh = mt + ch - by svg.append( f'' ) svg.append( f'' f'{val:{value_fmt}}' ) # Truncate long labels disp_label = label if len(label) <= 12 else label[:10] + ".." svg.append( f'' f'{disp_label}' ) # Title if title: svg.append( f'{title}' ) # Legend if n_series > 1: lx = ml + cw - len(series) * 100 for si, name in enumerate(series): color = colors[si % len(colors)] svg.append( f'' ) svg.append( f'{name}' ) svg.append("") return "\n".join(svg) def _make_horizontal_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 400, value_fmt: str = ".1f", ) -> str: """Generate an SVG horizontal bar chart (sorted).""" default_colors = ["#0891b2", "#0e4f6e", "#06d6a0"] colors = colors or default_colors n = len(labels) row_height = max(22, min(35, (height - 80) // max(n, 1))) actual_height = max(height, 80 + n * row_height) ml, mr, mt, mb = 120, 60, 40, 20 cw = width - ml - mr ch = actual_height - mt - mb # Use first series first_key = list(series.keys())[0] vals = series[first_key] x_max = max(vals) * 1.15 if vals else 1 svg = [ f'', f'', ] if title: svg.append( f'{title}' ) bar_h = row_height * 0.65 for i, (label, val) in enumerate(zip(labels, vals)): y = mt + i * row_height bw = (val / x_max) * cw if x_max else 0 color = colors[i % len(colors)] # Label disp = label if len(label) <= 14 else label[:12] + ".." svg.append( f'{disp}' ) # Bar svg.append( f'' ) # Value svg.append( f'{val:{value_fmt}}' ) svg.append("") return "\n".join(svg) def _make_heatmap( matrix: list[list[float]], row_labels: list[str], col_labels: list[str], title: str = "", color_scale: str = "cyan", width: int = 700, height: int = 500, value_fmt: str = ".2f", ) -> str: """Generate an SVG heatmap. Args: matrix: 2D list of values (rows x cols). row_labels: Labels for rows. col_labels: Labels for columns. title: Chart title. color_scale: Color scheme ("cyan", "red", "green"). width/height: SVG dimensions. value_fmt: Format string for cell values. Returns: SVG string. """ if not matrix or not matrix[0]: return "" n_rows = len(matrix) n_cols = len(matrix[0]) ml, mr, mt, mb = 110, 20, 70, 20 cw = width - ml - mr ch = height - mt - mb cell_w = cw / n_cols cell_h = ch / n_rows # Flatten to find range flat = [v for row in matrix for v in row] v_min = min(flat) v_max = max(flat) v_range = v_max - v_min or 1 def color_for(v): t = (v - v_min) / v_range if color_scale == "cyan": # White to deep teal r = int(255 - t * (255 - 14)) g = int(255 - t * (255 - 79)) b = int(255 - t * (255 - 110)) elif color_scale == "red": r = int(255 - t * 50) g = int(255 - t * 200) b = int(255 - t * 200) else: # green r = int(255 - t * 200) g = int(255 - t * 50) b = int(255 - t * 200) return f"rgb({r},{g},{b})" svg = [ f'', f'', ] if title: svg.append( f'{title}' ) # Column labels (rotated) for ci, label in enumerate(col_labels): x = ml + ci * cell_w + cell_w / 2 disp = label if len(label) <= 12 else label[:10] + ".." svg.append( f'{disp}' ) # Row labels + cells for ri, (row_label, row_vals) in enumerate(zip(row_labels, matrix)): y = mt + ri * cell_h disp = row_label if len(row_label) <= 14 else row_label[:12] + ".." svg.append( f'{disp}' ) for ci, val in enumerate(row_vals): x = ml + ci * cell_w fill = color_for(val) svg.append( f'' ) # Text color: dark on light, light on dark t = (val - v_min) / v_range txt_color = "#fff" if t > 0.55 else "#1a1a2e" # Only show text if cells are large enough if cell_w > 30 and cell_h > 18: svg.append( f'' f'{val:{value_fmt}}' ) svg.append("") return "\n".join(svg) def _make_scatter_plot( points: list[dict], x_label: str = "MW", y_label: str = "LogP", title: str = "", reference_lines: list[dict] | None = None, width: int = 700, height: int = 400, ) -> str: """Generate an SVG scatter plot. Args: points: List of dicts with "x", "y", "label" keys. x_label/y_label: Axis labels. title: Chart title. reference_lines: List of dicts with "axis" ("x"/"y"), "value", "label". width/height: SVG dimensions. Returns: SVG string. """ if not points: return "" ml, mr, mt, mb = 60, 30, 40, 50 cw = width - ml - mr ch = height - mt - mb x_vals = [p["x"] for p in points] y_vals = [p["y"] for p in points] x_min, x_max = min(x_vals) * 0.9, max(x_vals) * 1.1 y_min, y_max = min(y_vals) - 1, max(y_vals) + 1 # Extend ranges to include reference lines if reference_lines: for rl in reference_lines: if rl["axis"] == "x": x_max = max(x_max, rl["value"] * 1.1) else: y_max = max(y_max, rl["value"] * 1.1) x_range = x_max - x_min or 1 y_range = y_max - y_min or 1 def sx(v): return ml + (v - x_min) / x_range * cw def sy(v): return mt + ch - (v - y_min) / y_range * ch svg = [ f'', f'', ] # Grid for i in range(6): y_tick = y_min + y_range * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:.1f}' ) for i in range(6): x_tick = x_min + x_range * i / 5 px = sx(x_tick) svg.append( f'{x_tick:.0f}' ) # Axes svg.append( f'' ) svg.append( f'' ) # Reference lines (Lipinski boundaries) if reference_lines: for rl in reference_lines: if rl["axis"] == "x": px = sx(rl["value"]) svg.append( f'' ) svg.append( f'{rl["label"]}' ) else: py = sy(rl["value"]) svg.append( f'' ) svg.append( f'{rl["label"]}' ) # Drug-like zone shading (MW<=500 and LogP<=5 quadrant) if reference_lines: mw_line = next((rl for rl in reference_lines if rl["axis"] == "x"), None) logp_line = next((rl for rl in reference_lines if rl["axis"] == "y"), None) if mw_line and logp_line: zx1 = sx(x_min) zx2 = sx(min(mw_line["value"], x_max)) zy1 = sy(min(logp_line["value"], y_max)) zy2 = sy(y_min) svg.append( f'' ) svg.append( f'Drug-like Zone' ) # Points point_colors = ["#0891b2", "#0e4f6e", "#06d6a0", "#155e75", "#0284c7", "#059669", "#0d9488", "#0369a1", "#047857", "#115e59", "#0c4a6e", "#064e3b", "#1e3a5f", "#134e4a", "#075985"] for i, pt in enumerate(points): px, py = sx(pt["x"]), sy(pt["y"]) color = point_colors[i % len(point_colors)] svg.append( f'' ) # Label offset to avoid overlap offset_x = 8 offset_y = -8 if i % 2 == 0 else 14 label = pt["label"] if len(pt["label"]) <= 12 else pt["label"][:10] + ".." svg.append( f'{label}' ) # Title if title: svg.append( f'{title}' ) # Axis labels if x_label: svg.append( f'{x_label}' ) if y_label: svg.append( f'{y_label}' ) svg.append("") return "\n".join(svg) def _make_funnel( stages: list[dict], title: str = "", width: int = 600, height: int = 400, ) -> str: """Generate an SVG funnel visualization. Args: stages: List of dicts with "label", "count", "total" keys. title: Chart title. width/height: SVG dimensions. Returns: SVG string. """ if not stages: return "" n = len(stages) mt = 50 mb = 20 available_h = height - mt - mb stage_h = available_h / n cx = width / 2 # Color gradient from light cyan to deep teal colors = [] for i in range(n): t = i / max(n - 1, 1) r = int(207 - t * (207 - 14)) g = int(250 - t * (250 - 79)) b = int(254 - t * (254 - 110)) colors.append(f"rgb({r},{g},{b})") svg = [ f'', f'', ] if title: svg.append( f'{title}' ) max_count = stages[0]["count"] if stages else 1 max_width = width * 0.75 for i, stage in enumerate(stages): y_top = mt + i * stage_h y_bot = y_top + stage_h # Width proportional to count w_top = max_width * (stage["count"] / max_count) if i == 0 else prev_w_bot if i < n - 1: w_bot = max_width * (stages[i + 1]["count"] / max_count) else: w_bot = max_width * (stage["count"] / max_count) * 0.7 prev_w_bot = w_bot # Trapezoid x1_top = cx - w_top / 2 x2_top = cx + w_top / 2 x1_bot = cx - w_bot / 2 x2_bot = cx + w_bot / 2 svg.append( f'' ) # Text: dark on light, white on dark t = i / max(n - 1, 1) txt_color = "#0e4f6e" if t < 0.5 else "#fff" y_mid = (y_top + y_bot) / 2 svg.append( f'{stage["label"]}' ) svg.append( f'' f'{stage["count"]} / {stage["total"]}' ) svg.append("") return "\n".join(svg) # ------------------------------------------------------------------ # Task 1: Load and validate molecules # ------------------------------------------------------------------ @tool @env.task(cache="auto") async def load_molecules( molecules_json: str = "", ) -> flyte.io.Dir: """Parse SMILES strings, validate with RDKit, generate 2D depictions. Args: molecules_json: JSON string mapping molecule names to SMILES. Defaults to a curated library of ~15 well-known drugs. Returns: flyte.io.Dir containing molecule data (JSON + PNG depictions). Pass this directory to compute_properties and generate_report. """ from rdkit import Chem from rdkit.Chem import Draw if molecules_json.strip(): molecules = json.loads(molecules_json) else: molecules = DEFAULT_MOLECULES out_dir = tempfile.mkdtemp(prefix="mol_library_") results = [] valid_count = 0 invalid_count = 0 log.info(f"Parsing {len(molecules)} molecules...") for name, smiles in molecules.items(): mol = Chem.MolFromSmiles(smiles) if mol is None: log.warning(f" [INVALID] {name}: {smiles}") invalid_count += 1 continue valid_count += 1 # Generate 2D depiction as PNG img = Draw.MolToImage(mol, size=(300, 300)) img_path = os.path.join(out_dir, f"{name.replace(' ', '_')}.png") img.save(img_path) results.append({ "name": name, "smiles": smiles, "valid": True, "image_file": os.path.basename(img_path), }) # Save molecule manifest manifest = { "total": len(molecules), "valid": valid_count, "invalid": invalid_count, "molecules": results, } manifest_path = os.path.join(out_dir, "manifest.json") with open(manifest_path, "w") as f: json.dump(manifest, f, indent=2) log.info(f"Loaded {valid_count} valid molecules ({invalid_count} invalid)") return await flyte.io.Dir.from_local(out_dir) # ------------------------------------------------------------------ # Task 2: Compute physicochemical properties # ------------------------------------------------------------------ @tool @env.task(report=True) async def compute_properties( molecule_dir: flyte.io.Dir, ) -> str: """Compute drug-likeness properties for all molecules. Computes MW, LogP, HBD, HBA, TPSA, rotatable bonds, formal charge, ring count, QED, and Lipinski Rule of Five compliance. Args: molecule_dir: Directory from load_molecules. Returns: JSON string with all computed properties. Pass to screen_candidates and generate_report. """ from rdkit import Chem from rdkit.Chem import Descriptors, Lipinski from rdkit.Chem.QED import qed # --- Loading report --- await flyte.report.replace.aio( _wrap_report("

Computing Molecular Properties...

" "

Analyzing physicochemical descriptors for all molecules.

"), do_flush=True, ) mol_dir = await molecule_dir.download() with open(os.path.join(mol_dir, "manifest.json")) as f: manifest = json.load(f) molecules_data = [] lipinski_pass = 0 for mol_info in manifest["molecules"]: mol = Chem.MolFromSmiles(mol_info["smiles"]) if mol is None: continue mw = Descriptors.MolWt(mol) logp = Descriptors.MolLogP(mol) hbd = Lipinski.NumHDonors(mol) hba = Lipinski.NumHAcceptors(mol) tpsa = Descriptors.TPSA(mol) rotatable = Lipinski.NumRotatableBonds(mol) formal_charge = Chem.GetFormalCharge(mol) num_rings = Lipinski.RingCount(mol) qed_score = qed(mol) # Lipinski Rule of Five lipinski = { "mw_ok": mw <= 500, "logp_ok": logp <= 5, "hbd_ok": hbd <= 5, "hba_ok": hba <= 10, } lipinski_all = all(lipinski.values()) if lipinski_all: lipinski_pass += 1 # Read image for data URI img_path = os.path.join(mol_dir, mol_info["image_file"]) data_uri = "" if os.path.exists(img_path): with open(img_path, "rb") as img_f: b64 = base64.b64encode(img_f.read()).decode() data_uri = f"data:image/png;base64,{b64}" molecules_data.append({ "name": mol_info["name"], "smiles": mol_info["smiles"], "mw": round(mw, 2), "logp": round(logp, 2), "hbd": hbd, "hba": hba, "tpsa": round(tpsa, 2), "rotatable_bonds": rotatable, "formal_charge": formal_charge, "num_rings": num_rings, "qed": round(qed_score, 4), "lipinski": lipinski, "lipinski_pass": lipinski_all, "image_data_uri": data_uri, }) total = len(molecules_data) avg_mw = sum(m["mw"] for m in molecules_data) / total if total else 0 avg_logp = sum(m["logp"] for m in molecules_data) / total if total else 0 lipinski_rate = lipinski_pass / total * 100 if total else 0 # ---- Build report ---- html_parts = [] # Header html_parts.append("

Molecular Properties Analysis

") # Stat grid html_parts.append('
') for val, label in [ (str(total), "Total Molecules"), (f"{lipinski_rate:.0f}%", "Lipinski Pass Rate"), (f"{avg_mw:.1f}", "Avg. MW (Da)"), (f"{avg_logp:.2f}", "Avg. LogP"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # Molecule gallery html_parts.append("

Molecule Library

") html_parts.append('
') for m in molecules_data: if m["image_data_uri"]: badge_class = "badge-success" if m["lipinski_pass"] else "badge-danger" badge_text = "Lipinski Pass" if m["lipinski_pass"] else "Lipinski Fail" html_parts.append( f'
' f'' f'
{m["name"]}
' f'
MW: {m["mw"]:.1f} | LogP: {m["logp"]:.2f}
' f'
{badge_text}
' f'
' ) html_parts.append("
") # MW bar chart (horizontal, sorted) sorted_by_mw = sorted(molecules_data, key=lambda m: m["mw"], reverse=True) mw_labels = [m["name"] for m in sorted_by_mw] mw_vals = [m["mw"] for m in sorted_by_mw] mw_chart = _make_bar_chart( mw_labels, {"MW (Da)": mw_vals}, title="Molecular Weight Distribution", horizontal=True, width=700, height=max(300, len(mw_labels) * 30 + 80), value_fmt=".1f", ) html_parts.append("

Molecular Weight

") html_parts.append(f'
{mw_chart}
') # LogP vs MW scatter plot scatter_points = [ {"x": m["mw"], "y": m["logp"], "label": m["name"]} for m in molecules_data ] scatter_chart = _make_scatter_plot( scatter_points, x_label="Molecular Weight (Da)", y_label="LogP", title="LogP vs. Molecular Weight (Lipinski Boundaries)", reference_lines=[ {"axis": "x", "value": 500, "label": "MW = 500"}, {"axis": "y", "value": 5, "label": "LogP = 5"}, ], width=700, height=420, ) html_parts.append("

Lipinski Space

") html_parts.append(f'
{scatter_chart}
') # Property heatmap (molecules x properties) prop_names = ["MW", "LogP", "HBD", "HBA", "TPSA", "Rot. Bonds"] # Normalize each property to 0-1 for heatmap raw_matrix = [] for m in molecules_data: raw_matrix.append([m["mw"], m["logp"], m["hbd"], m["hba"], m["tpsa"], m["rotatable_bonds"]]) # Normalize per column n_props = len(prop_names) col_min = [min(row[c] for row in raw_matrix) for c in range(n_props)] col_max = [max(row[c] for row in raw_matrix) for c in range(n_props)] norm_matrix = [] for row in raw_matrix: norm_row = [] for c in range(n_props): rng = col_max[c] - col_min[c] norm_row.append((row[c] - col_min[c]) / rng if rng else 0.5) norm_matrix.append(norm_row) heatmap_labels = [m["name"] for m in molecules_data] heatmap = _make_heatmap( norm_matrix, heatmap_labels, prop_names, title="Normalized Property Heatmap", color_scale="cyan", width=700, height=max(400, len(heatmap_labels) * 28 + 100), ) html_parts.append("

Property Heatmap

") html_parts.append(f'
{heatmap}
') # Lipinski compliance table html_parts.append("

Lipinski Rule of Five Compliance

") html_parts.append("" "" "") for m in molecules_data: lip = m["lipinski"] def _badge(ok): if ok: return 'Pass' return 'Fail' overall_badge = _badge(m["lipinski_pass"]) html_parts.append( f'' f'' f'' f'' f'' f'' ) html_parts.append("
MoleculeMW ≤ 500LogP ≤ 5HBD ≤ 5HBA ≤ 10Overall
{m["name"]}{_badge(lip["mw_ok"])}{_badge(lip["logp_ok"])}{_badge(lip["hbd_ok"])}{_badge(lip["hba_ok"])}{overall_badge}
") # QED bar chart sorted_by_qed = sorted(molecules_data, key=lambda m: m["qed"], reverse=True) qed_labels = [m["name"] for m in sorted_by_qed] qed_vals = [m["qed"] for m in sorted_by_qed] qed_chart = _make_bar_chart( qed_labels, {"QED Score": qed_vals}, title="Drug-likeness (QED Score)", horizontal=True, width=700, height=max(300, len(qed_labels) * 30 + 80), value_fmt=".3f", colors=["#06d6a0"], ) html_parts.append("

Drug-likeness (QED)

") html_parts.append(f'
{qed_chart}
') # Flush full report await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) # Return properties as JSON (strip image data URIs to reduce size) output = { "total": total, "lipinski_pass_count": lipinski_pass, "lipinski_pass_rate": round(lipinski_rate, 2), "avg_mw": round(avg_mw, 2), "avg_logp": round(avg_logp, 2), "molecules": [ {k: v for k, v in m.items() if k != "image_data_uri"} for m in molecules_data ], } return json.dumps(output) # ------------------------------------------------------------------ # Task 3: Screen candidates against target profile # ------------------------------------------------------------------ @tool @env.task(report=True) async def screen_candidates( properties_json: str, target_profile: str = "", ) -> str: """Screen molecules against a target drug profile and rank candidates. Scores each molecule on how well it matches the target profile, computes pairwise Tanimoto similarity, and produces a ranked list. Args: properties_json: JSON from compute_properties. target_profile: JSON string with desired property ranges (e.g. {"mw": [150, 500], "logp": [-0.5, 5.0]}). Returns: JSON string with ranked_molecules, similarity_matrix, similarity_labels, funnel, and target_profile. Pass the full return value verbatim to generate_report along with molecule_dir and properties_json. """ from rdkit import Chem, DataStructs from rdkit.Chem import AllChem await flyte.report.replace.aio( _wrap_report("

Screening Candidates...

" "

Evaluating molecules against the target drug profile.

"), do_flush=True, ) props = json.loads(properties_json) molecules = props["molecules"] # Default target profile if target_profile.strip(): profile = json.loads(target_profile) else: profile = { "mw": [150, 500], "logp": [-0.5, 5.0], "hbd": [0, 5], "hba": [0, 10], "tpsa": [20, 140], } # --- Screening --- funnel_total = len(molecules) pass_mw = 0 pass_logp = 0 pass_lipinski = 0 final_candidates = 0 scored = [] for m in molecules: score = 0 max_score = 0 criteria = {} # Check each profile criterion checks = [ ("mw", m["mw"]), ("logp", m["logp"]), ("hbd", m["hbd"]), ("hba", m["hba"]), ("tpsa", m["tpsa"]), ] for key, val in checks: if key in profile: lo, hi = profile[key] max_score += 1 in_range = lo <= val <= hi criteria[key] = in_range if in_range: score += 1 # Bonus: closer to midpoint = higher score mid = (lo + hi) / 2 rng = (hi - lo) / 2 dist = abs(val - mid) / rng if rng else 0 score += max(0, 0.5 * (1 - dist)) # QED bonus score += m["qed"] * 2 max_score += 2 # Lipinski bonus if m["lipinski_pass"]: score += 1 max_score += 1 normalized_score = score / max_score if max_score else 0 # Funnel tracking โ€” cascading filter (each stage requires passing the previous) mw_ok = criteria.get("mw", True) logp_ok = criteria.get("logp", True) if mw_ok: pass_mw += 1 if logp_ok: pass_logp += 1 if m["lipinski_pass"]: pass_lipinski += 1 if all(criteria.values()): final_candidates += 1 scored.append({ **m, "screening_score": round(normalized_score, 4), "criteria_met": criteria, "all_criteria_met": all(criteria.values()), }) # Sort by score descending scored.sort(key=lambda m: m["screening_score"], reverse=True) # --- Tanimoto similarity matrix --- fps = [] valid_names = [] for m in scored: mol = Chem.MolFromSmiles(m["smiles"]) if mol: fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048) fps.append(fp) valid_names.append(m["name"]) similarity_matrix = [] for i in range(len(fps)): row = [] for j in range(len(fps)): sim = DataStructs.TanimotoSimilarity(fps[i], fps[j]) row.append(round(sim, 3)) similarity_matrix.append(row) # ---- Build report ---- html_parts = [] html_parts.append("

Candidate Screening Results

") # Stat grid html_parts.append('
') for val, label in [ (str(funnel_total), "Total Screened"), (str(pass_lipinski), "Lipinski Passes"), (str(final_candidates), "All Criteria Met"), (f"{scored[0]['screening_score']:.3f}" if scored else "N/A", "Top Score"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # Screening funnel funnel_stages = [ {"label": "Total Molecules", "count": funnel_total, "total": funnel_total}, {"label": "Pass MW Filter", "count": pass_mw, "total": funnel_total}, {"label": "Pass LogP Filter", "count": pass_logp, "total": funnel_total}, {"label": "Lipinski Compliant", "count": pass_lipinski, "total": funnel_total}, {"label": "All Criteria Met", "count": final_candidates, "total": funnel_total}, ] funnel_svg = _make_funnel( funnel_stages, title="Screening Funnel", width=600, height=380, ) html_parts.append("

Screening Funnel

") html_parts.append(f'
{funnel_svg}
') # Ranked candidates table html_parts.append("

Ranked Candidates

") html_parts.append( "" "" ) for rank, m in enumerate(scored, 1): lip_badge = ('Pass' if m["lipinski_pass"] else 'Fail') crit_badge = ('Pass' if m["all_criteria_met"] else 'Fail') # Highlight top 3 row_style = ' style="background:#ecfeff;font-weight:600;"' if rank <= 3 else "" html_parts.append( f"" f"" f"" f"" ) html_parts.append("
RankMoleculeScoreMWLogPQEDLipinskiAll Criteria
{rank}{m['name']}{m['screening_score']:.3f}{m['mw']:.1f}{m['logp']:.2f}{m['qed']:.3f}{lip_badge}{crit_badge}
") # Top 5 candidate cards with structures html_parts.append("

Top 5 Candidates

") html_parts.append('
') for m in scored[:5]: mol = Chem.MolFromSmiles(m["smiles"]) img_uri = _mol_to_data_uri(mol, size=(250, 250)) if mol else "" badge_class = "badge-success" if m["all_criteria_met"] else "badge-info" badge_text = "All Criteria Met" if m["all_criteria_met"] else "Partial Match" html_parts.append( f'
' f'' f'
{m["name"]}
' f'
Score: {m["screening_score"]:.3f}
' f'
MW: {m["mw"]:.1f} | LogP: {m["logp"]:.2f} | QED: {m["qed"]:.3f}
' f'
{badge_text}
' f'
' ) html_parts.append("
") # Tanimoto similarity heatmap if similarity_matrix: sim_heatmap = _make_heatmap( similarity_matrix, valid_names, valid_names, title="Pairwise Tanimoto Similarity (Morgan Fingerprints)", color_scale="cyan", width=700, height=max(500, len(valid_names) * 32 + 100), ) html_parts.append("

Chemical Similarity

") html_parts.append(f'
{sim_heatmap}
') await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) output = { "ranked_molecules": scored, "similarity_matrix": similarity_matrix, "similarity_labels": valid_names, "funnel": funnel_stages, "target_profile": profile, } return json.dumps(output) def _parse_screening_json(screening_json: str) -> dict: """Parse screening JSON from screen_candidates, with safe defaults. The agent must pass the exact tool return value. Partial or hand-built JSON is tolerated for optional similarity fields only. """ screening = json.loads(screening_json) if "ranked_molecules" not in screening: raise ValueError( "screening_json must be the exact JSON string returned by " "screen_candidates (missing 'ranked_molecules'). Do not construct, " "truncate, or summarize tool output." ) screening.setdefault("similarity_matrix", []) screening.setdefault("similarity_labels", []) return screening # ------------------------------------------------------------------ # Task 4: Generate final comprehensive report # ------------------------------------------------------------------ @tool @env.task(report=True) async def generate_report( molecule_dir: flyte.io.Dir, properties_json: str, screening_json: str, ) -> str: """Generate a comprehensive drug screening report. Produces an executive summary, top candidate spotlight cards, property distributions, chemical diversity analysis, and final recommendation. Args: molecule_dir: Directory from load_molecules. properties_json: JSON from compute_properties. screening_json: Exact verbatim JSON string returned by screen_candidates (must include ranked_molecules, similarity_matrix, similarity_labels). Do not construct or summarize this payload yourself. Returns: JSON summary with total_screened, lipinski_passes, all_criteria_met, top_candidate, top_score, and top_3 ranked molecules. """ from rdkit import Chem await flyte.report.replace.aio( _wrap_report("

Generating Final Report...

"), do_flush=True, ) props = json.loads(properties_json) screening = _parse_screening_json(screening_json) ranked = screening["ranked_molecules"] sim_matrix = screening["similarity_matrix"] sim_labels = screening["similarity_labels"] total = props["total"] lipinski_pass = props["lipinski_pass_count"] all_criteria = sum(1 for m in ranked if m["all_criteria_met"]) top = ranked[0] if ranked else None html_parts = [] # --- Executive Summary --- html_parts.append("

Drug Molecule Screening Report

") top_name = top["name"] if top else "N/A" top_score = f'{top["screening_score"]:.3f}' if top else "N/A" html_parts.append( f'
' f'

Executive Summary

' f'

' f'{total} molecules were screened against the target drug profile. ' f'{lipinski_pass} passed Lipinski\'s Rule of Five, and ' f'{all_criteria} met all screening criteria. ' f'The top candidate is {top_name} ' f'with a screening score of {top_score}.

' f'
' ) # Stat grid html_parts.append('
') for val, label in [ (str(total), "Molecules Screened"), (str(lipinski_pass), "Lipinski Passes"), (str(all_criteria), "All Criteria Met"), (top_score, "Top Score"), (f'{props["avg_mw"]:.0f} Da', "Avg. Molecular Weight"), (f'{props["avg_logp"]:.2f}', "Avg. LogP"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # --- Top 3 Candidate Spotlights --- html_parts.append("

Top Candidate Spotlights

") for rank, m in enumerate(ranked[:3], 1): mol = Chem.MolFromSmiles(m["smiles"]) img_uri = _mol_to_data_uri(mol, size=(300, 300)) if mol else "" medal = ["gold", "silver", "#cd7f32"][rank - 1] medal_emoji = ["1st", "2nd", "3rd"][rank - 1] lip_badges = "" for rule, key in [("MW", "mw_ok"), ("LogP", "logp_ok"), ("HBD", "hbd_ok"), ("HBA", "hba_ok")]: ok = m["lipinski"].get(key, False) cls = "badge-success" if ok else "badge-danger" lip_badges += f'{rule} ' html_parts.append( f'
' f'
' f'
{medal_emoji}
' f'' f'
{m["name"]}
' f'
' f'
' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'
SMILES{m["smiles"]}
Screening Score{m["screening_score"]:.3f}
Molecular Weight{m["mw"]:.1f} Da
LogP{m["logp"]:.2f}
H-Bond Donors{m["hbd"]}
H-Bond Acceptors{m["hba"]}
TPSA{m["tpsa"]:.1f} A²
Rotatable Bonds{m["rotatable_bonds"]}
QED{m["qed"]:.4f}
Lipinski Compliance{lip_badges}
' f'
' f'
' ) # --- Property Distribution (box-plot style as bars with min/max/median) --- html_parts.append("

Property Distributions

") prop_keys = [("mw", "Molecular Weight (Da)"), ("logp", "LogP"), ("tpsa", "TPSA"), ("qed", "QED Score")] for key, label in prop_keys: vals = sorted([m[key] for m in ranked]) n = len(vals) if n == 0: continue v_min = vals[0] v_max = vals[-1] median = vals[n // 2] if n % 2 == 1 else (vals[n // 2 - 1] + vals[n // 2]) / 2 q1 = vals[n // 4] if n >= 4 else v_min q3 = vals[3 * n // 4] if n >= 4 else v_max # Simple horizontal box-plot as SVG box_w = 500 box_h = 50 margin_l = 10 v_range = v_max - v_min or 1 def sx(v): return margin_l + ((v - v_min) / v_range) * (box_w - 2 * margin_l) box_svg = ( f'' f'' # Whisker line f'' # Min whisker f'' # Max whisker f'' # IQR box f'' # Median line f'' # Labels f'{v_min:.1f}' f'{median:.1f}' f'{v_max:.1f}' f'' ) html_parts.append( f'
{label}' f'
{box_svg}
' ) # --- Chemical Diversity --- html_parts.append("

Chemical Diversity Analysis

") if sim_matrix and len(sim_matrix) > 1: # Compute average pairwise similarity (off-diagonal) n_mols = len(sim_matrix) off_diag = [] for i in range(n_mols): for j in range(i + 1, n_mols): off_diag.append(sim_matrix[i][j]) avg_sim = sum(off_diag) / len(off_diag) if off_diag else 0 max_sim = max(off_diag) if off_diag else 0 min_sim = min(off_diag) if off_diag else 0 # Find most similar pair best_i, best_j = 0, 1 best_val = 0 for i in range(n_mols): for j in range(i + 1, n_mols): if sim_matrix[i][j] > best_val: best_val = sim_matrix[i][j] best_i, best_j = i, j html_parts.append('
') html_parts.append( f'
{avg_sim:.3f}
' f'
Avg. Pairwise Similarity
' ) html_parts.append( f'
{min_sim:.3f}
' f'
Min Similarity
' ) html_parts.append( f'
{max_sim:.3f}
' f'
Max Similarity
' ) html_parts.append("
") diversity_text = "highly diverse" if avg_sim < 0.3 else "moderately diverse" if avg_sim < 0.5 else "relatively similar" html_parts.append( f'
' f'The library is {diversity_text} (avg. Tanimoto = {avg_sim:.3f}). ' f'The most similar pair is {sim_labels[best_i]} and ' f'{sim_labels[best_j]} (similarity = {best_val:.3f}).
' ) # --- Recommendation --- html_parts.append("

Recommendation

") if top: html_parts.append( f'
' f'

Top Candidate: {top["name"]}

' f'

Based on the virtual screening analysis, {top["name"]} ' f'achieved the highest composite screening score of {top["screening_score"]:.3f}. ' ) reasons = [] if top["lipinski_pass"]: reasons.append("full Lipinski Rule of Five compliance") if top["qed"] > 0.5: reasons.append(f"high drug-likeness (QED = {top['qed']:.3f})") if top.get("all_criteria_met"): reasons.append("all target profile criteria met") if top["mw"] <= 500: reasons.append(f"favorable molecular weight ({top['mw']:.1f} Da)") if reasons: html_parts.append( f'This candidate stands out due to: {", ".join(reasons)}.

' ) else: html_parts.append("

") # Runner-up mentions if len(ranked) >= 2: html_parts.append( f'

Runner-up candidates: ' ) runners = [] for m in ranked[1:4]: runners.append(f'{m["name"]} (score: {m["screening_score"]:.3f})') html_parts.append(", ".join(runners) + ".

") html_parts.append("
") # Final note html_parts.append( '
' "This is a virtual screening analysis. All candidates should undergo " "further computational validation (molecular dynamics, docking) and " "experimental testing before advancing to clinical trials.
" ) await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) # JSON summary summary = { "total_screened": total, "lipinski_passes": lipinski_pass, "all_criteria_met": all_criteria, "top_candidate": top["name"] if top else None, "top_score": top["screening_score"] if top else None, "top_3": [ {"name": m["name"], "score": m["screening_score"]} for m in ranked[:3] ], } return json.dumps(summary) # ------------------------------------------------------------------ # Agent # ------------------------------------------------------------------ # {{docs-fragment agent}} SCREENING_AGENT_INSTRUCTIONS = """\ You are a medicinal chemistry screening strategist. You orchestrate a virtual \ screening pipeline using durable Flyte tools. You NEVER invent molecular \ properties โ€” only RDKit tools compute them. Workflow: 1. If target_profile is not provided in the user message, derive a JSON \ target_profile from the therapeutic brief. Valid keys: mw, logp, hbd, hba, tpsa \ (each [min, max]). Ground choices in oral bioavailability / kinase / CNS rules \ as appropriate to the brief. 2. First pass (always): load_molecules โ†’ compute_properties โ†’ \ screen_candidates โ†’ generate_report. Pass tool outputs between steps exactly \ (molecule_dir from load_molecules into compute_properties and generate_report; \ properties_json from compute_properties into screen_candidates and \ generate_report; screening_json must be the complete, unmodified string \ returned by screen_candidates โ€” never rebuild or summarize JSON yourself). 3. Read the JSON summary returned by generate_report. Reflect: - If all_criteria_met == 0: relax exactly ONE profile bound by ~10โ€“20% \ and re-run screen_candidates then generate_report only, reusing the same \ molecule_dir and properties_json from the first pass. - If all molecules pass but diversity is a stated goal: note high similarity \ in your summary; do not re-run unless brief asks for stricter filters. - Maximum ONE rescreen iteration. 4. Finish with plain text: top candidate, rationale tied to computed metrics \ from the tool JSON, funnel interpretation, and suggested next steps (docking, \ ADMET lab tests). If the user supplies an explicit target_profile JSON, use it as-is. Do NOT ask the user for SMILES or molecule lists when molecules_json is empty โ€” \ the default library is loaded automatically. """ screening_agent = Agent( name="drug-screening-agent", instructions=SCREENING_AGENT_INSTRUCTIONS, model=MODEL, tools=[ load_molecules, compute_properties, screen_candidates, generate_report, ], max_turns=12, ) # {{/docs-fragment agent}} # ------------------------------------------------------------------ # Pipeline # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @env.task(report=True) async def pipeline( brief: str = "Screen the default drug library for orally bioavailable small molecules.", molecules_json: str = "", target_profile: str = "", ) -> str: """Agentic virtual drug molecule screening pipeline. A medicinal-chemistry agent interprets the screening brief, derives or applies a target profile, orchestrates the RDKit screening stages, and optionally re-screens when funnel results are too narrow. Args: brief: Natural-language therapeutic goal (e.g. oral kinase inhibitors, CNS-penetrant small molecules). molecules_json: JSON mapping molecule names to SMILES strings. Defaults to a curated library of ~15 well-known drugs. target_profile: Optional JSON with desired property ranges that overrides agent-derived criteria (e.g. {"mw": [150, 500], "logp": [-0.5, 5]}). Returns: Agent summary with screening rationale and key results. """ prompt_parts = [ f"Screening brief: {brief}", 'Use molecules_json="" for the built-in default library unless provided below.', "Compose the four stage tools in order: load_molecules โ†’ compute_properties " "โ†’ screen_candidates โ†’ generate_report. Pass each tool's full return value " "verbatim to the next step (especially screening_json). Re-run " "screen_candidates and generate_report at most once if the funnel is too narrow.", ] if molecules_json.strip(): prompt_parts.append(f"molecules_json: {molecules_json}") if target_profile.strip(): prompt_parts.append(f"Use this target_profile exactly: {target_profile}") result = await screening_agent.run.aio("\n".join(prompt_parts)) return result.summary or result.error or "" # {{/docs-fragment pipeline}} # ------------------------------------------------------------------ # Rescreen demo โ€” tight profile + explicit rescreen instructions # ------------------------------------------------------------------ # Initial profile is deliberately strict (narrow MW + low LogP cap) so # all_criteria_met is typically 0 on the default library; the brief then # forces a single rescreen with a widened LogP window. RESCREEN_DEMO_TARGET_PROFILE = ( '{"mw": [150, 200], "logp": [-0.5, 1.0], "hbd": [0, 1], ' '"hba": [0, 3], "tpsa": [20, 45]}' ) RESCREEN_DEMO_TARGET_PROFILE_RESCREEN = ( '{"mw": [150, 200], "logp": [-0.5, 3.5], "hbd": [0, 1], ' '"hba": [0, 3], "tpsa": [20, 45]}' ) RESCREEN_DEMO_BRIEF = f"""\ Two-round agentic screening demo on the default library. **Round 1 (strict profile):** load_molecules โ†’ compute_properties โ†’ \ screen_candidates โ†’ generate_report using the initial target_profile exactly. **Round 2 (required โ€” do not skip):** call screen_candidates then generate_report \ again, reusing the same molecule_dir and properties_json from round 1, with this \ relaxed target_profile (wider LogP window only): \ {RESCREEN_DEMO_TARGET_PROFILE_RESCREEN} Pass every tool return value verbatim to the next step. After both rounds, \ summarize how the funnel and top candidates changed between round 1 and round 2.""" # {{docs-fragment rescreen_demo}} @env.task(report=True) async def rescreen_demo() -> str: """Example run with a two-round execution graph (rescreen). Round 1 uses a strict CNS-like profile; round 2 always re-runs screen_candidates and generate_report with a widened LogP window, reusing cached molecule_dir and properties_json. """ return await pipeline( brief=RESCREEN_DEMO_BRIEF, target_profile=RESCREEN_DEMO_TARGET_PROFILE, ) # {{/docs-fragment rescreen_demo}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/drug_molecule_screening/drug_molecule_screening.py* From the [example directory](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/drug_molecule_screening): ``` cd v2/tutorials/drug_molecule_screening uv run --script drug_molecule_screening.py ``` Pass a natural-language brief (the agent derives the target profile): ``` flyte run drug_molecule_screening.py pipeline \ --brief "Find oral kinase inhibitor candidates under 400 Da with moderate LogP" ``` Or pass an explicit target profile to skip agent-derived criteria: ``` flyte run drug_molecule_screening.py pipeline \ --target_profile '{"mw": [100, 400], "logp": [-0.5, 4.0]}' ``` ### Two-round rescreen demo (complex execution graph) The `rescreen_demo` task always runs two screening rounds: a strict first pass (`load_molecules` โ†’ `compute_properties` โ†’ `screen_candidates` โ†’ `generate_report`), then a second `screen_candidates` โ†’ `generate_report` with a widened LogP window reusing the same `molecule_dir` and `properties_json`. The Flyte UI shows six stage tasks instead of four. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.5.4", # "litellm", # "rdkit", # "numpy", # "scikit-learn", # "pillow", # ] # main = "pipeline" # params = "" # /// """Virtual drug molecule screening โ€” compute properties, apply Lipinski filters, rank candidates.""" import base64 import io import json import logging import math import os import tempfile import flyte import flyte.io import flyte.report from flyte.ai.agents import Agent, tool MODEL = os.getenv("DRUG_SCREENING_MODEL", "claude-haiku-4-5") # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="drug-molecule-screening", pre=True).with_apt_packages( "libxrender1", "libxext6", "libexpat1", ) env = flyte.TaskEnvironment( name="drug-molecule-screening", image=main_img, resources=flyte.Resources(cpu=2, memory="6Gi"), secrets=[ flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Default molecule library โ€” real SMILES for well-known drugs # ------------------------------------------------------------------ DEFAULT_MOLECULES = { "Aspirin": "CC(=O)OC1=CC=CC=C1C(=O)O", "Ibuprofen": "CC(C)CC1=CC=C(C=C1)C(C)C(=O)O", "Caffeine": "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", "Penicillin G": "CC1(C(N2C(S1)C(C2=O)NC(=O)CC3=CC=CC=C3)C(=O)O)C", "Metformin": "CN(C)C(=N)NC(=N)N", "Paracetamol": "CC(=O)NC1=CC=C(C=C1)O", "Diazepam": "ClC1=CC2=C(C=C1)N(C(=O)CN=C2C3=CC=CC=C3)C", "Omeprazole": "CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=CC=CC=C3N2", "Atorvastatin": "CC(C)C1=C(C(=C(N1CCC(CC(CC(=O)O)O)O)C2=CC=C(C=C2)F)C3=CC=CC=C3)C(=O)NC4=CC=CC=C4", "Methotrexate": "CN(CC1=CN=C2N=C(N=C(N)C2=N1)N)C3=CC=C(C=C3)C(=O)NC(CCC(=O)O)C(=O)O", "Doxorubicin": "CC1C(C(CC(O1)OC2CC(CC3=C2C(=C4C(=C3O)C(=O)C5=C(C4=O)C(=CC=C5)OC)O)(C(=O)CO)O)N)O", "Tamoxifen": "CCC(=C(C1=CC=CC=C1)C2=CC=C(C=C2)OCCN(C)C)C3=CC=CC=C3", "Lopinavir": "CC1=C(C(=CC=C1)C)OCC(=O)NC(CC2=CC=CC=C2)C(CC(CC3=CC=CC=C3)NC(=O)C(C(C)C)N4CCCNC4=O)O", "Remdesivir": "CCC(CC)COC(=O)C(C)NP(=O)(OCC1C(C(C(O1)C2=CC=C3N2N=CN=C3N)O)O)OC4=CC=CC=C4", "Erlotinib": "COCCOC1=CC2=C(C=C1OCCOC)C(=NC=N2)NC3=CC=CC(=C3)C#C", } # ------------------------------------------------------------------ # Report styling โ€” pharma blue/cyan theme # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: """Wrap HTML content with report styling.""" return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers # ------------------------------------------------------------------ def _mol_to_data_uri(mol, size: tuple[int, int] = (300, 300)) -> str: """Convert an RDKit molecule to a PNG base64 data URI.""" from rdkit.Chem import Draw img = Draw.MolToImage(mol, size=size) buf = io.BytesIO() img.save(buf, format="PNG") b64 = base64.b64encode(buf.getvalue()).decode() return f"data:image/png;base64,{b64}" def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 340, y_max_cap: float | None = None, horizontal: bool = False, value_fmt: str = ".1f", ) -> str: """Generate an SVG grouped bar chart. Args: labels: Category labels. series: Dict mapping series name to list of values. title: Chart title. colors: Colors for each series. width/height: SVG dimensions. y_max_cap: Cap the y-axis at this value. horizontal: If True, draw horizontal bars. value_fmt: Format string for value labels. Returns: SVG string. """ if not labels: return "" default_colors = ["#0891b2", "#0e4f6e", "#06d6a0", "#a5f3fc", "#155e75"] colors = colors or default_colors if horizontal: return _make_horizontal_bar_chart(labels, series, title, colors, width, height, value_fmt) ml, mr, mt, mb = 60, 20, 40, 60 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_max = max(all_vals) if all_vals else 1 y_max_plot = y_max * 1.15 or 1 if y_max_cap is not None: y_max_plot = min(y_max_plot, y_max_cap) or y_max_cap n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - (v / y_max_plot) * ch svg = [ f'', f'', ] # Grid lines for i in range(6): y_tick = y_max_plot * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:{value_fmt}}' ) # Axes svg.append( f'' ) svg.append( f'' ) # Bars for gi, label in enumerate(labels): gx = ml + gi * group_width + gap for si, (name, vals) in enumerate(series.items()): color = colors[si % len(colors)] bx = gx + si * bar_width val = vals[gi] by = sy(val) bh = mt + ch - by svg.append( f'' ) svg.append( f'' f'{val:{value_fmt}}' ) # Truncate long labels disp_label = label if len(label) <= 12 else label[:10] + ".." svg.append( f'' f'{disp_label}' ) # Title if title: svg.append( f'{title}' ) # Legend if n_series > 1: lx = ml + cw - len(series) * 100 for si, name in enumerate(series): color = colors[si % len(colors)] svg.append( f'' ) svg.append( f'{name}' ) svg.append("") return "\n".join(svg) def _make_horizontal_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 400, value_fmt: str = ".1f", ) -> str: """Generate an SVG horizontal bar chart (sorted).""" default_colors = ["#0891b2", "#0e4f6e", "#06d6a0"] colors = colors or default_colors n = len(labels) row_height = max(22, min(35, (height - 80) // max(n, 1))) actual_height = max(height, 80 + n * row_height) ml, mr, mt, mb = 120, 60, 40, 20 cw = width - ml - mr ch = actual_height - mt - mb # Use first series first_key = list(series.keys())[0] vals = series[first_key] x_max = max(vals) * 1.15 if vals else 1 svg = [ f'', f'', ] if title: svg.append( f'{title}' ) bar_h = row_height * 0.65 for i, (label, val) in enumerate(zip(labels, vals)): y = mt + i * row_height bw = (val / x_max) * cw if x_max else 0 color = colors[i % len(colors)] # Label disp = label if len(label) <= 14 else label[:12] + ".." svg.append( f'{disp}' ) # Bar svg.append( f'' ) # Value svg.append( f'{val:{value_fmt}}' ) svg.append("") return "\n".join(svg) def _make_heatmap( matrix: list[list[float]], row_labels: list[str], col_labels: list[str], title: str = "", color_scale: str = "cyan", width: int = 700, height: int = 500, value_fmt: str = ".2f", ) -> str: """Generate an SVG heatmap. Args: matrix: 2D list of values (rows x cols). row_labels: Labels for rows. col_labels: Labels for columns. title: Chart title. color_scale: Color scheme ("cyan", "red", "green"). width/height: SVG dimensions. value_fmt: Format string for cell values. Returns: SVG string. """ if not matrix or not matrix[0]: return "" n_rows = len(matrix) n_cols = len(matrix[0]) ml, mr, mt, mb = 110, 20, 70, 20 cw = width - ml - mr ch = height - mt - mb cell_w = cw / n_cols cell_h = ch / n_rows # Flatten to find range flat = [v for row in matrix for v in row] v_min = min(flat) v_max = max(flat) v_range = v_max - v_min or 1 def color_for(v): t = (v - v_min) / v_range if color_scale == "cyan": # White to deep teal r = int(255 - t * (255 - 14)) g = int(255 - t * (255 - 79)) b = int(255 - t * (255 - 110)) elif color_scale == "red": r = int(255 - t * 50) g = int(255 - t * 200) b = int(255 - t * 200) else: # green r = int(255 - t * 200) g = int(255 - t * 50) b = int(255 - t * 200) return f"rgb({r},{g},{b})" svg = [ f'', f'', ] if title: svg.append( f'{title}' ) # Column labels (rotated) for ci, label in enumerate(col_labels): x = ml + ci * cell_w + cell_w / 2 disp = label if len(label) <= 12 else label[:10] + ".." svg.append( f'{disp}' ) # Row labels + cells for ri, (row_label, row_vals) in enumerate(zip(row_labels, matrix)): y = mt + ri * cell_h disp = row_label if len(row_label) <= 14 else row_label[:12] + ".." svg.append( f'{disp}' ) for ci, val in enumerate(row_vals): x = ml + ci * cell_w fill = color_for(val) svg.append( f'' ) # Text color: dark on light, light on dark t = (val - v_min) / v_range txt_color = "#fff" if t > 0.55 else "#1a1a2e" # Only show text if cells are large enough if cell_w > 30 and cell_h > 18: svg.append( f'' f'{val:{value_fmt}}' ) svg.append("") return "\n".join(svg) def _make_scatter_plot( points: list[dict], x_label: str = "MW", y_label: str = "LogP", title: str = "", reference_lines: list[dict] | None = None, width: int = 700, height: int = 400, ) -> str: """Generate an SVG scatter plot. Args: points: List of dicts with "x", "y", "label" keys. x_label/y_label: Axis labels. title: Chart title. reference_lines: List of dicts with "axis" ("x"/"y"), "value", "label". width/height: SVG dimensions. Returns: SVG string. """ if not points: return "" ml, mr, mt, mb = 60, 30, 40, 50 cw = width - ml - mr ch = height - mt - mb x_vals = [p["x"] for p in points] y_vals = [p["y"] for p in points] x_min, x_max = min(x_vals) * 0.9, max(x_vals) * 1.1 y_min, y_max = min(y_vals) - 1, max(y_vals) + 1 # Extend ranges to include reference lines if reference_lines: for rl in reference_lines: if rl["axis"] == "x": x_max = max(x_max, rl["value"] * 1.1) else: y_max = max(y_max, rl["value"] * 1.1) x_range = x_max - x_min or 1 y_range = y_max - y_min or 1 def sx(v): return ml + (v - x_min) / x_range * cw def sy(v): return mt + ch - (v - y_min) / y_range * ch svg = [ f'', f'', ] # Grid for i in range(6): y_tick = y_min + y_range * i / 5 py = sy(y_tick) svg.append( f'' ) svg.append( f'{y_tick:.1f}' ) for i in range(6): x_tick = x_min + x_range * i / 5 px = sx(x_tick) svg.append( f'{x_tick:.0f}' ) # Axes svg.append( f'' ) svg.append( f'' ) # Reference lines (Lipinski boundaries) if reference_lines: for rl in reference_lines: if rl["axis"] == "x": px = sx(rl["value"]) svg.append( f'' ) svg.append( f'{rl["label"]}' ) else: py = sy(rl["value"]) svg.append( f'' ) svg.append( f'{rl["label"]}' ) # Drug-like zone shading (MW<=500 and LogP<=5 quadrant) if reference_lines: mw_line = next((rl for rl in reference_lines if rl["axis"] == "x"), None) logp_line = next((rl for rl in reference_lines if rl["axis"] == "y"), None) if mw_line and logp_line: zx1 = sx(x_min) zx2 = sx(min(mw_line["value"], x_max)) zy1 = sy(min(logp_line["value"], y_max)) zy2 = sy(y_min) svg.append( f'' ) svg.append( f'Drug-like Zone' ) # Points point_colors = ["#0891b2", "#0e4f6e", "#06d6a0", "#155e75", "#0284c7", "#059669", "#0d9488", "#0369a1", "#047857", "#115e59", "#0c4a6e", "#064e3b", "#1e3a5f", "#134e4a", "#075985"] for i, pt in enumerate(points): px, py = sx(pt["x"]), sy(pt["y"]) color = point_colors[i % len(point_colors)] svg.append( f'' ) # Label offset to avoid overlap offset_x = 8 offset_y = -8 if i % 2 == 0 else 14 label = pt["label"] if len(pt["label"]) <= 12 else pt["label"][:10] + ".." svg.append( f'{label}' ) # Title if title: svg.append( f'{title}' ) # Axis labels if x_label: svg.append( f'{x_label}' ) if y_label: svg.append( f'{y_label}' ) svg.append("") return "\n".join(svg) def _make_funnel( stages: list[dict], title: str = "", width: int = 600, height: int = 400, ) -> str: """Generate an SVG funnel visualization. Args: stages: List of dicts with "label", "count", "total" keys. title: Chart title. width/height: SVG dimensions. Returns: SVG string. """ if not stages: return "" n = len(stages) mt = 50 mb = 20 available_h = height - mt - mb stage_h = available_h / n cx = width / 2 # Color gradient from light cyan to deep teal colors = [] for i in range(n): t = i / max(n - 1, 1) r = int(207 - t * (207 - 14)) g = int(250 - t * (250 - 79)) b = int(254 - t * (254 - 110)) colors.append(f"rgb({r},{g},{b})") svg = [ f'', f'', ] if title: svg.append( f'{title}' ) max_count = stages[0]["count"] if stages else 1 max_width = width * 0.75 for i, stage in enumerate(stages): y_top = mt + i * stage_h y_bot = y_top + stage_h # Width proportional to count w_top = max_width * (stage["count"] / max_count) if i == 0 else prev_w_bot if i < n - 1: w_bot = max_width * (stages[i + 1]["count"] / max_count) else: w_bot = max_width * (stage["count"] / max_count) * 0.7 prev_w_bot = w_bot # Trapezoid x1_top = cx - w_top / 2 x2_top = cx + w_top / 2 x1_bot = cx - w_bot / 2 x2_bot = cx + w_bot / 2 svg.append( f'' ) # Text: dark on light, white on dark t = i / max(n - 1, 1) txt_color = "#0e4f6e" if t < 0.5 else "#fff" y_mid = (y_top + y_bot) / 2 svg.append( f'{stage["label"]}' ) svg.append( f'' f'{stage["count"]} / {stage["total"]}' ) svg.append("") return "\n".join(svg) # ------------------------------------------------------------------ # Task 1: Load and validate molecules # ------------------------------------------------------------------ @tool @env.task(cache="auto") async def load_molecules( molecules_json: str = "", ) -> flyte.io.Dir: """Parse SMILES strings, validate with RDKit, generate 2D depictions. Args: molecules_json: JSON string mapping molecule names to SMILES. Defaults to a curated library of ~15 well-known drugs. Returns: flyte.io.Dir containing molecule data (JSON + PNG depictions). Pass this directory to compute_properties and generate_report. """ from rdkit import Chem from rdkit.Chem import Draw if molecules_json.strip(): molecules = json.loads(molecules_json) else: molecules = DEFAULT_MOLECULES out_dir = tempfile.mkdtemp(prefix="mol_library_") results = [] valid_count = 0 invalid_count = 0 log.info(f"Parsing {len(molecules)} molecules...") for name, smiles in molecules.items(): mol = Chem.MolFromSmiles(smiles) if mol is None: log.warning(f" [INVALID] {name}: {smiles}") invalid_count += 1 continue valid_count += 1 # Generate 2D depiction as PNG img = Draw.MolToImage(mol, size=(300, 300)) img_path = os.path.join(out_dir, f"{name.replace(' ', '_')}.png") img.save(img_path) results.append({ "name": name, "smiles": smiles, "valid": True, "image_file": os.path.basename(img_path), }) # Save molecule manifest manifest = { "total": len(molecules), "valid": valid_count, "invalid": invalid_count, "molecules": results, } manifest_path = os.path.join(out_dir, "manifest.json") with open(manifest_path, "w") as f: json.dump(manifest, f, indent=2) log.info(f"Loaded {valid_count} valid molecules ({invalid_count} invalid)") return await flyte.io.Dir.from_local(out_dir) # ------------------------------------------------------------------ # Task 2: Compute physicochemical properties # ------------------------------------------------------------------ @tool @env.task(report=True) async def compute_properties( molecule_dir: flyte.io.Dir, ) -> str: """Compute drug-likeness properties for all molecules. Computes MW, LogP, HBD, HBA, TPSA, rotatable bonds, formal charge, ring count, QED, and Lipinski Rule of Five compliance. Args: molecule_dir: Directory from load_molecules. Returns: JSON string with all computed properties. Pass to screen_candidates and generate_report. """ from rdkit import Chem from rdkit.Chem import Descriptors, Lipinski from rdkit.Chem.QED import qed # --- Loading report --- await flyte.report.replace.aio( _wrap_report("

Computing Molecular Properties...

" "

Analyzing physicochemical descriptors for all molecules.

"), do_flush=True, ) mol_dir = await molecule_dir.download() with open(os.path.join(mol_dir, "manifest.json")) as f: manifest = json.load(f) molecules_data = [] lipinski_pass = 0 for mol_info in manifest["molecules"]: mol = Chem.MolFromSmiles(mol_info["smiles"]) if mol is None: continue mw = Descriptors.MolWt(mol) logp = Descriptors.MolLogP(mol) hbd = Lipinski.NumHDonors(mol) hba = Lipinski.NumHAcceptors(mol) tpsa = Descriptors.TPSA(mol) rotatable = Lipinski.NumRotatableBonds(mol) formal_charge = Chem.GetFormalCharge(mol) num_rings = Lipinski.RingCount(mol) qed_score = qed(mol) # Lipinski Rule of Five lipinski = { "mw_ok": mw <= 500, "logp_ok": logp <= 5, "hbd_ok": hbd <= 5, "hba_ok": hba <= 10, } lipinski_all = all(lipinski.values()) if lipinski_all: lipinski_pass += 1 # Read image for data URI img_path = os.path.join(mol_dir, mol_info["image_file"]) data_uri = "" if os.path.exists(img_path): with open(img_path, "rb") as img_f: b64 = base64.b64encode(img_f.read()).decode() data_uri = f"data:image/png;base64,{b64}" molecules_data.append({ "name": mol_info["name"], "smiles": mol_info["smiles"], "mw": round(mw, 2), "logp": round(logp, 2), "hbd": hbd, "hba": hba, "tpsa": round(tpsa, 2), "rotatable_bonds": rotatable, "formal_charge": formal_charge, "num_rings": num_rings, "qed": round(qed_score, 4), "lipinski": lipinski, "lipinski_pass": lipinski_all, "image_data_uri": data_uri, }) total = len(molecules_data) avg_mw = sum(m["mw"] for m in molecules_data) / total if total else 0 avg_logp = sum(m["logp"] for m in molecules_data) / total if total else 0 lipinski_rate = lipinski_pass / total * 100 if total else 0 # ---- Build report ---- html_parts = [] # Header html_parts.append("

Molecular Properties Analysis

") # Stat grid html_parts.append('
') for val, label in [ (str(total), "Total Molecules"), (f"{lipinski_rate:.0f}%", "Lipinski Pass Rate"), (f"{avg_mw:.1f}", "Avg. MW (Da)"), (f"{avg_logp:.2f}", "Avg. LogP"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # Molecule gallery html_parts.append("

Molecule Library

") html_parts.append('
') for m in molecules_data: if m["image_data_uri"]: badge_class = "badge-success" if m["lipinski_pass"] else "badge-danger" badge_text = "Lipinski Pass" if m["lipinski_pass"] else "Lipinski Fail" html_parts.append( f'
' f'' f'
{m["name"]}
' f'
MW: {m["mw"]:.1f} | LogP: {m["logp"]:.2f}
' f'
{badge_text}
' f'
' ) html_parts.append("
") # MW bar chart (horizontal, sorted) sorted_by_mw = sorted(molecules_data, key=lambda m: m["mw"], reverse=True) mw_labels = [m["name"] for m in sorted_by_mw] mw_vals = [m["mw"] for m in sorted_by_mw] mw_chart = _make_bar_chart( mw_labels, {"MW (Da)": mw_vals}, title="Molecular Weight Distribution", horizontal=True, width=700, height=max(300, len(mw_labels) * 30 + 80), value_fmt=".1f", ) html_parts.append("

Molecular Weight

") html_parts.append(f'
{mw_chart}
') # LogP vs MW scatter plot scatter_points = [ {"x": m["mw"], "y": m["logp"], "label": m["name"]} for m in molecules_data ] scatter_chart = _make_scatter_plot( scatter_points, x_label="Molecular Weight (Da)", y_label="LogP", title="LogP vs. Molecular Weight (Lipinski Boundaries)", reference_lines=[ {"axis": "x", "value": 500, "label": "MW = 500"}, {"axis": "y", "value": 5, "label": "LogP = 5"}, ], width=700, height=420, ) html_parts.append("

Lipinski Space

") html_parts.append(f'
{scatter_chart}
') # Property heatmap (molecules x properties) prop_names = ["MW", "LogP", "HBD", "HBA", "TPSA", "Rot. Bonds"] # Normalize each property to 0-1 for heatmap raw_matrix = [] for m in molecules_data: raw_matrix.append([m["mw"], m["logp"], m["hbd"], m["hba"], m["tpsa"], m["rotatable_bonds"]]) # Normalize per column n_props = len(prop_names) col_min = [min(row[c] for row in raw_matrix) for c in range(n_props)] col_max = [max(row[c] for row in raw_matrix) for c in range(n_props)] norm_matrix = [] for row in raw_matrix: norm_row = [] for c in range(n_props): rng = col_max[c] - col_min[c] norm_row.append((row[c] - col_min[c]) / rng if rng else 0.5) norm_matrix.append(norm_row) heatmap_labels = [m["name"] for m in molecules_data] heatmap = _make_heatmap( norm_matrix, heatmap_labels, prop_names, title="Normalized Property Heatmap", color_scale="cyan", width=700, height=max(400, len(heatmap_labels) * 28 + 100), ) html_parts.append("

Property Heatmap

") html_parts.append(f'
{heatmap}
') # Lipinski compliance table html_parts.append("

Lipinski Rule of Five Compliance

") html_parts.append("" "" "") for m in molecules_data: lip = m["lipinski"] def _badge(ok): if ok: return 'Pass' return 'Fail' overall_badge = _badge(m["lipinski_pass"]) html_parts.append( f'' f'' f'' f'' f'' f'' ) html_parts.append("
MoleculeMW ≤ 500LogP ≤ 5HBD ≤ 5HBA ≤ 10Overall
{m["name"]}{_badge(lip["mw_ok"])}{_badge(lip["logp_ok"])}{_badge(lip["hbd_ok"])}{_badge(lip["hba_ok"])}{overall_badge}
") # QED bar chart sorted_by_qed = sorted(molecules_data, key=lambda m: m["qed"], reverse=True) qed_labels = [m["name"] for m in sorted_by_qed] qed_vals = [m["qed"] for m in sorted_by_qed] qed_chart = _make_bar_chart( qed_labels, {"QED Score": qed_vals}, title="Drug-likeness (QED Score)", horizontal=True, width=700, height=max(300, len(qed_labels) * 30 + 80), value_fmt=".3f", colors=["#06d6a0"], ) html_parts.append("

Drug-likeness (QED)

") html_parts.append(f'
{qed_chart}
') # Flush full report await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) # Return properties as JSON (strip image data URIs to reduce size) output = { "total": total, "lipinski_pass_count": lipinski_pass, "lipinski_pass_rate": round(lipinski_rate, 2), "avg_mw": round(avg_mw, 2), "avg_logp": round(avg_logp, 2), "molecules": [ {k: v for k, v in m.items() if k != "image_data_uri"} for m in molecules_data ], } return json.dumps(output) # ------------------------------------------------------------------ # Task 3: Screen candidates against target profile # ------------------------------------------------------------------ @tool @env.task(report=True) async def screen_candidates( properties_json: str, target_profile: str = "", ) -> str: """Screen molecules against a target drug profile and rank candidates. Scores each molecule on how well it matches the target profile, computes pairwise Tanimoto similarity, and produces a ranked list. Args: properties_json: JSON from compute_properties. target_profile: JSON string with desired property ranges (e.g. {"mw": [150, 500], "logp": [-0.5, 5.0]}). Returns: JSON string with ranked_molecules, similarity_matrix, similarity_labels, funnel, and target_profile. Pass the full return value verbatim to generate_report along with molecule_dir and properties_json. """ from rdkit import Chem, DataStructs from rdkit.Chem import AllChem await flyte.report.replace.aio( _wrap_report("

Screening Candidates...

" "

Evaluating molecules against the target drug profile.

"), do_flush=True, ) props = json.loads(properties_json) molecules = props["molecules"] # Default target profile if target_profile.strip(): profile = json.loads(target_profile) else: profile = { "mw": [150, 500], "logp": [-0.5, 5.0], "hbd": [0, 5], "hba": [0, 10], "tpsa": [20, 140], } # --- Screening --- funnel_total = len(molecules) pass_mw = 0 pass_logp = 0 pass_lipinski = 0 final_candidates = 0 scored = [] for m in molecules: score = 0 max_score = 0 criteria = {} # Check each profile criterion checks = [ ("mw", m["mw"]), ("logp", m["logp"]), ("hbd", m["hbd"]), ("hba", m["hba"]), ("tpsa", m["tpsa"]), ] for key, val in checks: if key in profile: lo, hi = profile[key] max_score += 1 in_range = lo <= val <= hi criteria[key] = in_range if in_range: score += 1 # Bonus: closer to midpoint = higher score mid = (lo + hi) / 2 rng = (hi - lo) / 2 dist = abs(val - mid) / rng if rng else 0 score += max(0, 0.5 * (1 - dist)) # QED bonus score += m["qed"] * 2 max_score += 2 # Lipinski bonus if m["lipinski_pass"]: score += 1 max_score += 1 normalized_score = score / max_score if max_score else 0 # Funnel tracking โ€” cascading filter (each stage requires passing the previous) mw_ok = criteria.get("mw", True) logp_ok = criteria.get("logp", True) if mw_ok: pass_mw += 1 if logp_ok: pass_logp += 1 if m["lipinski_pass"]: pass_lipinski += 1 if all(criteria.values()): final_candidates += 1 scored.append({ **m, "screening_score": round(normalized_score, 4), "criteria_met": criteria, "all_criteria_met": all(criteria.values()), }) # Sort by score descending scored.sort(key=lambda m: m["screening_score"], reverse=True) # --- Tanimoto similarity matrix --- fps = [] valid_names = [] for m in scored: mol = Chem.MolFromSmiles(m["smiles"]) if mol: fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048) fps.append(fp) valid_names.append(m["name"]) similarity_matrix = [] for i in range(len(fps)): row = [] for j in range(len(fps)): sim = DataStructs.TanimotoSimilarity(fps[i], fps[j]) row.append(round(sim, 3)) similarity_matrix.append(row) # ---- Build report ---- html_parts = [] html_parts.append("

Candidate Screening Results

") # Stat grid html_parts.append('
') for val, label in [ (str(funnel_total), "Total Screened"), (str(pass_lipinski), "Lipinski Passes"), (str(final_candidates), "All Criteria Met"), (f"{scored[0]['screening_score']:.3f}" if scored else "N/A", "Top Score"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # Screening funnel funnel_stages = [ {"label": "Total Molecules", "count": funnel_total, "total": funnel_total}, {"label": "Pass MW Filter", "count": pass_mw, "total": funnel_total}, {"label": "Pass LogP Filter", "count": pass_logp, "total": funnel_total}, {"label": "Lipinski Compliant", "count": pass_lipinski, "total": funnel_total}, {"label": "All Criteria Met", "count": final_candidates, "total": funnel_total}, ] funnel_svg = _make_funnel( funnel_stages, title="Screening Funnel", width=600, height=380, ) html_parts.append("

Screening Funnel

") html_parts.append(f'
{funnel_svg}
') # Ranked candidates table html_parts.append("

Ranked Candidates

") html_parts.append( "" "" ) for rank, m in enumerate(scored, 1): lip_badge = ('Pass' if m["lipinski_pass"] else 'Fail') crit_badge = ('Pass' if m["all_criteria_met"] else 'Fail') # Highlight top 3 row_style = ' style="background:#ecfeff;font-weight:600;"' if rank <= 3 else "" html_parts.append( f"" f"" f"" f"" ) html_parts.append("
RankMoleculeScoreMWLogPQEDLipinskiAll Criteria
{rank}{m['name']}{m['screening_score']:.3f}{m['mw']:.1f}{m['logp']:.2f}{m['qed']:.3f}{lip_badge}{crit_badge}
") # Top 5 candidate cards with structures html_parts.append("

Top 5 Candidates

") html_parts.append('
') for m in scored[:5]: mol = Chem.MolFromSmiles(m["smiles"]) img_uri = _mol_to_data_uri(mol, size=(250, 250)) if mol else "" badge_class = "badge-success" if m["all_criteria_met"] else "badge-info" badge_text = "All Criteria Met" if m["all_criteria_met"] else "Partial Match" html_parts.append( f'
' f'' f'
{m["name"]}
' f'
Score: {m["screening_score"]:.3f}
' f'
MW: {m["mw"]:.1f} | LogP: {m["logp"]:.2f} | QED: {m["qed"]:.3f}
' f'
{badge_text}
' f'
' ) html_parts.append("
") # Tanimoto similarity heatmap if similarity_matrix: sim_heatmap = _make_heatmap( similarity_matrix, valid_names, valid_names, title="Pairwise Tanimoto Similarity (Morgan Fingerprints)", color_scale="cyan", width=700, height=max(500, len(valid_names) * 32 + 100), ) html_parts.append("

Chemical Similarity

") html_parts.append(f'
{sim_heatmap}
') await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) output = { "ranked_molecules": scored, "similarity_matrix": similarity_matrix, "similarity_labels": valid_names, "funnel": funnel_stages, "target_profile": profile, } return json.dumps(output) def _parse_screening_json(screening_json: str) -> dict: """Parse screening JSON from screen_candidates, with safe defaults. The agent must pass the exact tool return value. Partial or hand-built JSON is tolerated for optional similarity fields only. """ screening = json.loads(screening_json) if "ranked_molecules" not in screening: raise ValueError( "screening_json must be the exact JSON string returned by " "screen_candidates (missing 'ranked_molecules'). Do not construct, " "truncate, or summarize tool output." ) screening.setdefault("similarity_matrix", []) screening.setdefault("similarity_labels", []) return screening # ------------------------------------------------------------------ # Task 4: Generate final comprehensive report # ------------------------------------------------------------------ @tool @env.task(report=True) async def generate_report( molecule_dir: flyte.io.Dir, properties_json: str, screening_json: str, ) -> str: """Generate a comprehensive drug screening report. Produces an executive summary, top candidate spotlight cards, property distributions, chemical diversity analysis, and final recommendation. Args: molecule_dir: Directory from load_molecules. properties_json: JSON from compute_properties. screening_json: Exact verbatim JSON string returned by screen_candidates (must include ranked_molecules, similarity_matrix, similarity_labels). Do not construct or summarize this payload yourself. Returns: JSON summary with total_screened, lipinski_passes, all_criteria_met, top_candidate, top_score, and top_3 ranked molecules. """ from rdkit import Chem await flyte.report.replace.aio( _wrap_report("

Generating Final Report...

"), do_flush=True, ) props = json.loads(properties_json) screening = _parse_screening_json(screening_json) ranked = screening["ranked_molecules"] sim_matrix = screening["similarity_matrix"] sim_labels = screening["similarity_labels"] total = props["total"] lipinski_pass = props["lipinski_pass_count"] all_criteria = sum(1 for m in ranked if m["all_criteria_met"]) top = ranked[0] if ranked else None html_parts = [] # --- Executive Summary --- html_parts.append("

Drug Molecule Screening Report

") top_name = top["name"] if top else "N/A" top_score = f'{top["screening_score"]:.3f}' if top else "N/A" html_parts.append( f'
' f'

Executive Summary

' f'

' f'{total} molecules were screened against the target drug profile. ' f'{lipinski_pass} passed Lipinski\'s Rule of Five, and ' f'{all_criteria} met all screening criteria. ' f'The top candidate is {top_name} ' f'with a screening score of {top_score}.

' f'
' ) # Stat grid html_parts.append('
') for val, label in [ (str(total), "Molecules Screened"), (str(lipinski_pass), "Lipinski Passes"), (str(all_criteria), "All Criteria Met"), (top_score, "Top Score"), (f'{props["avg_mw"]:.0f} Da', "Avg. Molecular Weight"), (f'{props["avg_logp"]:.2f}', "Avg. LogP"), ]: html_parts.append( f'
{val}
' f'
{label}
' ) html_parts.append("
") # --- Top 3 Candidate Spotlights --- html_parts.append("

Top Candidate Spotlights

") for rank, m in enumerate(ranked[:3], 1): mol = Chem.MolFromSmiles(m["smiles"]) img_uri = _mol_to_data_uri(mol, size=(300, 300)) if mol else "" medal = ["gold", "silver", "#cd7f32"][rank - 1] medal_emoji = ["1st", "2nd", "3rd"][rank - 1] lip_badges = "" for rule, key in [("MW", "mw_ok"), ("LogP", "logp_ok"), ("HBD", "hbd_ok"), ("HBA", "hba_ok")]: ok = m["lipinski"].get(key, False) cls = "badge-success" if ok else "badge-danger" lip_badges += f'{rule} ' html_parts.append( f'
' f'
' f'
{medal_emoji}
' f'' f'
{m["name"]}
' f'
' f'
' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'' f'
SMILES{m["smiles"]}
Screening Score{m["screening_score"]:.3f}
Molecular Weight{m["mw"]:.1f} Da
LogP{m["logp"]:.2f}
H-Bond Donors{m["hbd"]}
H-Bond Acceptors{m["hba"]}
TPSA{m["tpsa"]:.1f} A²
Rotatable Bonds{m["rotatable_bonds"]}
QED{m["qed"]:.4f}
Lipinski Compliance{lip_badges}
' f'
' f'
' ) # --- Property Distribution (box-plot style as bars with min/max/median) --- html_parts.append("

Property Distributions

") prop_keys = [("mw", "Molecular Weight (Da)"), ("logp", "LogP"), ("tpsa", "TPSA"), ("qed", "QED Score")] for key, label in prop_keys: vals = sorted([m[key] for m in ranked]) n = len(vals) if n == 0: continue v_min = vals[0] v_max = vals[-1] median = vals[n // 2] if n % 2 == 1 else (vals[n // 2 - 1] + vals[n // 2]) / 2 q1 = vals[n // 4] if n >= 4 else v_min q3 = vals[3 * n // 4] if n >= 4 else v_max # Simple horizontal box-plot as SVG box_w = 500 box_h = 50 margin_l = 10 v_range = v_max - v_min or 1 def sx(v): return margin_l + ((v - v_min) / v_range) * (box_w - 2 * margin_l) box_svg = ( f'' f'' # Whisker line f'' # Min whisker f'' # Max whisker f'' # IQR box f'' # Median line f'' # Labels f'{v_min:.1f}' f'{median:.1f}' f'{v_max:.1f}' f'' ) html_parts.append( f'
{label}' f'
{box_svg}
' ) # --- Chemical Diversity --- html_parts.append("

Chemical Diversity Analysis

") if sim_matrix and len(sim_matrix) > 1: # Compute average pairwise similarity (off-diagonal) n_mols = len(sim_matrix) off_diag = [] for i in range(n_mols): for j in range(i + 1, n_mols): off_diag.append(sim_matrix[i][j]) avg_sim = sum(off_diag) / len(off_diag) if off_diag else 0 max_sim = max(off_diag) if off_diag else 0 min_sim = min(off_diag) if off_diag else 0 # Find most similar pair best_i, best_j = 0, 1 best_val = 0 for i in range(n_mols): for j in range(i + 1, n_mols): if sim_matrix[i][j] > best_val: best_val = sim_matrix[i][j] best_i, best_j = i, j html_parts.append('
') html_parts.append( f'
{avg_sim:.3f}
' f'
Avg. Pairwise Similarity
' ) html_parts.append( f'
{min_sim:.3f}
' f'
Min Similarity
' ) html_parts.append( f'
{max_sim:.3f}
' f'
Max Similarity
' ) html_parts.append("
") diversity_text = "highly diverse" if avg_sim < 0.3 else "moderately diverse" if avg_sim < 0.5 else "relatively similar" html_parts.append( f'
' f'The library is {diversity_text} (avg. Tanimoto = {avg_sim:.3f}). ' f'The most similar pair is {sim_labels[best_i]} and ' f'{sim_labels[best_j]} (similarity = {best_val:.3f}).
' ) # --- Recommendation --- html_parts.append("

Recommendation

") if top: html_parts.append( f'
' f'

Top Candidate: {top["name"]}

' f'

Based on the virtual screening analysis, {top["name"]} ' f'achieved the highest composite screening score of {top["screening_score"]:.3f}. ' ) reasons = [] if top["lipinski_pass"]: reasons.append("full Lipinski Rule of Five compliance") if top["qed"] > 0.5: reasons.append(f"high drug-likeness (QED = {top['qed']:.3f})") if top.get("all_criteria_met"): reasons.append("all target profile criteria met") if top["mw"] <= 500: reasons.append(f"favorable molecular weight ({top['mw']:.1f} Da)") if reasons: html_parts.append( f'This candidate stands out due to: {", ".join(reasons)}.

' ) else: html_parts.append("

") # Runner-up mentions if len(ranked) >= 2: html_parts.append( f'

Runner-up candidates: ' ) runners = [] for m in ranked[1:4]: runners.append(f'{m["name"]} (score: {m["screening_score"]:.3f})') html_parts.append(", ".join(runners) + ".

") html_parts.append("
") # Final note html_parts.append( '
' "This is a virtual screening analysis. All candidates should undergo " "further computational validation (molecular dynamics, docking) and " "experimental testing before advancing to clinical trials.
" ) await flyte.report.replace.aio( _wrap_report("\n".join(html_parts)), do_flush=True, ) # JSON summary summary = { "total_screened": total, "lipinski_passes": lipinski_pass, "all_criteria_met": all_criteria, "top_candidate": top["name"] if top else None, "top_score": top["screening_score"] if top else None, "top_3": [ {"name": m["name"], "score": m["screening_score"]} for m in ranked[:3] ], } return json.dumps(summary) # ------------------------------------------------------------------ # Agent # ------------------------------------------------------------------ # {{docs-fragment agent}} SCREENING_AGENT_INSTRUCTIONS = """\ You are a medicinal chemistry screening strategist. You orchestrate a virtual \ screening pipeline using durable Flyte tools. You NEVER invent molecular \ properties โ€” only RDKit tools compute them. Workflow: 1. If target_profile is not provided in the user message, derive a JSON \ target_profile from the therapeutic brief. Valid keys: mw, logp, hbd, hba, tpsa \ (each [min, max]). Ground choices in oral bioavailability / kinase / CNS rules \ as appropriate to the brief. 2. First pass (always): load_molecules โ†’ compute_properties โ†’ \ screen_candidates โ†’ generate_report. Pass tool outputs between steps exactly \ (molecule_dir from load_molecules into compute_properties and generate_report; \ properties_json from compute_properties into screen_candidates and \ generate_report; screening_json must be the complete, unmodified string \ returned by screen_candidates โ€” never rebuild or summarize JSON yourself). 3. Read the JSON summary returned by generate_report. Reflect: - If all_criteria_met == 0: relax exactly ONE profile bound by ~10โ€“20% \ and re-run screen_candidates then generate_report only, reusing the same \ molecule_dir and properties_json from the first pass. - If all molecules pass but diversity is a stated goal: note high similarity \ in your summary; do not re-run unless brief asks for stricter filters. - Maximum ONE rescreen iteration. 4. Finish with plain text: top candidate, rationale tied to computed metrics \ from the tool JSON, funnel interpretation, and suggested next steps (docking, \ ADMET lab tests). If the user supplies an explicit target_profile JSON, use it as-is. Do NOT ask the user for SMILES or molecule lists when molecules_json is empty โ€” \ the default library is loaded automatically. """ screening_agent = Agent( name="drug-screening-agent", instructions=SCREENING_AGENT_INSTRUCTIONS, model=MODEL, tools=[ load_molecules, compute_properties, screen_candidates, generate_report, ], max_turns=12, ) # {{/docs-fragment agent}} # ------------------------------------------------------------------ # Pipeline # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @env.task(report=True) async def pipeline( brief: str = "Screen the default drug library for orally bioavailable small molecules.", molecules_json: str = "", target_profile: str = "", ) -> str: """Agentic virtual drug molecule screening pipeline. A medicinal-chemistry agent interprets the screening brief, derives or applies a target profile, orchestrates the RDKit screening stages, and optionally re-screens when funnel results are too narrow. Args: brief: Natural-language therapeutic goal (e.g. oral kinase inhibitors, CNS-penetrant small molecules). molecules_json: JSON mapping molecule names to SMILES strings. Defaults to a curated library of ~15 well-known drugs. target_profile: Optional JSON with desired property ranges that overrides agent-derived criteria (e.g. {"mw": [150, 500], "logp": [-0.5, 5]}). Returns: Agent summary with screening rationale and key results. """ prompt_parts = [ f"Screening brief: {brief}", 'Use molecules_json="" for the built-in default library unless provided below.', "Compose the four stage tools in order: load_molecules โ†’ compute_properties " "โ†’ screen_candidates โ†’ generate_report. Pass each tool's full return value " "verbatim to the next step (especially screening_json). Re-run " "screen_candidates and generate_report at most once if the funnel is too narrow.", ] if molecules_json.strip(): prompt_parts.append(f"molecules_json: {molecules_json}") if target_profile.strip(): prompt_parts.append(f"Use this target_profile exactly: {target_profile}") result = await screening_agent.run.aio("\n".join(prompt_parts)) return result.summary or result.error or "" # {{/docs-fragment pipeline}} # ------------------------------------------------------------------ # Rescreen demo โ€” tight profile + explicit rescreen instructions # ------------------------------------------------------------------ # Initial profile is deliberately strict (narrow MW + low LogP cap) so # all_criteria_met is typically 0 on the default library; the brief then # forces a single rescreen with a widened LogP window. RESCREEN_DEMO_TARGET_PROFILE = ( '{"mw": [150, 200], "logp": [-0.5, 1.0], "hbd": [0, 1], ' '"hba": [0, 3], "tpsa": [20, 45]}' ) RESCREEN_DEMO_TARGET_PROFILE_RESCREEN = ( '{"mw": [150, 200], "logp": [-0.5, 3.5], "hbd": [0, 1], ' '"hba": [0, 3], "tpsa": [20, 45]}' ) RESCREEN_DEMO_BRIEF = f"""\ Two-round agentic screening demo on the default library. **Round 1 (strict profile):** load_molecules โ†’ compute_properties โ†’ \ screen_candidates โ†’ generate_report using the initial target_profile exactly. **Round 2 (required โ€” do not skip):** call screen_candidates then generate_report \ again, reusing the same molecule_dir and properties_json from round 1, with this \ relaxed target_profile (wider LogP window only): \ {RESCREEN_DEMO_TARGET_PROFILE_RESCREEN} Pass every tool return value verbatim to the next step. After both rounds, \ summarize how the funnel and top candidates changed between round 1 and round 2.""" # {{docs-fragment rescreen_demo}} @env.task(report=True) async def rescreen_demo() -> str: """Example run with a two-round execution graph (rescreen). Round 1 uses a strict CNS-like profile; round 2 always re-runs screen_candidates and generate_report with a widened LogP window, reusing cached molecule_dir and properties_json. """ return await pipeline( brief=RESCREEN_DEMO_BRIEF, target_profile=RESCREEN_DEMO_TARGET_PROFILE, ) # {{/docs-fragment rescreen_demo}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(pipeline) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/drug_molecule_screening/drug_molecule_screening.py* ``` flyte run drug_molecule_screening.py rescreen_demo ``` Or pass the same inputs to `pipeline` directly: ``` flyte run drug_molecule_screening.py pipeline \ --brief "Screen the default library. If all_criteria_met is 0 after generate_report, re-run screen_candidates and generate_report with target_profile {\"mw\": [150, 200], \"logp\": [-0.5, 3.5], \"hbd\": [0, 1], \"hba\": [0, 3], \"tpsa\": [20, 45]}." \ --target_profile '{"mw": [150, 200], "logp": [-0.5, 1.0], "hbd": [0, 1], "hba": [0, 3], "tpsa": [20, 45]}' ``` Open the run URL and follow the report panel for funnel charts, property distributions, top-candidate spotlights, and the agent's final screening summary. A successful rescreen demo shows two rounds of `screen_candidates` and `generate_report` in the action tree. === PAGE: https://www.union.ai/docs/v2/union/tutorials/geospatial === Satellite imagery, remote sensing, and earth and atmospheric modeling workloads. # Geospatial Tutorials for satellite imagery, remote sensing, and earth and atmospheric modeling workloads. ### **Geospatial > GPU-accelerated climate modeling** Run ensemble atmospheric simulations on H200 GPUs with multi-source data ingestion and real-time extreme event detection. ### **Geospatial > Satellite image classification** Build a production-grade EfficientNet pipeline for land-use classification with caching, experiment tracking, and reporting. ## Subpages - **Geospatial > GPU-accelerated climate modeling** - Run ensemble atmospheric simulations on H200 GPUs with multi-source data ingestion and real-time extreme event detection. - **Geospatial > Satellite image classification** - Build a production-grade EfficientNet pipeline for land-use classification with caching, experiment tracking, and reporting. === PAGE: https://www.union.ai/docs/v2/union/tutorials/geospatial/climate-modeling === Run ensemble atmospheric simulations on H200 GPUs with multi-source data ingestion and real-time extreme event detection. # GPU-accelerated climate modeling Climate modeling is hard for two reasons: data and compute. Satellite imagery arrives continuously from multiple sources. Reanalysis datasets have to be pulled from remote APIs. Weather station data shows up in different formats and schemas. And once all of that is finally in one place, running atmospheric physics simulations demands serious GPU compute. In practice, many climate workflows are held together with scripts, cron jobs, and a lot of manual babysitting. Data ingestion breaks without warning. GPU jobs run overnight with little visibility into what's happening. When something interesting shows up in a simulation, like a developing hurricane, no one notices until the job finishes hours later. In this tutorial, we build a production-grade climate modeling pipeline using Flyte. We ingest data from three different sources in parallel, combine it with Dask, run ensemble atmospheric simulations on H200 GPUs, detect extreme weather events as they emerge, and visualize everything in a live dashboard. The entire pipeline is orchestrated, cached, and fault-tolerant, so it can run reliably at scale. ![Report](../../../_static/images/tutorials/climate-modeling/report.png) > [!NOTE] > Full code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/climate_modeling/simulation.py). ## Overview We're building an ensemble weather forecasting system. Ensemble forecasting runs the same simulation multiple times with slightly different initial conditions. This quantifies forecast uncertainty. Instead of saying "the temperature will be 25ยฐC", we can say "the temperature will be 24-26ยฐC with 90% confidence". The pipeline has five stages: 1. **Data ingestion**: Pull satellite imagery from NOAA GOES, reanalysis data from ERA5, and surface observations from weather stations in parallel. 2. **Preprocessing**: Fuse the datasets, interpolate to a common grid, and run quality control using Dask for distributed computation. 3. **GPU simulation**: Run ensemble atmospheric physics on H200 GPUs. Each ensemble member evolves independently. PyTorch handles the tensor operations; `torch.compile` optimizes the kernels. 4. **Event detection**: Monitor for hurricanes (high wind + low pressure) and heatwaves during simulation. When extreme events are detected, the pipeline can adaptively refine the grid resolution. 5. **Real-time reporting**: Stream metrics to a live Flyte Reports dashboard showing convergence and detected events. This workflow is a good example of where Flyte shines! - **Parallel data ingestion**: Three different data sources, three different APIs, all running concurrently. Flyte's async task execution handles this naturally. - **Resource heterogeneity**: Data ingestion needs CPU and network. Preprocessing needs a Dask cluster. Simulation needs GPUs. Flyte provisions exactly what each stage needs. - **Caching**: ERA5 data fetches can take minutes. Run the pipeline twice with the same date range, and Flyte skips the fetch entirely. - **Adaptive workflows**: When a hurricane is detected, we can dynamically refine the simulation. Flyte makes this kind of conditional logic straightforward. ## Implementation ### Dependencies and container image ``` import asyncio import gc import io import json import os import tempfile from dataclasses import dataclass from datetime import datetime, timedelta from typing import Literal import flyte import numpy as np import pandas as pd import xarray as xr from flyte.io import File from flyteplugins.dask import Dask, Scheduler, WorkerGroup ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* The key imports include `xarray` for multi-dimensional climate data, `flyteplugins.dask` for distributed preprocessing, and `flyte` for orchestration. ``` climate_image = ( flyte.Image.from_debian_base(name="climate_modeling_h200") .with_apt_packages( "libnetcdf-dev", # NetCDF for climate data "libhdf5-dev", # HDF5 for large datasets "libeccodes-dev", # GRIB format support (ECMWF's native format) "libudunits2-dev", # Unit conversions ) .with_pip_packages( "numpy==2.3.5", "pandas==2.3.3", "xarray==2025.11.0", "torch==2.9.1", "netCDF4==1.7.3", "s3fs==2025.10.0", "aiohttp==3.13.2", "ecmwf-datastores-client==0.4.1", "h5netcdf==1.7.3", "cfgrib==0.9.15.1", "pyarrow==22.0.0", "scipy==1.15.1", "flyteplugins-dask>=2.0.0b33", "nvidia-ml-py3==7.352.0", ) .with_env_vars({"PYTORCH_CUDA_ALLOC_CONF": "max_split_size_mb:512"}) ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* Climate data comes in specialized formats such as NetCDF, HDF5, and GRIB. The container image includes libraries to work with all of them, along with PyTorch for GPU computation and the ECMWF client for accessing ERA5 data. ### Simulation parameters and data structures ``` @dataclass class SimulationParams: grid_resolution_km: float = 10.0 time_step_minutes: int = 10 simulation_hours: int = 240 physics_model: Literal["WRF", "MPAS", "CAM"] = "WRF" boundary_layer_scheme: str = "YSU" microphysics_scheme: str = "Thompson" radiation_scheme: str = "RRTMG" # Ensemble forecasting parameters ensemble_size: int = 800 perturbation_magnitude: float = 0.5 # Convergence criteria for adaptive refinement convergence_threshold: float = 0.1 # 10% of initial ensemble spread max_iterations: int = 3 @dataclass class ClimateMetrics: timestamp: str iteration: int convergence_rate: float energy_conservation_error: float max_wind_speed_mps: float min_pressure_mb: float detected_phenomena: list[str] compute_time_seconds: float ensemble_spread: float @dataclass class SimulationSummary: total_iterations: int final_resolution_km: float avg_convergence_rate: float total_compute_time_seconds: float hurricanes_detected: int heatwaves_detected: int converged: bool region: str output_files: list[File] date_range: list[str, str] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* `SimulationParams` defines the core behavior of the simulation, including grid resolution, physics schemes, and ensemble size. The default configuration runs 800 ensemble members, which is sufficient to produce statistically meaningful uncertainty estimates. > [!NOTE] > Decreasing the grid spacing via `grid_resolution_km` (for example, from 10 km to 5 km) increases grid resolution and significantly increases memory usage because it introduces more data points and intermediate state. Even with 141 GB of H200 GPU memory, high-resolution or adaptively refined simulations may exceed available VRAM, especially when running large ensembles. > > To mitigate this, consider reducing the ensemble size, limiting the refined region, running fewer physics variables, or scaling the simulation across more GPUs so memory is distributed more evenly. `ClimateMetrics` collects diagnostics at each iteration, such as convergence rate, energy conservation, and detected phenomena. These metrics are streamed to the real-time dashboard so you can monitor how the simulation evolves as it runs. ### Task environments Different stages need different resources. Flyte's `TaskEnvironment` declares exactly what each task requires: ``` gpu_env = flyte.TaskEnvironment( name="climate_modeling_gpu", resources=flyte.Resources( cpu=5, memory="130Gi", gpu="H200:1", ), image=climate_image, cache="auto", ) dask_env = flyte.TaskEnvironment( name="climate_modeling_dask", plugin_config=Dask( scheduler=Scheduler(resources=flyte.Resources(cpu=2, memory="6Gi")), workers=WorkerGroup( number_of_workers=2, resources=flyte.Resources(cpu=2, memory="12Gi"), ), ), image=climate_image, resources=flyte.Resources(cpu=2, memory="12Gi"), # Head node cache="auto", ) cpu_env = flyte.TaskEnvironment( name="climate_modeling_cpu", resources=flyte.Resources(cpu=8, memory="64Gi"), image=climate_image, cache="auto", secrets=[ flyte.Secret(key="cds_api_key", as_env_var="ECMWF_DATASTORES_KEY"), flyte.Secret(key="cds_api_url", as_env_var="ECMWF_DATASTORES_URL"), ], depends_on=[gpu_env, dask_env], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* Hereโ€™s what each environment is responsible for: - **`gpu_env`**: Runs the atmospheric simulations on H200 GPUs. The 130 GB of GPU memory is used to hold the ensemble members in VRAM during execution. - **`dask_env`**: Provides a distributed Dask cluster for preprocessing. A scheduler and multiple workers handle data fusion and transformation in parallel. - **`cpu_env`**: Handles data ingestion and orchestration. This environment also includes the secrets required to access the ERA5 API. The `depends_on` setting on `cpu_env` ensures that Flyte builds the GPU and Dask images first. Once those environments are ready, the orchestration task can launch the specialized simulation and preprocessing tasks. ### Data ingestion: multiple sources in parallel Climate models need data from multiple sources. Each source has different formats, APIs, and failure modes. We handle them as separate Flyte tasks that run concurrently. **Satellite imagery from NOAA GOES** ``` @cpu_env.task async def ingest_satellite_data(region: str, date_range: list[str, str]) -> File: """Ingest GOES satellite imagery from NOAA's public S3 buckets.""" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* This task fetches cloud imagery and precipitable water products from NOAA's public S3 buckets. GOES-16 covers the Atlantic; GOES-17 covers the Pacific. The task selects the appropriate satellite based on region, fetches multiple days in parallel using `asyncio.gather`, and combines everything into a single xarray Dataset. **ERA5 reanalysis from Copernicus** ``` @cpu_env.task async def ingest_reanalysis_data(region: str, date_range: list[str, str]) -> File: """Fetch ERA5 reanalysis from Copernicus Climate Data Store.""" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* ERA5 provides 3D atmospheric fields such as temperature, wind, humidity at multiple pressure levels from surface to stratosphere. The ECMWF datastores client handles authentication via Flyte secrets. Each day fetches in parallel, then gets concatenated. **Surface observations from weather stations:** ``` @cpu_env.task async def ingest_station_data( region: str, date_range: list[str, str], max_stations: int = 100 ) -> File: """Fetch ground observations from NOAA's Integrated Surface Database.""" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* Ground truth comes from NOAA's Integrated Surface Database. The task filters stations by geographic bounds, fetches hourly observations, and returns a Parquet file for efficient downstream processing. All three tasks return Flyte `File` objects that hold references to data in blob storage. No data moves until a downstream task actually needs it. ### Preprocessing with Dask The three data sources need to be combined into a unified atmospheric state. This means: - Interpolating to a common grid - Handling missing values - Merging variables from different sources - Quality control This is a perfect fit for Dask to handle lazy evaluation over chunked arrays: ```python @dask_env.task async def preprocess_atmospheric_data( satellite_data: File, reanalysis_data: File, station_data: File, target_resolution_km: float, ) -> File: ``` This task connects to the Dask cluster provisioned by Flyte, loads the datasets with appropriate chunking, merges satellite and reanalysis grids, fills in missing values, and persists the result. Flyte caches the output, so preprocessing only runs when the inputs change. ### GPU-accelerated atmospheric simulation Now the core: running atmospheric physics on the GPU. Each ensemble member is an independent forecast with slightly perturbed initial conditions. ``` @gpu_env.task async def run_atmospheric_simulation( input_data: File, params: SimulationParams, partition_id: int = 0, ensemble_start: int | None = None, ensemble_end: int | None = None, ) -> tuple[File, ClimateMetrics]: """Run GPU-accelerated atmospheric simulation with ensemble forecasting.""" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* The task accepts a subset of ensemble members (`ensemble_start` to `ensemble_end`). This enables distributing 800 members across multiple GPUs. The physics step is the computational kernel. It runs advection (wind transport), pressure gradients, Coriolis forces, turbulent diffusion, and moisture condensation: ``` @torch.compile(mode="reduce-overhead") def physics_step(state_tensor, dt_val, dx_val): """Compiled atmospheric physics - 3-4x faster with torch.compile.""" # Advection: transport by wind temp_grad_x = torch.roll(state_tensor[:, 0], -1, dims=2) - torch.roll( state_tensor[:, 0], 1, dims=2 ) temp_grad_y = torch.roll(state_tensor[:, 0], -1, dims=3) - torch.roll( state_tensor[:, 0], 1, dims=3 ) advection = -( state_tensor[:, 3] * temp_grad_x + state_tensor[:, 4] * temp_grad_y ) / (2 * dx_val) state_tensor[:, 0] = state_tensor[:, 0] + advection * dt_val # Pressure gradient with Coriolis pressure_grad_x = ( torch.roll(state_tensor[:, 1], -1, dims=2) - torch.roll(state_tensor[:, 1], 1, dims=2) ) / (2 * dx_val) pressure_grad_y = ( torch.roll(state_tensor[:, 1], -1, dims=3) - torch.roll(state_tensor[:, 1], 1, dims=3) ) / (2 * dx_val) coriolis_param = 1e-4 # ~45ยฐN latitude coriolis_u = coriolis_param * state_tensor[:, 4] coriolis_v = -coriolis_param * state_tensor[:, 3] state_tensor[:, 3] = ( state_tensor[:, 3] - pressure_grad_x * dt_val * 0.01 + coriolis_u * dt_val ) state_tensor[:, 4] = ( state_tensor[:, 4] - pressure_grad_y * dt_val * 0.01 + coriolis_v * dt_val ) # Turbulent diffusion diffusion_coeff = 10.0 laplacian_temp = ( torch.roll(state_tensor[:, 0], 1, dims=2) + torch.roll(state_tensor[:, 0], -1, dims=2) + torch.roll(state_tensor[:, 0], 1, dims=3) + torch.roll(state_tensor[:, 0], -1, dims=3) - 4 * state_tensor[:, 0] ) / (dx_val * dx_val) state_tensor[:, 0] = ( state_tensor[:, 0] + diffusion_coeff * laplacian_temp * dt_val ) # Moisture condensation sat_vapor_pressure = 611.2 * torch.exp( 17.67 * state_tensor[:, 0] / (state_tensor[:, 0] + 243.5) ) condensation = torch.clamp( state_tensor[:, 2] - sat_vapor_pressure * 0.001, min=0 ) state_tensor[:, 2] = state_tensor[:, 2] - condensation * 0.1 state_tensor[:, 0] = state_tensor[:, 0] + condensation * 2.5e6 / 1005 * dt_val return state_tensor ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* `@torch.compile(mode="reduce-overhead")` compiles this function into optimized CUDA kernels. Combined with mixed precision (`torch.cuda.amp.autocast`), this runs 3-4x faster than eager PyTorch. Every 10 timesteps, the simulation checks for extreme events: - **Hurricanes**: Wind speed > 33 m/s with low pressure - **Heatwaves**: Temperature anomalies exceeding thresholds Detected phenomena get logged to the metrics, which flow to the live dashboard. ### Distributing across multiple GPUs 800 ensemble members is a lot for one GPU, so we distribute them: ``` @cpu_env.task async def run_distributed_simulation_ensemble( preprocessed_data: File, params: SimulationParams, n_gpus: int ) -> tuple[list[File], list[ClimateMetrics]]: total_members = params.ensemble_size members_per_gpu = total_members // n_gpus # Distribute ensemble members across GPUs tasks = [] for gpu_id in range(n_gpus): # Calculate ensemble range for this GPU ensemble_start = gpu_id * members_per_gpu # Last GPU gets any remainder members if gpu_id == n_gpus - 1: ensemble_end = total_members else: ensemble_end = ensemble_start + members_per_gpu # Launch GPU task with ensemble subset gpu_task = run_atmospheric_simulation( preprocessed_data, params, gpu_id, ensemble_start=ensemble_start, ensemble_end=ensemble_end, ) tasks.append(gpu_task) # Execute all GPUs in parallel results = await asyncio.gather(*tasks) output_files = [r[0] for r in results] metrics = [r[1] for r in results] return output_files, metrics ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* The task splits the ensemble members evenly across the available GPUs, launches the simulation runs in parallel using `asyncio.gather`, and then aggregates the results. With five GPUs, each GPU runs 160 ensemble members. Flyte takes care of scheduling, so GPU tasks start automatically as soon as resources become available. ### The main workflow Everything comes together in the orchestration task: ``` @cpu_env.task(report=True) async def adaptive_climate_modeling_workflow( region: str = "atlantic", date_range: list[str, str] = ["2024-09-01", "2024-09-10"], current_params: SimulationParams = SimulationParams(), enable_multi_gpu: bool = True, n_gpus: int = 5, ) -> SimulationSummary: """Orchestrates multi-source ingestion, GPU simulation, and adaptive refinement.""" ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* `report=True` enables Flyte Reports for live monitoring. ``` # Parallel data ingestion from three sources with flyte.group("data-ingestion"): satellite_task = ingest_satellite_data(region, date_range) reanalysis_task = ingest_reanalysis_data(region, date_range) station_task = ingest_station_data(region, date_range) satellite_data, reanalysis_data, station_data = await asyncio.gather( satellite_task, reanalysis_task, station_task, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* `flyte.group("data-ingestion")` visually groups the ingestion tasks in the Flyte UI. Inside the group, three tasks launch concurrently. `asyncio.gather` waits for all three to complete before preprocessing begins. The workflow then enters an iterative loop: 1. Run GPU simulation (single or multi-GPU) 2. Check convergence by comparing forecasts across iterations 3. Detect extreme events 4. If a hurricane is detected and we haven't refined yet, double the grid resolution 5. Stream metrics to the live dashboard 6. Repeat until converged or max iterations reached Adaptive mesh refinement is the key feature here. When the simulation detects a hurricane forming, it automatically increases resolution to capture the fine-scale dynamics. This is expensive, so we limit it to one refinement per run. ### Running the pipeline ``` if __name__ == "__main__": flyte.init_from_config() run_multi_gpu = flyte.run(adaptive_climate_modeling_workflow) print(f"Run URL: {run_multi_gpu.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/climate_modeling/simulation.py* Before running, set up ERA5 API credentials: ```bash flyte create secret cds_api_key --value flyte create secret cds_api_url --value https://cds.climate.copernicus.eu/api ``` Then launch: ```bash flyte create config --endpoint --project --domain --builder remote uv run simulation.py ``` The default configuration uses the Atlantic region for September 2024, which is hurricane season. ## Key concepts ### Ensemble forecasting Weather prediction is inherently uncertain. Small errors in the initial conditions grow over time due to chaotic dynamics, which means a single forecast can only ever be one possible outcome. Ensemble forecasting addresses this uncertainty by: - Perturbing the initial conditions within known observational error bounds - Running many independent forecasts - Computing the ensemble mean as the most likely outcome and the ensemble spread as a measure of uncertainty ### Adaptive mesh refinement When a hurricane begins to form, coarse spatial grids are not sufficient to resolve critical features like eyewall dynamics. Adaptive mesh refinement allows the simulation to focus compute where it matters most by: - Increasing grid resolution, for example from 10 km to 5 km - Reducing the timestep to maintain numerical stability - Refining only the regions of interest instead of the entire domain This approach is computationally expensive, but it is essential for producing accurate intensity forecasts. ### Real-time event detection Rather than analyzing results after a simulation completes, this pipeline detects significant events as the simulation runs. The system monitors for conditions such as: - **Hurricanes**: Wind speeds exceeding 33 m/s (Category 1 threshold) combined with central pressure below 980 mb - **Heatwaves**: Sustained temperature anomalies over a defined period Detecting these events in real time enables adaptive responses, such as refining the simulation or triggering alerts, and supports earlier warnings for extreme weather. ## Where to go next This example is intentionally scoped to keep the ideas clear, but there are several natural ways to extend it for more realistic workloads. To model different ocean basins, change the `region` parameter to values like `"pacific"` or `"indian"`. The ingestion tasks automatically adjust to pull the appropriate satellite coverage for each region. To run longer forecasts, increase `simulation_hours` in `SimulationParams`. The default of 240 hours, or 10 days, is typical for medium-range forecasting, but you can run longer simulations if you have the compute budget. Finally, the physics step here is deliberately simplified. Production systems usually incorporate additional components such as radiation schemes, boundary layer parameterizations, and land surface models. These can be added incrementally as separate steps without changing the overall structure of the pipeline. === PAGE: https://www.union.ai/docs/v2/union/tutorials/geospatial/satellite_image_classification === Build a production-grade EfficientNet pipeline for land-use classification with caching, experiment tracking, and reporting. # Satellite image classification ![Satellite Image](../../../_static/images/tutorials/satellite_image_classification/satellite_image.png) ## Background Remote sensing has transformed how we monitor our planet. From tracking deforestation to detecting urban sprawl, satellite imagery provides a bird's-eye view of land use change at global scale. But training a model that can reliably classify that imagery (across 10 distinct land-use categories, at production quality) requires more than just a good model. It requires a pipeline that handles data, compute, caching, experiment tracking, and reporting as first-class concerns. This tutorial walks through a complete satellite image classification pipeline built on Union.ai, using EfficientNet-B0, a two-phase training strategy, and Weights & Biases for experiment tracking. > [!NOTE] > Full code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/satellite_image_classification). ## Dataset [EuroSAT](https://github.com/phelber/EuroSAT) is a benchmark dataset of 27,000 labeled satellite images drawn from the Sentinel-2 satellite. Each image is 64ร—64 pixels across 10 land-use classes: Annual Crop, Forest, Herbaceous Vegetation, Highway, Industrial, Pasture, Permanent Crop, Residential, River, and Sea/Lake. It's a well-structured dataset - balanced, clearly labeled - which makes it ideal for demonstrating a production-grade training pipeline without the overhead of massive data infrastructure. ## Model We use EfficientNet-B0 from `timm` (the PyTorch Image Models library), pretrained on ImageNet. EfficientNet was designed to scale depth, width, and resolution jointly using a compound coefficient, giving strong accuracy with a relatively small parameter count (~5.3M). The ImageNet pretraining means the backbone already understands edges, textures, and shapes - features that transfer well to satellite imagery. ## Two-phase training Fine-tuning a pretrained model naively by using all weights immediately often leads to catastrophic forgetting: the model destroys its learned representations before the new task-specific head has had a chance to stabilize. Instead, we use a two-phase approach: **Phase 1: Feature Extraction (frozen backbone).** The EfficientNet backbone is frozen. Only the classification head is trained, at a relatively high learning rate (2e-3). This gives the head 7 epochs to learn to map ImageNet features to EuroSAT categories, without disturbing the pretrained weights. **Phase 2: Fine-tuning (unfrozen backbone).** The backbone is unfrozen and added to the optimizer with a 10ร— lower learning rate than the head (`phase2_lr` ร— 0.1). A fresh cosine annealing schedule is initialized over the remaining steps, so the learning rate doesn't arrive near-zero from Phase 1's schedule before Phase 2 even begins. This lets the backbone adapt to satellite-specific features while preserving the general representations it learned on ImageNet. The transition happens automatically inside a `PhaseChangeCallback`: ``` class PhaseChangeCallback(L.Callback): def __init__(self, phase1_epochs: int, phase2_lr: float): super().__init__() self.phase1_epochs = phase1_epochs self.phase2_lr = phase2_lr self.phase_changed = False def on_train_epoch_end(self, trainer, pl_module): if not self.phase_changed and (trainer.current_epoch + 1) == self.phase1_epochs: print("\n" + "=" * 80) print("TRANSITIONING TO PHASE 2: UNFREEZING BACKBONE AND ADJUSTING LR") print("=" * 80 + "\n") pl_module.model.unfreeze_backbone() for param_group in trainer.optimizers[0].param_groups: param_group["lr"] = self.phase2_lr # Add backbone params to optimizer with 10x lower LR. # Backbone was excluded at init because it was frozen. backbone_lr = self.phase2_lr * 0.1 backbone_decay, backbone_no_decay = [], [] for param in pl_module.model.backbone.parameters(): if param.ndim >= 2: backbone_decay.append(param) else: backbone_no_decay.append(param) optimizer = trainer.optimizers[0] optimizer.add_param_group({"params": backbone_decay, "lr": backbone_lr, "weight_decay": pl_module.weight_decay}) optimizer.add_param_group({"params": backbone_no_decay, "lr": backbone_lr, "weight_decay": 0.0}) # Fresh cosine schedule over remaining Phase 2 steps to avoid # the Phase 1 schedule arriving near-zero before Phase 2 begins. steps_remaining = trainer.estimated_stepping_batches - trainer.global_step new_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( trainer.optimizers[0], T_max=max(1, steps_remaining), eta_min=1e-6, ) for lr_scheduler_config in trainer.lr_scheduler_configs: lr_scheduler_config.scheduler = new_scheduler print(f"Phase 2 started: lr={self.phase2_lr}") print(f"Total parameters: {get_model_size(pl_module.model):,}") print(f"Trainable parameters: {get_trainable_params(pl_module.model):,}") self.phase_changed = True ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/satellite_image_classification/training.py* This two-phase strategy consistently reaches >95% validation accuracy on EuroSAT within 17 total epochs. ## Pipeline Training a model is only part of the story. The real challenge is building a system that is reproducible, cost-efficient, and easy to iterate on. That's where Union's `TaskEnvironment` model shines: each stage of the pipeline runs in the right compute environment, and results are cached so you never pay for work you've already done. The pipeline has four components, each with its own environment defined in `config.py`. ### Task 1: Data download (`dataset_env`) ``` @dataset_env.task async def load_dataset() -> Dir: """ Download raw EuroSAT JPEG files and cache as flyte.io.Dir. Runs once โ€” result is reused on subsequent pipeline runs (cache="auto"). """ return await download_eurosat() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/satellite_image_classification/run.py* This task downloads the raw EuroSAT JPEG files via torchvision and packages them as a `flyte.io.Dir`. It runs on a lightweight CPU container (2 cores, 2 GB RAM) - no GPU needed. With `cache="auto"`, the result is stored and reused on every subsequent run. You pay for the download exactly once. No preprocessing happens here. Raw images are passed directly to training so that all transforms - resize, normalization, and augmentation - happen per-batch with the full training context, giving the model properly prepared 224ร—224 input from the original pixels. ### Task 2: GPU training (`training_env`) ``` @wandb_init @training_env.task async def train_model(dataset_dir: Dir, config: TrainingConfig) -> Dir: """ Download the raw dataset Dir, run two-phase training, and return training metrics as a Dir for the report task. """ from pathlib import Path local_dir = Path("/tmp/eurosat_local") local_dir.mkdir(parents=True, exist_ok=True) await dataset_dir.download(local_path=str(local_dir)) result = train_satellite_classifier(config=config, dataset_path=str(local_dir)) output_dir = Path("/tmp/training_results") output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "metrics.json").write_text(json.dumps(result["metrics"])) return await Dir.from_local(str(output_dir)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/satellite_image_classification/run.py* This task runs on a T4 GPU with 32 GB RAM. It receives the dataset `Dir` from Task 1, downloads it locally, then runs the two-phase training loop using PyTorch Lightning. Two things worth noting: - With `cache="auto"`, training results are cached based on the input data and config. If you rerun the pipeline with the same dataset and hyperparameters, Union skips training entirely and returns the cached metrics. This makes hyperparameter search much cheaper: only configurations you haven't tried before actually execute. - `@wandb_init`: the `flyteplugins-wandb` integration initializes a W&B run automatically and makes it available via `get_wandb_run()`. This means every training run automatically logs metrics, learning rate curves, and t-SNE visualizations of the learned feature space to your W&B project. ``` wandb_logger = WandbLogger(experiment=get_wandb_run(), log_model=False) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/satellite_image_classification/training.py* ### Task 3: Report generation (`report_env`) This task reads the `metrics.json` produced by training and renders interactive Plotly charts - validation accuracy and train/val loss curves - directly in the Union UI. The `report=True` flag tells Union to render the task output as a rich report panel. A dashed vertical line marks the Phase 1 โ†’ Phase 2 transition, making it easy to see how much the backbone fine-tuning contributes. ``` @report_env.task(report=True) async def create_report(results_dir: Dir) -> None: """ Download training metrics and render loss/accuracy curves in the Union UI report panel. """ import plotly.graph_objects as go from pathlib import Path local_dir = Path("/tmp/training_report") local_dir.mkdir(parents=True, exist_ok=True) await results_dir.download(local_path=str(local_dir)) matches = list(local_dir.glob("**/metrics.json")) if not matches: raise RuntimeError(f"metrics.json not found under {local_dir}") local_path = matches[0].parent history = json.loads((local_path / "metrics.json").read_text()) epochs = [e["epoch"] for e in history] val_acc = [e["val_acc"] for e in history] val_loss = [e["val_loss"] for e in history] train_loss = [e["train_loss"] for e in history] # phase_boundary: first epoch where phase 2 begins (frozen โ†’ fine-tune transition) phase_boundary = next((e["epoch"] for e in history if e["phase"] == 2), None) def add_phase_line(fig): if phase_boundary is not None: fig.add_vline( x=phase_boundary, line_dash="dash", line_color="gray", annotation_text="Phase 2 start", ) acc_fig = go.Figure() acc_fig.add_trace(go.Scatter(x=epochs, y=val_acc, mode="lines+markers", name="Val Accuracy")) acc_fig.update_layout(title="Validation Accuracy", xaxis_title="Epoch", yaxis_title="Accuracy") add_phase_line(acc_fig) loss_fig = go.Figure() loss_fig.add_trace(go.Scatter(x=epochs, y=train_loss, mode="lines+markers", name="Train Loss")) loss_fig.add_trace(go.Scatter(x=epochs, y=val_loss, mode="lines+markers", name="Val Loss")) loss_fig.update_layout(title="Loss", xaxis_title="Epoch", yaxis_title="Loss") add_phase_line(loss_fig) combined_html = ( acc_fig.to_html(include_plotlyjs=True, full_html=False) + loss_fig.to_html(include_plotlyjs=False, full_html=False) ) flyte.report.log(combined_html, do_flush=True) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/satellite_image_classification/run.py* ### Task 4: Orchestration (`pipeline_env`) The pipeline task is a lightweight orchestrator. It has no heavy dependencies of its own, just enough to call the three tasks above in sequence. The `async`/`await` pattern means each task handoff is non-blocking: Union manages scheduling, retries, and data movement between tasks transparently. ``` @pipeline_env.task async def satellite_classification_pipeline(config: TrainingConfig) -> None: """Orchestrate dataset loading, GPU training, and report generation.""" dataset_dir = await load_dataset() results_dir = await train_model( dataset_dir=dataset_dir, config=config, ) await create_report(results_dir=results_dir) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/satellite_image_classification/run.py* ## Running the pipeline Submit the pipeline with a single command from the project directory: ```bash uv run run.py ``` This calls: ``` run = flyte.with_runcontext( custom_context=wandb_config( project=training_config.wandb_project, entity=training_config.wandb_entity, ), ).run(satellite_classification_pipeline, config=training_config) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/satellite_image_classification/run.py* The W&B project and entity are wired in at submission time. Union handles spinning up the right containers, routing data between tasks, and surfacing results in the UI. ## What you get After the pipeline completes: - Union UI: a report panel with interactive accuracy and loss curves, phase transition marker, and full task logs for each stage. ![Validation Accuracy](../../../_static/images/tutorials/satellite_image_classification/validation_accuracy.png) ![Loss](../../../_static/images/tutorials/satellite_image_classification/loss.png) - Weights & Biases: a complete experiment run with validation metrics like loss and accuracy, train loss, and t-SNE visualizations of the model's learned embeddings at configurable epoch intervals. Every few epochs, a t-SNE plot of the validation set embeddings is logged, showing how the model's feature representations evolve over training. Classes that start as an overlapping cloud gradually pull apart into tight, well-separated clusters as the backbone learns satellite-specific features. ![t-SNE Visualization](../../../_static/images/tutorials/satellite_image_classification/tsne.gif) - Model checkpoints: Lightning's `ModelCheckpoint` saves the top 3 best-performing checkpoints by validation accuracy, named `best-{epoch}-{val_acc}.ckpt`. These are standard PyTorch Lightning checkpoints that can be loaded directly for inference. === PAGE: https://www.union.ai/docs/v2/union/tutorials/financial-services === Financial research, trading, and other fintech workloads. # Financial services & fintech Tutorials for financial research, trading, and other fintech workloads. ### **Financial services & fintech > Financial research agent** Prep equity briefings for the earnings cycle with grounded You.com Research synthesis and fresh news from the Search API. ### **Financial services & fintech > Fraud detection with Feast** Train an XGBoost fraud classifier and materialize transaction features in Feast for online scoring. ### **Financial services & fintech > Multi-agent trading simulation** A multi-agent trading simulation, modeling how agents within a firm might interact, strategize, and make trades collaboratively. ## Subpages - **Financial services & fintech > Multi-agent trading simulation** - A multi-agent trading simulation, modeling how agents within a firm might interact, strategize, and make trades collaboratively. - **Financial services & fintech > Fraud detection with Feast** - Train an XGBoost fraud classifier and materialize transaction features in Feast for online scoring. - **Financial services & fintech > Financial research agent** - Prep equity briefings for the earnings cycle with grounded You.com Research synthesis and fresh news from the Search API. === PAGE: https://www.union.ai/docs/v2/union/tutorials/financial-services/trading-agents === A multi-agent trading simulation, modeling how agents within a firm might interact, strategize, and make trades collaboratively. # Multi-agent trading simulation > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/trading_agents); based on work by [TauricResearch](https://github.com/TauricResearch/TradingAgents). This example walks you through building a multi-agent trading simulation, modeling how agents within a firm might interact, strategize, and make trades collaboratively. ![Trading agents execution visualization](../../../_static/images/tutorials/trading-agents/execution.png) _Trading agents execution visualization_ ## TL;DR - You'll build a trading firm made up of agents that analyze, argue, and act, modeled with Python functions. - You'll use the Flyte SDK to orchestrate this world, giving you visibility, retries, caching, and durability. - You'll learn how to plug in tools, structure conversations, and track decisions across agents. - You'll see how agents debate, use context, generate reports, and retain memory via vector DBs. ## What is an agent, anyway? Agentic workflows are a rising pattern for complex problem-solving with LLMs. Think of agents as: - An LLM (like GPT-4 or Mistral) - A loop that keeps them thinking until a goal is met - A set of optional tools they can call (APIs, search, calculators, etc.) - Enough tokens to reason about the problem at hand That's it. You define tools, bind them to an agent, and let it run, reasoning step-by-step, optionally using those tools, until it finishes. ## What's different here? We're not building yet another agent framework. You're free to use LangChain, custom code, or whatever setup you like. What we're giving you is the missing piece: a way to run these workflows **reliably, observably, and at scale, with zero rewrites.** With Flyte, you get: - Prompt + tool traceability and full state retention - Built-in retries, caching, and failure recovery - A native way to plug in your agents; no magic syntax required ## How it works: step-by-step walkthrough This simulation is powered by a Flyte task that orchestrates multiple intelligent agents working together to analyze a company's stock and make informed trading decisions. ![Trading agents schema](../../../_static/images/tutorials/trading-agents/schema.png) _Trading agents schema_ ### Entry point Everything begins with a top-level Flyte task called `main`, which serves as the entry point to the workflow. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # "akshare==1.16.98", # "backtrader==1.9.78.123", # "boto3==1.39.9", # "chainlit==2.5.5", # "eodhd==1.0.32", # "feedparser==6.0.11", # "finnhub-python==2.4.23", # "langchain-experimental==0.3.4", # "langchain-openai==0.3.23", # "pandas==2.3.0", # "parsel==1.10.0", # "praw==7.8.1", # "pytz==2025.2", # "questionary==2.1.0", # "redis==6.2.0", # "requests==2.32.4", # "stockstats==0.6.5", # "tqdm==4.67.1", # "tushare==1.4.21", # "typing-extensions==4.14.0", # "yfinance==0.2.63", # ] # main = "main" # params = "" # /// import asyncio from copy import deepcopy import agents import agents.analysts from agents.managers import create_research_manager, create_risk_manager from agents.researchers import create_bear_researcher, create_bull_researcher from agents.risk_debators import ( create_neutral_debator, create_risky_debator, create_safe_debator, ) from agents.trader import create_trader from agents.utils.utils import AgentState from flyte_env import DEEP_THINKING_LLM, QUICK_THINKING_LLM, env, flyte from langchain_openai import ChatOpenAI from reflection import ( reflect_bear_researcher, reflect_bull_researcher, reflect_research_manager, reflect_risk_manager, reflect_trader, ) @env.task async def process_signal(full_signal: str, QUICK_THINKING_LLM: str) -> str: """Process a full trading signal to extract the core decision.""" messages = [ { "role": "system", "content": """You are an efficient assistant designed to analyze paragraphs or financial reports provided by a group of analysts. Your task is to extract the investment decision: SELL, BUY, or HOLD. Provide only the extracted decision (SELL, BUY, or HOLD) as your output, without adding any additional text or information.""", }, {"role": "human", "content": full_signal}, ] return ChatOpenAI(model=QUICK_THINKING_LLM).invoke(messages).content async def run_analyst(analyst_name, state, online_tools): # Create a copy of the state for isolation run_fn = getattr(agents.analysts, f"create_{analyst_name}_analyst") # Run the analyst's chain result_state = await run_fn(QUICK_THINKING_LLM, state, online_tools) # Determine the report key report_key = ( "sentiment_report" if analyst_name == "social_media" else f"{analyst_name}_report" ) report_value = getattr(result_state, report_key) return result_state.messages[1:], report_key, report_value # {{docs-fragment main}} @env.task async def main( selected_analysts: list[str] = [ "market", "fundamentals", "news", "social_media", ], max_debate_rounds: int = 1, max_risk_discuss_rounds: int = 1, online_tools: bool = True, company_name: str = "NVDA", trade_date: str = "2024-05-12", ) -> tuple[str, AgentState]: if not selected_analysts: raise ValueError( "No analysts selected. Please select at least one analyst from market, fundamentals, news, or social_media." ) state = AgentState( messages=[{"role": "human", "content": company_name}], company_of_interest=company_name, trade_date=str(trade_date), ) # Run all analysts concurrently results = await asyncio.gather( *[ run_analyst(analyst, deepcopy(state), online_tools) for analyst in selected_analysts ] ) # Flatten and append all resulting messages into the shared state for messages, report_attr, report in results: state.messages.extend(messages) setattr(state, report_attr, report) # Bull/Bear debate loop state = await create_bull_researcher(QUICK_THINKING_LLM, state) # Start with bull while state.investment_debate_state.count < 2 * max_debate_rounds: current = state.investment_debate_state.current_response if current.startswith("Bull"): state = await create_bear_researcher(QUICK_THINKING_LLM, state) else: state = await create_bull_researcher(QUICK_THINKING_LLM, state) state = await create_research_manager(DEEP_THINKING_LLM, state) state = await create_trader(QUICK_THINKING_LLM, state) # Risk debate loop state = await create_risky_debator(QUICK_THINKING_LLM, state) # Start with risky while state.risk_debate_state.count < 3 * max_risk_discuss_rounds: speaker = state.risk_debate_state.latest_speaker if speaker == "Risky": state = await create_safe_debator(QUICK_THINKING_LLM, state) elif speaker == "Safe": state = await create_neutral_debator(QUICK_THINKING_LLM, state) else: state = await create_risky_debator(QUICK_THINKING_LLM, state) state = await create_risk_manager(DEEP_THINKING_LLM, state) decision = await process_signal(state.final_trade_decision, QUICK_THINKING_LLM) return decision, state # {{/docs-fragment main}} # {{docs-fragment reflect_on_decisions}} @env.task async def reflect_and_store(state: AgentState, returns: str) -> str: await asyncio.gather( reflect_bear_researcher(state, returns), reflect_bull_researcher(state, returns), reflect_trader(state, returns), reflect_risk_manager(state, returns), reflect_research_manager(state, returns), ) return "Reflection completed." # Run the reflection task after the main function @env.task(cache="disable") async def reflect_on_decisions( returns: str, selected_analysts: list[str] = [ "market", "fundamentals", "news", "social_media", ], max_debate_rounds: int = 1, max_risk_discuss_rounds: int = 1, online_tools: bool = True, company_name: str = "NVDA", trade_date: str = "2024-05-12", ) -> str: _, state = await main( selected_analysts, max_debate_rounds, max_risk_discuss_rounds, online_tools, company_name, trade_date, ) return await reflect_and_store(state, returns) # {{/docs-fragment reflect_on_decisions}} # {{docs-fragment execute_main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main) print(run.url) run.wait() # run = flyte.run(reflect_on_decisions, "+3.2% gain over 5 days") # print(run.url) # {{/docs-fragment execute_main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/main.py* This task accepts several inputs: - the list of analysts to run, - the number of debate and risk discussion rounds, - a flag to enable online tools, - the company you're evaluating, - and the target trading date. The most interesting parameter here is the list of analysts to run. It determines which analyst agents will be invoked and shapes the overall structure of the simulation. Based on this input, the task dynamically launches agent tasks, running them in parallel. The `main` task is written as a regular asynchronous Python function wrapped with Flyte's task decorator. No domain-specific language or orchestration glue is needed: just idiomatic Python, optionally using async for better performance. The task environment is configured once and shared across all tasks for consistency. ``` # {{docs-fragment env}} import flyte QUICK_THINKING_LLM = "gpt-4o-mini" DEEP_THINKING_LLM = "o4-mini" env = flyte.TaskEnvironment( name="trading-agents", secrets=[ flyte.Secret(key="finnhub_api_key", as_env_var="FINNHUB_API_KEY"), flyte.Secret(key="openai_api_key", as_env_var="OPENAI_API_KEY"), ], image=flyte.Image.from_uv_script("main.py", name="trading-agents", pre=True), resources=flyte.Resources(cpu="1"), cache="auto", ) # {{/docs-fragment env}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/flyte_env.py* ### Analyst agents Each analyst agent comes equipped with a set of tools and a carefully designed prompt tailored to its specific domain. These tools are modular Flyte tasks (for example, downloading financial reports or computing technical indicators) and benefit from Flyte's built-in caching to avoid redundant computation. ``` from datetime import datetime import pandas as pd import tools.interface as interface import yfinance as yf from flyte_env import env from flyte.io import File @env.task async def get_reddit_news( curr_date: str, # Date you want to get news for in yyyy-mm-dd format ) -> str: """ Retrieve global news from Reddit within a specified time frame. Args: curr_date (str): Date you want to get news for in yyyy-mm-dd format Returns: str: A formatted dataframe containing the latest global news from Reddit in the specified time frame. """ global_news_result = interface.get_reddit_global_news(curr_date, 7, 5) return global_news_result @env.task async def get_finnhub_news( ticker: str, # Search query of a company, e.g. 'AAPL, TSM, etc. start_date: str, # Start date in yyyy-mm-dd format end_date: str, # End date in yyyy-mm-dd format ) -> str: """ Retrieve the latest news about a given stock from Finnhub within a date range Args: ticker (str): Ticker of a company. e.g. AAPL, TSM start_date (str): Start date in yyyy-mm-dd format end_date (str): End date in yyyy-mm-dd format Returns: str: A formatted dataframe containing news about the company within the date range from start_date to end_date """ end_date_str = end_date end_date = datetime.strptime(end_date, "%Y-%m-%d") start_date = datetime.strptime(start_date, "%Y-%m-%d") look_back_days = (end_date - start_date).days finnhub_news_result = interface.get_finnhub_news( ticker, end_date_str, look_back_days ) return finnhub_news_result @env.task async def get_reddit_stock_info( ticker: str, # Ticker of a company. e.g. AAPL, TSM curr_date: str, # Current date you want to get news for ) -> str: """ Retrieve the latest news about a given stock from Reddit, given the current date. Args: ticker (str): Ticker of a company. e.g. AAPL, TSM curr_date (str): current date in yyyy-mm-dd format to get news for Returns: str: A formatted dataframe containing the latest news about the company on the given date """ stock_news_results = interface.get_reddit_company_news(ticker, curr_date, 7, 5) return stock_news_results @env.task async def get_YFin_data( symbol: str, # ticker symbol of the company start_date: str, # Start date in yyyy-mm-dd format end_date: str, # End date in yyyy-mm-dd format ) -> str: """ Retrieve the stock price data for a given ticker symbol from Yahoo Finance. Args: symbol (str): Ticker symbol of the company, e.g. AAPL, TSM start_date (str): Start date in yyyy-mm-dd format end_date (str): End date in yyyy-mm-dd format Returns: str: A formatted dataframe containing the stock price data for the specified ticker symbol in the specified date range. """ result_data = interface.get_YFin_data(symbol, start_date, end_date) return result_data @env.task async def get_YFin_data_online( symbol: str, # ticker symbol of the company start_date: str, # Start date in yyyy-mm-dd format end_date: str, # End date in yyyy-mm-dd format ) -> str: """ Retrieve the stock price data for a given ticker symbol from Yahoo Finance. Args: symbol (str): Ticker symbol of the company, e.g. AAPL, TSM start_date (str): Start date in yyyy-mm-dd format end_date (str): End date in yyyy-mm-dd format Returns: str: A formatted dataframe containing the stock price data for the specified ticker symbol in the specified date range. """ result_data = interface.get_YFin_data_online(symbol, start_date, end_date) return result_data @env.task async def cache_market_data(symbol: str, start_date: str, end_date: str) -> File: data_file = f"{symbol}-YFin-data-{start_date}-{end_date}.csv" data = yf.download( symbol, start=start_date, end=end_date, multi_level_index=False, progress=False, auto_adjust=True, ) data = data.reset_index() data.to_csv(data_file, index=False) return await File.from_local(data_file) @env.task async def get_stockstats_indicators_report( symbol: str, # ticker symbol of the company indicator: str, # technical indicator to get the analysis and report of curr_date: str, # The current trading date you are trading on, YYYY-mm-dd look_back_days: int = 30, # how many days to look back ) -> str: """ Retrieve stock stats indicators for a given ticker symbol and indicator. Args: symbol (str): Ticker symbol of the company, e.g. AAPL, TSM indicator (str): Technical indicator to get the analysis and report of curr_date (str): The current trading date you are trading on, YYYY-mm-dd look_back_days (int): How many days to look back, default is 30 Returns: str: A formatted dataframe containing the stock stats indicators for the specified ticker symbol and indicator. """ today_date = pd.Timestamp.today() end_date = today_date start_date = today_date - pd.DateOffset(years=15) start_date = start_date.strftime("%Y-%m-%d") end_date = end_date.strftime("%Y-%m-%d") data_file = await cache_market_data(symbol, start_date, end_date) local_data_file = await data_file.download() result_stockstats = interface.get_stock_stats_indicators_window( symbol, indicator, curr_date, look_back_days, False, local_data_file ) return result_stockstats # {{docs-fragment get_stockstats_indicators_report_online}} @env.task async def get_stockstats_indicators_report_online( symbol: str, # ticker symbol of the company indicator: str, # technical indicator to get the analysis and report of curr_date: str, # The current trading date you are trading on, YYYY-mm-dd" look_back_days: int = 30, # "how many days to look back" ) -> str: """ Retrieve stock stats indicators for a given ticker symbol and indicator. Args: symbol (str): Ticker symbol of the company, e.g. AAPL, TSM indicator (str): Technical indicator to get the analysis and report of curr_date (str): The current trading date you are trading on, YYYY-mm-dd look_back_days (int): How many days to look back, default is 30 Returns: str: A formatted dataframe containing the stock stats indicators for the specified ticker symbol and indicator. """ today_date = pd.Timestamp.today() end_date = today_date start_date = today_date - pd.DateOffset(years=15) start_date = start_date.strftime("%Y-%m-%d") end_date = end_date.strftime("%Y-%m-%d") data_file = await cache_market_data(symbol, start_date, end_date) local_data_file = await data_file.download() result_stockstats = interface.get_stock_stats_indicators_window( symbol, indicator, curr_date, look_back_days, True, local_data_file ) return result_stockstats # {{/docs-fragment get_stockstats_indicators_report_online}} @env.task async def get_finnhub_company_insider_sentiment( ticker: str, # ticker symbol for the company curr_date: str, # current date of you are trading at, yyyy-mm-dd ) -> str: """ Retrieve insider sentiment information about a company (retrieved from public SEC information) for the past 30 days Args: ticker (str): ticker symbol of the company curr_date (str): current date you are trading at, yyyy-mm-dd Returns: str: a report of the sentiment in the past 30 days starting at curr_date """ data_sentiment = interface.get_finnhub_company_insider_sentiment( ticker, curr_date, 30 ) return data_sentiment @env.task async def get_finnhub_company_insider_transactions( ticker: str, # ticker symbol curr_date: str, # current date you are trading at, yyyy-mm-dd ) -> str: """ Retrieve insider transaction information about a company (retrieved from public SEC information) for the past 30 days Args: ticker (str): ticker symbol of the company curr_date (str): current date you are trading at, yyyy-mm-dd Returns: str: a report of the company's insider transactions/trading information in the past 30 days """ data_trans = interface.get_finnhub_company_insider_transactions( ticker, curr_date, 30 ) return data_trans @env.task async def get_simfin_balance_sheet( ticker: str, # ticker symbol freq: str, # reporting frequency of the company's financial history: annual/quarterly curr_date: str, # current date you are trading at, yyyy-mm-dd ): """ Retrieve the most recent balance sheet of a company Args: ticker (str): ticker symbol of the company freq (str): reporting frequency of the company's financial history: annual / quarterly curr_date (str): current date you are trading at, yyyy-mm-dd Returns: str: a report of the company's most recent balance sheet """ data_balance_sheet = interface.get_simfin_balance_sheet(ticker, freq, curr_date) return data_balance_sheet @env.task async def get_simfin_cashflow( ticker: str, # ticker symbol freq: str, # reporting frequency of the company's financial history: annual/quarterly curr_date: str, # current date you are trading at, yyyy-mm-dd ) -> str: """ Retrieve the most recent cash flow statement of a company Args: ticker (str): ticker symbol of the company freq (str): reporting frequency of the company's financial history: annual / quarterly curr_date (str): current date you are trading at, yyyy-mm-dd Returns: str: a report of the company's most recent cash flow statement """ data_cashflow = interface.get_simfin_cashflow(ticker, freq, curr_date) return data_cashflow @env.task async def get_simfin_income_stmt( ticker: str, # ticker symbol freq: str, # reporting frequency of the company's financial history: annual/quarterly curr_date: str, # current date you are trading at, yyyy-mm-dd ) -> str: """ Retrieve the most recent income statement of a company Args: ticker (str): ticker symbol of the company freq (str): reporting frequency of the company's financial history: annual / quarterly curr_date (str): current date you are trading at, yyyy-mm-dd Returns: str: a report of the company's most recent income statement """ data_income_stmt = interface.get_simfin_income_statements(ticker, freq, curr_date) return data_income_stmt @env.task async def get_google_news( query: str, # Query to search with curr_date: str, # Curr date in yyyy-mm-dd format ) -> str: """ Retrieve the latest news from Google News based on a query and date range. Args: query (str): Query to search with curr_date (str): Current date in yyyy-mm-dd format look_back_days (int): How many days to look back Returns: str: A formatted string containing the latest news from Google News based on the query and date range. """ google_news_results = interface.get_google_news(query, curr_date, 7) return google_news_results @env.task async def get_stock_news_openai( ticker: str, # the company's ticker curr_date: str, # Current date in yyyy-mm-dd format ) -> str: """ Retrieve the latest news about a given stock by using OpenAI's news API. Args: ticker (str): Ticker of a company. e.g. AAPL, TSM curr_date (str): Current date in yyyy-mm-dd format Returns: str: A formatted string containing the latest news about the company on the given date. """ openai_news_results = interface.get_stock_news_openai(ticker, curr_date) return openai_news_results @env.task async def get_global_news_openai( curr_date: str, # Current date in yyyy-mm-dd format ) -> str: """ Retrieve the latest macroeconomics news on a given date using OpenAI's macroeconomics news API. Args: curr_date (str): Current date in yyyy-mm-dd format Returns: str: A formatted string containing the latest macroeconomic news on the given date. """ openai_news_results = interface.get_global_news_openai(curr_date) return openai_news_results @env.task async def get_fundamentals_openai( ticker: str, # the company's ticker curr_date: str, # Current date in yyyy-mm-dd format ) -> str: """ Retrieve the latest fundamental information about a given stock on a given date by using OpenAI's news API. Args: ticker (str): Ticker of a company. e.g. AAPL, TSM curr_date (str): Current date in yyyy-mm-dd format Returns: str: A formatted string containing the latest fundamental information about the company on the given date. """ openai_fundamentals_results = interface.get_fundamentals_openai(ticker, curr_date) return openai_fundamentals_results ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/tools/toolkit.py* When initialized, an analyst enters a structured reasoning loop (via LangChain), where it can call tools, observe outputs, and refine its internal state before generating a final report. These reports are later consumed by downstream agents. Here's an example of a news analyst that interprets global events and macroeconomic signals. We specify the tools accessible to the analyst, and the LLM selects which ones to use based on context. ``` import asyncio from agents.utils.utils import AgentState from flyte_env import env from langchain_core.messages import ToolMessage, convert_to_openai_messages from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_openai import ChatOpenAI from tools import toolkit import flyte MAX_ITERATIONS = 5 # {{docs-fragment agent_helper}} async def run_chain_with_tools( type: str, state: AgentState, llm: str, system_message: str, tool_names: list[str] ) -> AgentState: prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful AI assistant, collaborating with other assistants." " Use the provided tools to progress towards answering the question." " If you are unable to fully answer, that's OK; another assistant with different tools" " will help where you left off. Execute what you can to make progress." " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable," " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop." " You have access to the following tools: {tool_names}.\n{system_message}" " For your reference, the current date is {current_date}. The company we want to look at is {ticker}.", ), MessagesPlaceholder(variable_name="messages"), ] ) prompt = prompt.partial(system_message=system_message) prompt = prompt.partial(tool_names=", ".join(tool_names)) prompt = prompt.partial(current_date=state.trade_date) prompt = prompt.partial(ticker=state.company_of_interest) chain = prompt | ChatOpenAI(model=llm).bind_tools( [getattr(toolkit, tool_name).func for tool_name in tool_names] ) iteration = 0 while iteration < MAX_ITERATIONS: result = await chain.ainvoke(state.messages) state.messages.append(convert_to_openai_messages(result)) if not result.tool_calls: # Final response โ€” no tools required setattr(state, f"{type}_report", result.content or "") break # Run all tool calls in parallel async def run_single_tool(tool_call): tool_name = tool_call["name"] tool_args = tool_call["args"] tool = getattr(toolkit, tool_name, None) if not tool: return None content = await tool(**tool_args) return ToolMessage( tool_call_id=tool_call["id"], name=tool_name, content=content ) with flyte.group(f"tool_calls_iteration_{iteration}"): tool_messages = await asyncio.gather( *[run_single_tool(tc) for tc in result.tool_calls] ) # Add valid tool results to state tool_messages = [msg for msg in tool_messages if msg] state.messages.extend(convert_to_openai_messages(tool_messages)) iteration += 1 else: # Reached iteration cap โ€” optionally raise or log print(f"Max iterations ({MAX_ITERATIONS}) reached for {type}") return state # {{/docs-fragment agent_helper}} @env.task async def create_fundamentals_analyst( llm: str, state: AgentState, online_tools: bool ) -> AgentState: if online_tools: tools = [toolkit.get_fundamentals_openai] else: tools = [ toolkit.get_finnhub_company_insider_sentiment, toolkit.get_finnhub_company_insider_transactions, toolkit.get_simfin_balance_sheet, toolkit.get_simfin_cashflow, toolkit.get_simfin_income_stmt, ] system_message = ( "You are a researcher tasked with analyzing fundamental information over the past week about a company. " "Please write a comprehensive report of the company's fundamental information such as financial documents, " "company profile, basic company financials, company financial history, insider sentiment, and insider " "transactions to gain a full view of the company's " "fundamental information to inform traders. Make sure to include as much detail as possible. " "Do not simply state the trends are mixed, " "provide detailed and finegrained analysis and insights that may help traders make decisions. " "Make sure to append a Markdown table at the end of the report to organize key points in the report, " "organized and easy to read." ) tool_names = [tool.func.__name__ for tool in tools] return await run_chain_with_tools( "fundamentals", state, llm, system_message, tool_names ) @env.task async def create_market_analyst( llm: str, state: AgentState, online_tools: bool ) -> AgentState: if online_tools: tools = [ toolkit.get_YFin_data_online, toolkit.get_stockstats_indicators_report_online, ] else: tools = [ toolkit.get_YFin_data, toolkit.get_stockstats_indicators_report, ] system_message = ( """You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy. Categories and each category's indicators are: Moving Averages: - close_50_sma: 50 SMA: A medium-term trend indicator. Usage: Identify trend direction and serve as dynamic support/resistance. Tips: It lags price; combine with faster indicators for timely signals. - close_200_sma: 200 SMA: A long-term trend benchmark. Usage: Confirm overall market trend and identify golden/death cross setups. Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries. - close_10_ema: 10 EMA: A responsive short-term average. Usage: Capture quick shifts in momentum and potential entry points. Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals. MACD Related: - macd: MACD: Computes momentum via differences of EMAs. Usage: Look for crossovers and divergence as signals of trend changes. Tips: Confirm with other indicators in low-volatility or sideways markets. - macds: MACD Signal: An EMA smoothing of the MACD line. Usage: Use crossovers with the MACD line to trigger trades. Tips: Should be part of a broader strategy to avoid false positives. - macdh: MACD Histogram: Shows the gap between the MACD line and its signal. Usage: Visualize momentum strength and spot divergence early. Tips: Can be volatile; complement with additional filters in fast-moving markets. Momentum Indicators: - rsi: RSI: Measures momentum to flag overbought/oversold conditions. Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis. Volatility Indicators: - boll: Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. Usage: Acts as a dynamic benchmark for price movement. Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals. - boll_ub: Bollinger Upper Band: Typically 2 standard deviations above the middle line. Usage: Signals potential overbought conditions and breakout zones. Tips: Confirm signals with other tools; prices may ride the band in strong trends. - boll_lb: Bollinger Lower Band: Typically 2 standard deviations below the middle line. Usage: Indicates potential oversold conditions. Tips: Use additional analysis to avoid false reversal signals. - atr: ATR: Averages true range to measure volatility. Usage: Set stop-loss levels and adjust position sizes based on current market volatility. Tips: It's a reactive measure, so use it as part of a broader risk management strategy. Volume-Based Indicators: - vwma: VWMA: A moving average weighted by volume. Usage: Confirm trends by integrating price action with volume data. Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses. - Select indicators that provide diverse and complementary information. Avoid redundancy (e.g., do not select both rsi and stochrsi). Also briefly explain why they are suitable for the given market context. When you tool call, please use the exact name of the indicators provided above as they are defined parameters, otherwise your call will fail. Please make sure to call get_YFin_data first to retrieve the CSV that is needed to generate indicators. Write a very detailed and nuanced report of the trends you observe. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions.""" """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""" ) tool_names = [tool.func.__name__ for tool in tools] return await run_chain_with_tools("market", state, llm, system_message, tool_names) # {{docs-fragment news_analyst}} @env.task async def create_news_analyst( llm: str, state: AgentState, online_tools: bool ) -> AgentState: if online_tools: tools = [ toolkit.get_global_news_openai, toolkit.get_google_news, ] else: tools = [ toolkit.get_finnhub_news, toolkit.get_reddit_news, toolkit.get_google_news, ] system_message = ( "You are a news researcher tasked with analyzing recent news and trends over the past week. " "Please write a comprehensive report of the current state of the world that is relevant for " "trading and macroeconomics. " "Look at news from EODHD, and finnhub to be comprehensive. Do not simply state the trends are mixed, " "provide detailed and finegrained analysis and insights that may help traders make decisions." """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""" ) tool_names = [tool.func.__name__ for tool in tools] return await run_chain_with_tools("news", state, llm, system_message, tool_names) # {{/docs-fragment news_analyst}} @env.task async def create_social_media_analyst( llm: str, state: AgentState, online_tools: bool ) -> AgentState: if online_tools: tools = [toolkit.get_stock_news_openai] else: tools = [toolkit.get_reddit_stock_info] system_message = ( "You are a social media and company specific news researcher/analyst tasked with analyzing social media posts, " "recent company news, and public sentiment for a specific company over the past week. " "You will be given a company's name your objective is to write a comprehensive long report " "detailing your analysis, insights, and implications for traders and investors on this company's current state " "after looking at social media and what people are saying about that company, " "analyzing sentiment data of what people feel each day about the company, and looking at recent company news. " "Try to look at all sources possible from social media to sentiment to news. Do not simply state the trends " "are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions." """ Make sure to append a Makrdown table at the end of the report to organize key points in the report, organized and easy to read.""" ) tool_names = [tool.func.__name__ for tool in tools] return await run_chain_with_tools( "sentiment", state, llm, system_message, tool_names ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/agents/analysts.py* Each analyst agent uses a helper function to bind tools, iterate through reasoning steps (up to a configurable maximum), and produce an answer. Setting a max iteration count is crucial to prevent runaway loops. As agents reason, their message history is preserved in their internal state and passed along to the next agent in the chain. ``` import asyncio from agents.utils.utils import AgentState from flyte_env import env from langchain_core.messages import ToolMessage, convert_to_openai_messages from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_openai import ChatOpenAI from tools import toolkit import flyte MAX_ITERATIONS = 5 # {{docs-fragment agent_helper}} async def run_chain_with_tools( type: str, state: AgentState, llm: str, system_message: str, tool_names: list[str] ) -> AgentState: prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful AI assistant, collaborating with other assistants." " Use the provided tools to progress towards answering the question." " If you are unable to fully answer, that's OK; another assistant with different tools" " will help where you left off. Execute what you can to make progress." " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable," " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop." " You have access to the following tools: {tool_names}.\n{system_message}" " For your reference, the current date is {current_date}. The company we want to look at is {ticker}.", ), MessagesPlaceholder(variable_name="messages"), ] ) prompt = prompt.partial(system_message=system_message) prompt = prompt.partial(tool_names=", ".join(tool_names)) prompt = prompt.partial(current_date=state.trade_date) prompt = prompt.partial(ticker=state.company_of_interest) chain = prompt | ChatOpenAI(model=llm).bind_tools( [getattr(toolkit, tool_name).func for tool_name in tool_names] ) iteration = 0 while iteration < MAX_ITERATIONS: result = await chain.ainvoke(state.messages) state.messages.append(convert_to_openai_messages(result)) if not result.tool_calls: # Final response โ€” no tools required setattr(state, f"{type}_report", result.content or "") break # Run all tool calls in parallel async def run_single_tool(tool_call): tool_name = tool_call["name"] tool_args = tool_call["args"] tool = getattr(toolkit, tool_name, None) if not tool: return None content = await tool(**tool_args) return ToolMessage( tool_call_id=tool_call["id"], name=tool_name, content=content ) with flyte.group(f"tool_calls_iteration_{iteration}"): tool_messages = await asyncio.gather( *[run_single_tool(tc) for tc in result.tool_calls] ) # Add valid tool results to state tool_messages = [msg for msg in tool_messages if msg] state.messages.extend(convert_to_openai_messages(tool_messages)) iteration += 1 else: # Reached iteration cap โ€” optionally raise or log print(f"Max iterations ({MAX_ITERATIONS}) reached for {type}") return state # {{/docs-fragment agent_helper}} @env.task async def create_fundamentals_analyst( llm: str, state: AgentState, online_tools: bool ) -> AgentState: if online_tools: tools = [toolkit.get_fundamentals_openai] else: tools = [ toolkit.get_finnhub_company_insider_sentiment, toolkit.get_finnhub_company_insider_transactions, toolkit.get_simfin_balance_sheet, toolkit.get_simfin_cashflow, toolkit.get_simfin_income_stmt, ] system_message = ( "You are a researcher tasked with analyzing fundamental information over the past week about a company. " "Please write a comprehensive report of the company's fundamental information such as financial documents, " "company profile, basic company financials, company financial history, insider sentiment, and insider " "transactions to gain a full view of the company's " "fundamental information to inform traders. Make sure to include as much detail as possible. " "Do not simply state the trends are mixed, " "provide detailed and finegrained analysis and insights that may help traders make decisions. " "Make sure to append a Markdown table at the end of the report to organize key points in the report, " "organized and easy to read." ) tool_names = [tool.func.__name__ for tool in tools] return await run_chain_with_tools( "fundamentals", state, llm, system_message, tool_names ) @env.task async def create_market_analyst( llm: str, state: AgentState, online_tools: bool ) -> AgentState: if online_tools: tools = [ toolkit.get_YFin_data_online, toolkit.get_stockstats_indicators_report_online, ] else: tools = [ toolkit.get_YFin_data, toolkit.get_stockstats_indicators_report, ] system_message = ( """You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy. Categories and each category's indicators are: Moving Averages: - close_50_sma: 50 SMA: A medium-term trend indicator. Usage: Identify trend direction and serve as dynamic support/resistance. Tips: It lags price; combine with faster indicators for timely signals. - close_200_sma: 200 SMA: A long-term trend benchmark. Usage: Confirm overall market trend and identify golden/death cross setups. Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries. - close_10_ema: 10 EMA: A responsive short-term average. Usage: Capture quick shifts in momentum and potential entry points. Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals. MACD Related: - macd: MACD: Computes momentum via differences of EMAs. Usage: Look for crossovers and divergence as signals of trend changes. Tips: Confirm with other indicators in low-volatility or sideways markets. - macds: MACD Signal: An EMA smoothing of the MACD line. Usage: Use crossovers with the MACD line to trigger trades. Tips: Should be part of a broader strategy to avoid false positives. - macdh: MACD Histogram: Shows the gap between the MACD line and its signal. Usage: Visualize momentum strength and spot divergence early. Tips: Can be volatile; complement with additional filters in fast-moving markets. Momentum Indicators: - rsi: RSI: Measures momentum to flag overbought/oversold conditions. Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis. Volatility Indicators: - boll: Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. Usage: Acts as a dynamic benchmark for price movement. Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals. - boll_ub: Bollinger Upper Band: Typically 2 standard deviations above the middle line. Usage: Signals potential overbought conditions and breakout zones. Tips: Confirm signals with other tools; prices may ride the band in strong trends. - boll_lb: Bollinger Lower Band: Typically 2 standard deviations below the middle line. Usage: Indicates potential oversold conditions. Tips: Use additional analysis to avoid false reversal signals. - atr: ATR: Averages true range to measure volatility. Usage: Set stop-loss levels and adjust position sizes based on current market volatility. Tips: It's a reactive measure, so use it as part of a broader risk management strategy. Volume-Based Indicators: - vwma: VWMA: A moving average weighted by volume. Usage: Confirm trends by integrating price action with volume data. Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses. - Select indicators that provide diverse and complementary information. Avoid redundancy (e.g., do not select both rsi and stochrsi). Also briefly explain why they are suitable for the given market context. When you tool call, please use the exact name of the indicators provided above as they are defined parameters, otherwise your call will fail. Please make sure to call get_YFin_data first to retrieve the CSV that is needed to generate indicators. Write a very detailed and nuanced report of the trends you observe. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions.""" """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""" ) tool_names = [tool.func.__name__ for tool in tools] return await run_chain_with_tools("market", state, llm, system_message, tool_names) # {{docs-fragment news_analyst}} @env.task async def create_news_analyst( llm: str, state: AgentState, online_tools: bool ) -> AgentState: if online_tools: tools = [ toolkit.get_global_news_openai, toolkit.get_google_news, ] else: tools = [ toolkit.get_finnhub_news, toolkit.get_reddit_news, toolkit.get_google_news, ] system_message = ( "You are a news researcher tasked with analyzing recent news and trends over the past week. " "Please write a comprehensive report of the current state of the world that is relevant for " "trading and macroeconomics. " "Look at news from EODHD, and finnhub to be comprehensive. Do not simply state the trends are mixed, " "provide detailed and finegrained analysis and insights that may help traders make decisions." """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""" ) tool_names = [tool.func.__name__ for tool in tools] return await run_chain_with_tools("news", state, llm, system_message, tool_names) # {{/docs-fragment news_analyst}} @env.task async def create_social_media_analyst( llm: str, state: AgentState, online_tools: bool ) -> AgentState: if online_tools: tools = [toolkit.get_stock_news_openai] else: tools = [toolkit.get_reddit_stock_info] system_message = ( "You are a social media and company specific news researcher/analyst tasked with analyzing social media posts, " "recent company news, and public sentiment for a specific company over the past week. " "You will be given a company's name your objective is to write a comprehensive long report " "detailing your analysis, insights, and implications for traders and investors on this company's current state " "after looking at social media and what people are saying about that company, " "analyzing sentiment data of what people feel each day about the company, and looking at recent company news. " "Try to look at all sources possible from social media to sentiment to news. Do not simply state the trends " "are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions." """ Make sure to append a Makrdown table at the end of the report to organize key points in the report, organized and easy to read.""" ) tool_names = [tool.func.__name__ for tool in tools] return await run_chain_with_tools( "sentiment", state, llm, system_message, tool_names ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/agents/analysts.py* Once all analyst reports are complete, their outputs are collected and passed to the next stage of the workflow. ### Research agents The research phase consists of two agents: a bullish researcher and a bearish one. They evaluate the company from opposing viewpoints, drawing on the analysts' reports. Unlike analysts, they don't use tools. Their role is to interpret, critique, and develop positions based on the evidence. ``` from agents.utils.utils import AgentState, InvestmentDebateState, memory_init from flyte_env import env from langchain_openai import ChatOpenAI # {{docs-fragment bear_researcher}} @env.task async def create_bear_researcher(llm: str, state: AgentState) -> AgentState: investment_debate_state = state.investment_debate_state history = investment_debate_state.history bear_history = investment_debate_state.bear_history current_response = investment_debate_state.current_response market_research_report = state.market_report sentiment_report = state.sentiment_report news_report = state.news_report fundamentals_report = state.fundamentals_report memory = await memory_init(name="bear-researcher") curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for rec in past_memories: past_memory_str += rec["recommendation"] + "\n\n" prompt = f"""You are a Bear Analyst making the case against investing in the stock. Your goal is to present a well-reasoned argument emphasizing risks, challenges, and negative indicators. Leverage the provided research and data to highlight potential downsides and counter bullish arguments effectively. Key points to focus on: - Risks and Challenges: Highlight factors like market saturation, financial instability, or macroeconomic threats that could hinder the stock's performance. - Competitive Weaknesses: Emphasize vulnerabilities such as weaker market positioning, declining innovation, or threats from competitors. - Negative Indicators: Use evidence from financial data, market trends, or recent adverse news to support your position. - Bull Counterpoints: Critically analyze the bull argument with specific data and sound reasoning, exposing weaknesses or over-optimistic assumptions. - Engagement: Present your argument in a conversational style, directly engaging with the bull analyst's points and debating effectively rather than simply listing facts. Resources available: Market research report: {market_research_report} Social media sentiment report: {sentiment_report} Latest world affairs news: {news_report} Company fundamentals report: {fundamentals_report} Conversation history of the debate: {history} Last bull argument: {current_response} Reflections from similar situations and lessons learned: {past_memory_str} Use this information to deliver a compelling bear argument, refute the bull's claims, and engage in a dynamic debate that demonstrates the risks and weaknesses of investing in the stock. You must also address reflections and learn from lessons and mistakes you made in the past. """ response = ChatOpenAI(model=llm).invoke(prompt) argument = f"Bear Analyst: {response.content}" new_investment_debate_state = InvestmentDebateState( history=history + "\n" + argument, bear_history=bear_history + "\n" + argument, bull_history=investment_debate_state.bull_history, current_response=argument, count=investment_debate_state.count + 1, ) state.investment_debate_state = new_investment_debate_state return state # {{/docs-fragment bear_researcher}} @env.task async def create_bull_researcher(llm: str, state: AgentState) -> AgentState: investment_debate_state = state.investment_debate_state history = investment_debate_state.history bull_history = investment_debate_state.bull_history current_response = investment_debate_state.current_response market_research_report = state.market_report sentiment_report = state.sentiment_report news_report = state.news_report fundamentals_report = state.fundamentals_report memory = await memory_init(name="bull-researcher") curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for rec in past_memories: past_memory_str += rec["recommendation"] + "\n\n" prompt = f"""You are a Bull Analyst advocating for investing in the stock. Your task is to build a strong, evidence-based case emphasizing growth potential, competitive advantages, and positive market indicators. Leverage the provided research and data to address concerns and counter bearish arguments effectively. Key points to focus on: - Growth Potential: Highlight the company's market opportunities, revenue projections, and scalability. - Competitive Advantages: Emphasize factors like unique products, strong branding, or dominant market positioning. - Positive Indicators: Use financial health, industry trends, and recent positive news as evidence. - Bear Counterpoints: Critically analyze the bear argument with specific data and sound reasoning, addressing concerns thoroughly and showing why the bull perspective holds stronger merit. - Engagement: Present your argument in a conversational style, engaging directly with the bear analyst's points and debating effectively rather than just listing data. Resources available: Market research report: {market_research_report} Social media sentiment report: {sentiment_report} Latest world affairs news: {news_report} Company fundamentals report: {fundamentals_report} Conversation history of the debate: {history} Last bear argument: {current_response} Reflections from similar situations and lessons learned: {past_memory_str} Use this information to deliver a compelling bull argument, refute the bear's concerns, and engage in a dynamic debate that demonstrates the strengths of the bull position. You must also address reflections and learn from lessons and mistakes you made in the past. """ response = ChatOpenAI(model=llm).invoke(prompt) argument = f"Bull Analyst: {response.content}" new_investment_debate_state = InvestmentDebateState( history=history + "\n" + argument, bull_history=bull_history + "\n" + argument, bear_history=investment_debate_state.bear_history, current_response=argument, count=investment_debate_state.count + 1, ) state.investment_debate_state = new_investment_debate_state return state ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/agents/researchers.py* To aid reasoning, the agents can also retrieve relevant "memories" from a vector database, giving them richer historical context. The number of debate rounds is configurable, and after a few iterations of back-and-forth between the bull and bear, a research manager agent reviews their arguments and makes a final investment decision. ``` from agents.utils.utils import ( AgentState, InvestmentDebateState, RiskDebateState, memory_init, ) from flyte_env import env from langchain_openai import ChatOpenAI # {{docs-fragment research_manager}} @env.task async def create_research_manager(llm: str, state: AgentState) -> AgentState: history = state.investment_debate_state.history investment_debate_state = state.investment_debate_state market_research_report = state.market_report sentiment_report = state.sentiment_report news_report = state.news_report fundamentals_report = state.fundamentals_report memory = await memory_init(name="research-manager") curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for rec in past_memories: past_memory_str += rec["recommendation"] + "\n\n" prompt = f"""As the portfolio manager and debate facilitator, your role is to critically evaluate this round of debate and make a definitive decision: align with the bear analyst, the bull analyst, or choose Hold only if it is strongly justified based on the arguments presented. Summarize the key points from both sides concisely, focusing on the most compelling evidence or reasoning. Your recommendationโ€”Buy, Sell, or Holdโ€”must be clear and actionable. Avoid defaulting to Hold simply because both sides have valid points; commit to a stance grounded in the debate's strongest arguments. Additionally, develop a detailed investment plan for the trader. This should include: Your Recommendation: A decisive stance supported by the most convincing arguments. Rationale: An explanation of why these arguments lead to your conclusion. Strategic Actions: Concrete steps for implementing the recommendation. Take into account your past mistakes on similar situations. Use these insights to refine your decision-making and ensure you are learning and improving. Present your analysis conversationally, as if speaking naturally, without special formatting. Here are your past reflections on mistakes: \"{past_memory_str}\" Here is the debate: Debate History: {history}""" response = ChatOpenAI(model=llm).invoke(prompt) new_investment_debate_state = InvestmentDebateState( judge_decision=response.content, history=investment_debate_state.history, bear_history=investment_debate_state.bear_history, bull_history=investment_debate_state.bull_history, current_response=response.content, count=investment_debate_state.count, ) state.investment_debate_state = new_investment_debate_state state.investment_plan = response.content return state # {{/docs-fragment research_manager}} @env.task async def create_risk_manager(llm: str, state: AgentState) -> AgentState: history = state.risk_debate_state.history risk_debate_state = state.risk_debate_state trader_plan = state.investment_plan market_research_report = state.market_report sentiment_report = state.sentiment_report news_report = state.news_report fundamentals_report = state.fundamentals_report memory = await memory_init(name="risk-manager") curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for rec in past_memories: past_memory_str += rec["recommendation"] + "\n\n" prompt = f"""As the Risk Management Judge and Debate Facilitator, your goal is to evaluate the debate between three risk analystsโ€”Risky, Neutral, and Safe/Conservativeโ€”and determine the best course of action for the trader. Your decision must result in a clear recommendation: Buy, Sell, or Hold. Choose Hold only if strongly justified by specific arguments, not as a fallback when all sides seem valid. Strive for clarity and decisiveness. Guidelines for Decision-Making: 1. **Summarize Key Arguments**: Extract the strongest points from each analyst, focusing on relevance to the context. 2. **Provide Rationale**: Support your recommendation with direct quotes and counterarguments from the debate. 3. **Refine the Trader's Plan**: Start with the trader's original plan, **{trader_plan}**, and adjust it based on the analysts' insights. 4. **Learn from Past Mistakes**: Use lessons from **{past_memory_str}** to address prior misjudgments and improve the decision you are making now to make sure you don't make a wrong BUY/SELL/HOLD call that loses money. Deliverables: - A clear and actionable recommendation: Buy, Sell, or Hold. - Detailed reasoning anchored in the debate and past reflections. --- **Analysts Debate History:** {history} --- Focus on actionable insights and continuous improvement. Build on past lessons, critically evaluate all perspectives, and ensure each decision advances better outcomes.""" response = ChatOpenAI(model=llm).invoke(prompt) new_risk_debate_state = RiskDebateState( judge_decision=response.content, history=risk_debate_state.history, risky_history=risk_debate_state.risky_history, safe_history=risk_debate_state.safe_history, neutral_history=risk_debate_state.neutral_history, latest_speaker="Judge", current_risky_response=risk_debate_state.current_risky_response, current_safe_response=risk_debate_state.current_safe_response, current_neutral_response=risk_debate_state.current_neutral_response, count=risk_debate_state.count, ) state.risk_debate_state = new_risk_debate_state state.final_trade_decision = response.content return state ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/agents/managers.py* ### Trading agent The trader agent consolidates the insights from analysts and researchers to generate a final recommendation. It synthesizes competing signals and produces a conclusion such as _Buy for long-term growth despite short-term volatility_. ``` from agents.utils.utils import AgentState, memory_init from flyte_env import env from langchain_core.messages import convert_to_openai_messages from langchain_openai import ChatOpenAI # {{docs-fragment trader}} @env.task async def create_trader(llm: str, state: AgentState) -> AgentState: company_name = state.company_of_interest investment_plan = state.investment_plan market_research_report = state.market_report sentiment_report = state.sentiment_report news_report = state.news_report fundamentals_report = state.fundamentals_report memory = await memory_init(name="trader") curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for rec in past_memories: past_memory_str += rec["recommendation"] + "\n\n" context = { "role": "user", "content": f"Based on a comprehensive analysis by a team of analysts, " f"here is an investment plan tailored for {company_name}. " "This plan incorporates insights from current technical market trends, " "macroeconomic indicators, and social media sentiment. " "Use this plan as a foundation for evaluating your next trading decision.\n\n" f"Proposed Investment Plan: {investment_plan}\n\n" "Leverage these insights to make an informed and strategic decision.", } messages = [ { "role": "system", "content": f"""You are a trading agent analyzing market data to make investment decisions. Based on your analysis, provide a specific recommendation to buy, sell, or hold. End with a firm decision and always conclude your response with 'FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL**' to confirm your recommendation. Do not forget to utilize lessons from past decisions to learn from your mistakes. Here is some reflections from similar situatiosn you traded in and the lessons learned: {past_memory_str}""", }, context, ] result = ChatOpenAI(model=llm).invoke(messages) state.messages.append(convert_to_openai_messages(result)) state.trader_investment_plan = result.content state.sender = "Trader" return state # {{/docs-fragment trader}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/agents/trader.py* ### Risk agents Risk agents comprise agents with different risk tolerances: a risky debater, a neutral one, and a conservative one. They assess the portfolio through lenses like market volatility, liquidity, and systemic risk. Similar to the bull-bear debate, these agents engage in internal discussion, after which a risk manager makes the final call. ``` from agents.utils.utils import AgentState, RiskDebateState from flyte_env import env from langchain_openai import ChatOpenAI # {{docs-fragment risk_debator}} @env.task async def create_risky_debator(llm: str, state: AgentState) -> AgentState: risk_debate_state = state.risk_debate_state history = risk_debate_state.history risky_history = risk_debate_state.risky_history current_safe_response = risk_debate_state.current_safe_response current_neutral_response = risk_debate_state.current_neutral_response market_research_report = state.market_report sentiment_report = state.sentiment_report news_report = state.news_report fundamentals_report = state.fundamentals_report trader_decision = state.trader_investment_plan prompt = f"""As the Risky Risk Analyst, your role is to actively champion high-reward, high-risk opportunities, emphasizing bold strategies and competitive advantages. When evaluating the trader's decision or plan, focus intently on the potential upside, growth potential, and innovative benefitsโ€”even when these come with elevated risk. Use the provided market data and sentiment analysis to strengthen your arguments and challenge the opposing views. Specifically, respond directly to each point made by the conservative and neutral analysts, countering with data-driven rebuttals and persuasive reasoning. Highlight where their caution might miss critical opportunities or where their assumptions may be overly conservative. Here is the trader's decision: {trader_decision} Your task is to create a compelling case for the trader's decision by questioning and critiquing the conservative and neutral stances to demonstrate why your high-reward perspective offers the best path forward. Incorporate insights from the following sources into your arguments: Market Research Report: {market_research_report} Social Media Sentiment Report: {sentiment_report} Latest World Affairs Report: {news_report} Company Fundamentals Report: {fundamentals_report} Here is the current conversation history: {history} Here are the last arguments from the conservative analyst: {current_safe_response} Here are the last arguments from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints, do not halluncinate and just present your point. Engage actively by addressing any specific concerns raised, refuting the weaknesses in their logic, and asserting the benefits of risk-taking to outpace market norms. Maintain a focus on debating and persuading, not just presenting data. Challenge each counterpoint to underscore why a high-risk approach is optimal. Output conversationally as if you are speaking without any special formatting.""" response = ChatOpenAI(model=llm).invoke(prompt) argument = f"Risky Analyst: {response.content}" new_risk_debate_state = RiskDebateState( history=history + "\n" + argument, risky_history=risky_history + "\n" + argument, safe_history=risk_debate_state.safe_history, neutral_history=risk_debate_state.neutral_history, latest_speaker="Risky", current_risky_response=argument, current_safe_response=current_safe_response, current_neutral_response=current_neutral_response, count=risk_debate_state.count + 1, ) state.risk_debate_state = new_risk_debate_state return state # {{/docs-fragment risk_debator}} @env.task async def create_safe_debator(llm: str, state: AgentState) -> AgentState: risk_debate_state = state.risk_debate_state history = risk_debate_state.history safe_history = risk_debate_state.safe_history current_risky_response = risk_debate_state.current_risky_response current_neutral_response = risk_debate_state.current_neutral_response market_research_report = state.market_report sentiment_report = state.sentiment_report news_report = state.news_report fundamentals_report = state.fundamentals_report trader_decision = state.trader_investment_plan prompt = f"""As the Safe/Conservative Risk Analyst, your primary objective is to protect assets, minimize volatility, and ensure steady, reliable growth. You prioritize stability, security, and risk mitigation, carefully assessing potential losses, economic downturns, and market volatility. When evaluating the trader's decision or plan, critically examine high-risk elements, pointing out where the decision may expose the firm to undue risk and where more cautious alternatives could secure long-term gains. Here is the trader's decision: {trader_decision} Your task is to actively counter the arguments of the Risky and Neutral Analysts, highlighting where their views may overlook potential threats or fail to prioritize sustainability. Respond directly to their points, drawing from the following data sources to build a convincing case for a low-risk approach adjustment to the trader's decision: Market Research Report: {market_research_report} Social Media Sentiment Report: {sentiment_report} Latest World Affairs Report: {news_report} Company Fundamentals Report: {fundamentals_report} Here is the current conversation history: {history} Here is the last response from the risky analyst: {current_risky_response} Here is the last response from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints, do not halluncinate and just present your point. Engage by questioning their optimism and emphasizing the potential downsides they may have overlooked. Address each of their counterpoints to showcase why a conservative stance is ultimately the safest path for the firm's assets. Focus on debating and critiquing their arguments to demonstrate the strength of a low-risk strategy over their approaches. Output conversationally as if you are speaking without any special formatting.""" response = ChatOpenAI(model=llm).invoke(prompt) argument = f"Safe Analyst: {response.content}" new_risk_debate_state = RiskDebateState( history=history + "\n" + argument, risky_history=risk_debate_state.risky_history, safe_history=safe_history + "\n" + argument, neutral_history=risk_debate_state.neutral_history, latest_speaker="Safe", current_risky_response=current_risky_response, current_safe_response=argument, current_neutral_response=current_neutral_response, count=risk_debate_state.count + 1, ) state.risk_debate_state = new_risk_debate_state return state @env.task async def create_neutral_debator(llm: str, state: AgentState) -> AgentState: risk_debate_state = state.risk_debate_state history = risk_debate_state.history neutral_history = risk_debate_state.neutral_history current_risky_response = risk_debate_state.current_risky_response current_safe_response = risk_debate_state.current_safe_response market_research_report = state.market_report sentiment_report = state.sentiment_report news_report = state.news_report fundamentals_report = state.fundamentals_report trader_decision = state.trader_investment_plan prompt = f"""As the Neutral Risk Analyst, your role is to provide a balanced perspective, weighing both the potential benefits and risks of the trader's decision or plan. You prioritize a well-rounded approach, evaluating the upsides and downsides while factoring in broader market trends, potential economic shifts, and diversification strategies.Here is the trader's decision: {trader_decision} Your task is to challenge both the Risky and Safe Analysts, pointing out where each perspective may be overly optimistic or overly cautious. Use insights from the following data sources to support a moderate, sustainable strategy to adjust the trader's decision: Market Research Report: {market_research_report} Social Media Sentiment Report: {sentiment_report} Latest World Affairs Report: {news_report} Company Fundamentals Report: {fundamentals_report} Here is the current conversation history: {history} Here is the last response from the risky analyst: {current_risky_response} Here is the last response from the safe analyst: {current_safe_response}. If there are no responses from the other viewpoints, do not halluncinate and just present your point. Engage actively by analyzing both sides critically, addressing weaknesses in the risky and conservative arguments to advocate for a more balanced approach. Challenge each of their points to illustrate why a moderate risk strategy might offer the best of both worlds, providing growth potential while safeguarding against extreme volatility. Focus on debating rather than simply presenting data, aiming to show that a balanced view can lead to the most reliable outcomes. Output conversationally as if you are speaking without any special formatting.""" response = ChatOpenAI(model=llm).invoke(prompt) argument = f"Neutral Analyst: {response.content}" new_risk_debate_state = RiskDebateState( history=history + "\n" + argument, risky_history=risk_debate_state.risky_history, safe_history=risk_debate_state.safe_history, neutral_history=neutral_history + "\n" + argument, latest_speaker="Neutral", current_risky_response=current_risky_response, current_safe_response=current_safe_response, current_neutral_response=argument, count=risk_debate_state.count + 1, ) state.risk_debate_state = new_risk_debate_state return state ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/agents/risk_debators.py* The outcome of the risk manager, whether to proceed with the trade or not, is considered the final decision of the trading simulation. You can visualize this full pipeline in the Flyte/Union UI, where every step is logged. Youโ€™ll see input/output metadata for each tool and agent task. Thanks to Flyte's caching, repeated steps are skipped unless inputs change, saving time and compute resources. ### Retaining agent memory with S3 vectors To help agents learn from past decisions, we persist their memory in a vector store. In this example, we use an [S3 vector](https://aws.amazon.com/s3/features/vectors/) bucket for their simplicity and tight integration with Flyte and Union, but any vector database can be used. Note: To use the S3 vector store, make sure your IAM role has the following permissions configured: ``` s3vectors:CreateVectorBucket s3vectors:CreateIndex s3vectors:PutVectors s3vectors:GetIndex s3vectors:GetVectors s3vectors:QueryVectors s3vectors:GetVectorBucket ``` After each trade decision, you can run a `reflect_on_decisions` task. This evaluates whether the final outcome aligned with the agent's recommendation and stores that reflection in the vector store. These stored insights can later be retrieved to provide historical context and improve future decision-making. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # "akshare==1.16.98", # "backtrader==1.9.78.123", # "boto3==1.39.9", # "chainlit==2.5.5", # "eodhd==1.0.32", # "feedparser==6.0.11", # "finnhub-python==2.4.23", # "langchain-experimental==0.3.4", # "langchain-openai==0.3.23", # "pandas==2.3.0", # "parsel==1.10.0", # "praw==7.8.1", # "pytz==2025.2", # "questionary==2.1.0", # "redis==6.2.0", # "requests==2.32.4", # "stockstats==0.6.5", # "tqdm==4.67.1", # "tushare==1.4.21", # "typing-extensions==4.14.0", # "yfinance==0.2.63", # ] # main = "main" # params = "" # /// import asyncio from copy import deepcopy import agents import agents.analysts from agents.managers import create_research_manager, create_risk_manager from agents.researchers import create_bear_researcher, create_bull_researcher from agents.risk_debators import ( create_neutral_debator, create_risky_debator, create_safe_debator, ) from agents.trader import create_trader from agents.utils.utils import AgentState from flyte_env import DEEP_THINKING_LLM, QUICK_THINKING_LLM, env, flyte from langchain_openai import ChatOpenAI from reflection import ( reflect_bear_researcher, reflect_bull_researcher, reflect_research_manager, reflect_risk_manager, reflect_trader, ) @env.task async def process_signal(full_signal: str, QUICK_THINKING_LLM: str) -> str: """Process a full trading signal to extract the core decision.""" messages = [ { "role": "system", "content": """You are an efficient assistant designed to analyze paragraphs or financial reports provided by a group of analysts. Your task is to extract the investment decision: SELL, BUY, or HOLD. Provide only the extracted decision (SELL, BUY, or HOLD) as your output, without adding any additional text or information.""", }, {"role": "human", "content": full_signal}, ] return ChatOpenAI(model=QUICK_THINKING_LLM).invoke(messages).content async def run_analyst(analyst_name, state, online_tools): # Create a copy of the state for isolation run_fn = getattr(agents.analysts, f"create_{analyst_name}_analyst") # Run the analyst's chain result_state = await run_fn(QUICK_THINKING_LLM, state, online_tools) # Determine the report key report_key = ( "sentiment_report" if analyst_name == "social_media" else f"{analyst_name}_report" ) report_value = getattr(result_state, report_key) return result_state.messages[1:], report_key, report_value # {{docs-fragment main}} @env.task async def main( selected_analysts: list[str] = [ "market", "fundamentals", "news", "social_media", ], max_debate_rounds: int = 1, max_risk_discuss_rounds: int = 1, online_tools: bool = True, company_name: str = "NVDA", trade_date: str = "2024-05-12", ) -> tuple[str, AgentState]: if not selected_analysts: raise ValueError( "No analysts selected. Please select at least one analyst from market, fundamentals, news, or social_media." ) state = AgentState( messages=[{"role": "human", "content": company_name}], company_of_interest=company_name, trade_date=str(trade_date), ) # Run all analysts concurrently results = await asyncio.gather( *[ run_analyst(analyst, deepcopy(state), online_tools) for analyst in selected_analysts ] ) # Flatten and append all resulting messages into the shared state for messages, report_attr, report in results: state.messages.extend(messages) setattr(state, report_attr, report) # Bull/Bear debate loop state = await create_bull_researcher(QUICK_THINKING_LLM, state) # Start with bull while state.investment_debate_state.count < 2 * max_debate_rounds: current = state.investment_debate_state.current_response if current.startswith("Bull"): state = await create_bear_researcher(QUICK_THINKING_LLM, state) else: state = await create_bull_researcher(QUICK_THINKING_LLM, state) state = await create_research_manager(DEEP_THINKING_LLM, state) state = await create_trader(QUICK_THINKING_LLM, state) # Risk debate loop state = await create_risky_debator(QUICK_THINKING_LLM, state) # Start with risky while state.risk_debate_state.count < 3 * max_risk_discuss_rounds: speaker = state.risk_debate_state.latest_speaker if speaker == "Risky": state = await create_safe_debator(QUICK_THINKING_LLM, state) elif speaker == "Safe": state = await create_neutral_debator(QUICK_THINKING_LLM, state) else: state = await create_risky_debator(QUICK_THINKING_LLM, state) state = await create_risk_manager(DEEP_THINKING_LLM, state) decision = await process_signal(state.final_trade_decision, QUICK_THINKING_LLM) return decision, state # {{/docs-fragment main}} # {{docs-fragment reflect_on_decisions}} @env.task async def reflect_and_store(state: AgentState, returns: str) -> str: await asyncio.gather( reflect_bear_researcher(state, returns), reflect_bull_researcher(state, returns), reflect_trader(state, returns), reflect_risk_manager(state, returns), reflect_research_manager(state, returns), ) return "Reflection completed." # Run the reflection task after the main function @env.task(cache="disable") async def reflect_on_decisions( returns: str, selected_analysts: list[str] = [ "market", "fundamentals", "news", "social_media", ], max_debate_rounds: int = 1, max_risk_discuss_rounds: int = 1, online_tools: bool = True, company_name: str = "NVDA", trade_date: str = "2024-05-12", ) -> str: _, state = await main( selected_analysts, max_debate_rounds, max_risk_discuss_rounds, online_tools, company_name, trade_date, ) return await reflect_and_store(state, returns) # {{/docs-fragment reflect_on_decisions}} # {{docs-fragment execute_main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main) print(run.url) run.wait() # run = flyte.run(reflect_on_decisions, "+3.2% gain over 5 days") # print(run.url) # {{/docs-fragment execute_main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/main.py* ### Running the simulation First, set up your OpenAI secret (from [openai.com](https://platform.openai.com/api-keys)) and Finnhub API key (from [finnhub.io](https://finnhub.io/)): ``` flyte create secret openai_api_key --value flyte create secret finnhub_api_key --value ``` Then [clone the repo](https://github.com/unionai/unionai-examples), navigate to the `tutorials-v2/trading_agents` directory, and run the following commands: ``` flyte create config --endpoint --project --domain --builder remote uv run main.py ``` If you'd like to run the `reflect_on_decisions` task instead, comment out the `main` function call and uncomment the `reflect_on_decisions` call in the `__main__` block: ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.0.0b52", # "akshare==1.16.98", # "backtrader==1.9.78.123", # "boto3==1.39.9", # "chainlit==2.5.5", # "eodhd==1.0.32", # "feedparser==6.0.11", # "finnhub-python==2.4.23", # "langchain-experimental==0.3.4", # "langchain-openai==0.3.23", # "pandas==2.3.0", # "parsel==1.10.0", # "praw==7.8.1", # "pytz==2025.2", # "questionary==2.1.0", # "redis==6.2.0", # "requests==2.32.4", # "stockstats==0.6.5", # "tqdm==4.67.1", # "tushare==1.4.21", # "typing-extensions==4.14.0", # "yfinance==0.2.63", # ] # main = "main" # params = "" # /// import asyncio from copy import deepcopy import agents import agents.analysts from agents.managers import create_research_manager, create_risk_manager from agents.researchers import create_bear_researcher, create_bull_researcher from agents.risk_debators import ( create_neutral_debator, create_risky_debator, create_safe_debator, ) from agents.trader import create_trader from agents.utils.utils import AgentState from flyte_env import DEEP_THINKING_LLM, QUICK_THINKING_LLM, env, flyte from langchain_openai import ChatOpenAI from reflection import ( reflect_bear_researcher, reflect_bull_researcher, reflect_research_manager, reflect_risk_manager, reflect_trader, ) @env.task async def process_signal(full_signal: str, QUICK_THINKING_LLM: str) -> str: """Process a full trading signal to extract the core decision.""" messages = [ { "role": "system", "content": """You are an efficient assistant designed to analyze paragraphs or financial reports provided by a group of analysts. Your task is to extract the investment decision: SELL, BUY, or HOLD. Provide only the extracted decision (SELL, BUY, or HOLD) as your output, without adding any additional text or information.""", }, {"role": "human", "content": full_signal}, ] return ChatOpenAI(model=QUICK_THINKING_LLM).invoke(messages).content async def run_analyst(analyst_name, state, online_tools): # Create a copy of the state for isolation run_fn = getattr(agents.analysts, f"create_{analyst_name}_analyst") # Run the analyst's chain result_state = await run_fn(QUICK_THINKING_LLM, state, online_tools) # Determine the report key report_key = ( "sentiment_report" if analyst_name == "social_media" else f"{analyst_name}_report" ) report_value = getattr(result_state, report_key) return result_state.messages[1:], report_key, report_value # {{docs-fragment main}} @env.task async def main( selected_analysts: list[str] = [ "market", "fundamentals", "news", "social_media", ], max_debate_rounds: int = 1, max_risk_discuss_rounds: int = 1, online_tools: bool = True, company_name: str = "NVDA", trade_date: str = "2024-05-12", ) -> tuple[str, AgentState]: if not selected_analysts: raise ValueError( "No analysts selected. Please select at least one analyst from market, fundamentals, news, or social_media." ) state = AgentState( messages=[{"role": "human", "content": company_name}], company_of_interest=company_name, trade_date=str(trade_date), ) # Run all analysts concurrently results = await asyncio.gather( *[ run_analyst(analyst, deepcopy(state), online_tools) for analyst in selected_analysts ] ) # Flatten and append all resulting messages into the shared state for messages, report_attr, report in results: state.messages.extend(messages) setattr(state, report_attr, report) # Bull/Bear debate loop state = await create_bull_researcher(QUICK_THINKING_LLM, state) # Start with bull while state.investment_debate_state.count < 2 * max_debate_rounds: current = state.investment_debate_state.current_response if current.startswith("Bull"): state = await create_bear_researcher(QUICK_THINKING_LLM, state) else: state = await create_bull_researcher(QUICK_THINKING_LLM, state) state = await create_research_manager(DEEP_THINKING_LLM, state) state = await create_trader(QUICK_THINKING_LLM, state) # Risk debate loop state = await create_risky_debator(QUICK_THINKING_LLM, state) # Start with risky while state.risk_debate_state.count < 3 * max_risk_discuss_rounds: speaker = state.risk_debate_state.latest_speaker if speaker == "Risky": state = await create_safe_debator(QUICK_THINKING_LLM, state) elif speaker == "Safe": state = await create_neutral_debator(QUICK_THINKING_LLM, state) else: state = await create_risky_debator(QUICK_THINKING_LLM, state) state = await create_risk_manager(DEEP_THINKING_LLM, state) decision = await process_signal(state.final_trade_decision, QUICK_THINKING_LLM) return decision, state # {{/docs-fragment main}} # {{docs-fragment reflect_on_decisions}} @env.task async def reflect_and_store(state: AgentState, returns: str) -> str: await asyncio.gather( reflect_bear_researcher(state, returns), reflect_bull_researcher(state, returns), reflect_trader(state, returns), reflect_risk_manager(state, returns), reflect_research_manager(state, returns), ) return "Reflection completed." # Run the reflection task after the main function @env.task(cache="disable") async def reflect_on_decisions( returns: str, selected_analysts: list[str] = [ "market", "fundamentals", "news", "social_media", ], max_debate_rounds: int = 1, max_risk_discuss_rounds: int = 1, online_tools: bool = True, company_name: str = "NVDA", trade_date: str = "2024-05-12", ) -> str: _, state = await main( selected_analysts, max_debate_rounds, max_risk_discuss_rounds, online_tools, company_name, trade_date, ) return await reflect_and_store(state, returns) # {{/docs-fragment reflect_on_decisions}} # {{docs-fragment execute_main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(main) print(run.url) run.wait() # run = flyte.run(reflect_on_decisions, "+3.2% gain over 5 days") # print(run.url) # {{/docs-fragment execute_main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/trading_agents/main.py* Then run: ``` uv run main.py ``` ## Why Flyte? _(A quick note before you go)_ You might now be wondering: can't I just build all this with Python and LangChain? Absolutely. But as your project grows, you'll likely run into these challenges: 1. **Observability**: Agent workflows can feel opaque. You send a prompt, get a response, but what happened in between? - Were the right tools used? - Were correct arguments passed? - How did the LLM reason through intermediate steps? - Why did it fail? Flyte gives you a window into each of these stages. 2. **Multi-agent coordination**: Real-world applications often require multiple agents with distinct roles and responsibilities. In such cases, you'll need: - Isolated state per agent, - Shared context where needed, - And coordination: sequential or parallel. Managing this manually gets fragile, fast. Flyte handles it for you. 3. **Scalability**: Agents and tools might need to run in isolated or containerized environments. Whether you're scaling out to more agents or more powerful hardware, Flyte lets you scale without taxing your local machine or racking up unnecessary cloud bills. 4. **Durability & recovery**: LLM-based workflows are often long-running and expensive. If something fails halfway: - Do you lose all progress? - Replay everything from scratch? With Flyte, you get built-in caching, checkpointing, and recovery, so you can resume where you left off. === PAGE: https://www.union.ai/docs/v2/union/tutorials/financial-services/fraud-detection-feast === Train an XGBoost fraud classifier and materialize transaction features in Feast for online scoring. # Fraud detection with Feast > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/fraud_detection_feast). This tutorial builds a credit-card fraud detection pipeline that combines [Feast](https://feast.dev/) feature store materialization with an XGBoost classifier on the Sparkov simulated transactions dataset. The workflow engineers transaction and user-level features, trains a model, registers features in Feast, and materializes online feature values for low-latency scoring. Flyte provides: - **Cached data preparation** for the Kaggle dataset download and feature engineering. - **Report-backed training** with confusion matrix and ROC-style metrics in the UI. - **Durable artifacts**: the trained model and Feast repo are returned as `flyte.io.File` and `flyte.io.Dir`. ## Define the task environment ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "feast==0.63.0", # "scikit-learn==1.8.0", # "xgboost==3.2.0", # "joblib", # "pandas", # "pyarrow", # "kagglehub==0.3.12", # ] # main = "fraud_detection_pipeline" # params = "" # /// import json import logging import math import os import shutil import tempfile from datetime import datetime, timedelta, timezone import joblib import numpy as np import pandas as pd import flyte import flyte.io import flyte.report # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="fraud-detection-feast", pre=True) env = flyte.TaskEnvironment( name="fraud-detection-feast", image=main_img, resources=flyte.Resources(cpu=2, memory="4Gi"), ) # {{/docs-fragment env}} import report_helpers as rh logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Feature definitions # # Transaction features: known at scoring time (from the request) # User features: pre-computed aggregates stored in Feast # Derived features: computed at both training and scoring time by # comparing the transaction to the user's profile # ------------------------------------------------------------------ TXN_FEATURE_COLS = ["amt", "amt_log", "category_encoded", "merch_lat", "merch_long"] USER_FEATURE_COLS = [ "txn_count", "mean_amt", "std_amt", "max_amt", "home_lat", "home_long", "age", ] DERIVED_FEATURE_COLS = [ "amt_zscore", "amt_ratio", "distance_from_home", "hour", "day_of_week", ] ALL_FEATURE_COLS = TXN_FEATURE_COLS + USER_FEATURE_COLS + DERIVED_FEATURE_COLS def haversine(lat1, lon1, lat2, lon2): """Compute distance in miles between two (lat, lon) points.""" R = 3959 # Earth radius in miles lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2]) dlat = lat2 - lat1 dlon = lon2 - lon1 a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2 return 2 * R * np.arcsin(np.sqrt(a)) # ------------------------------------------------------------------ # Task 1: Download dataset and engineer features # ------------------------------------------------------------------ @env.task(report=True, cache="auto") async def prepare_data() -> flyte.io.Dir: """Download the Sparkov credit card fraud dataset and prepare parquets.""" import kagglehub log.info("Downloading dataset...") dataset_path = kagglehub.dataset_download("kartik2112/fraud-detection") csv_path = os.path.join(dataset_path, "fraudTrain.csv") df = pd.read_csv(csv_path) log.info(f"Loaded {len(df):,} transactions ({int(df['is_fraud'].sum()):,} fraudulent)") # Sample for workshop speed (stratified to preserve fraud ratio) if len(df) > 500_000: from sklearn.model_selection import train_test_split df, _ = train_test_split(df, train_size=500_000, stratify=df["is_fraud"], random_state=42) log.info(f"Sampled to {len(df):,} transactions") # ------------------------------------------------------------------ # Parse timestamps # ------------------------------------------------------------------ df["event_timestamp"] = pd.to_datetime(df["trans_date_trans_time"]) df["event_timestamp"] = df["event_timestamp"].dt.tz_localize("UTC") df["hour"] = df["event_timestamp"].dt.hour df["day_of_week"] = df["event_timestamp"].dt.dayofweek # ------------------------------------------------------------------ # Map cc_num โ†’ sequential user_id for clean API # ------------------------------------------------------------------ cc_nums = df["cc_num"].unique() cc_to_user = {cc: i for i, cc in enumerate(sorted(cc_nums))} df["user_id"] = df["cc_num"].map(cc_to_user) # ------------------------------------------------------------------ # Feature engineering # ------------------------------------------------------------------ df["amt_log"] = np.log1p(df["amt"]) # Label-encode merchant category categories = sorted(df["category"].unique()) cat_to_int = {cat: i for i, cat in enumerate(categories)} df["category_encoded"] = df["category"].map(cat_to_int) # Compute age from dob df["dob"] = pd.to_datetime(df["dob"]).dt.tz_localize("UTC") ref_date = df["event_timestamp"].max() df["age"] = ((ref_date - df["dob"]).dt.days / 365.25).astype(int) # Distance between buyer and merchant df["distance"] = haversine(df["lat"], df["long"], df["merch_lat"], df["merch_long"]) # ------------------------------------------------------------------ # Build user aggregates # ------------------------------------------------------------------ user_stats = df.groupby("user_id").agg( txn_count=("amt", "count"), mean_amt=("amt", "mean"), std_amt=("amt", "std"), max_amt=("amt", "max"), home_lat=("lat", "median"), home_long=("long", "median"), age=("age", "first"), ).reset_index() user_stats["std_amt"] = user_stats["std_amt"].fillna(0) # Use earliest timestamp so Feast point-in-time joins work for all transactions earliest_ts = df.groupby("user_id")["event_timestamp"].min().reset_index() user_stats = user_stats.merge(earliest_ts, on="user_id") # ------------------------------------------------------------------ # Save to temp directory # ------------------------------------------------------------------ data_dir = tempfile.mkdtemp() txn_cols = [ "user_id", "event_timestamp", "amt", "amt_log", "category_encoded", "merch_lat", "merch_long", "hour", "day_of_week", "lat", "long", "distance", "is_fraud", ] df[txn_cols].to_parquet(os.path.join(data_dir, "transactions.parquet"), index=False) user_stats.to_parquet(os.path.join(data_dir, "user_features.parquet"), index=False) # Save category mapping + cc_num mapping for the app with open(os.path.join(data_dir, "category_mapping.json"), "w") as f: json.dump(cat_to_int, f) with open(os.path.join(data_dir, "user_mapping.json"), "w") as f: json.dump({str(k): v for k, v in cc_to_user.items()}, f) n_fraud = int(df["is_fraud"].sum()) n_legit = len(df) - n_fraud fraud_pct = df["is_fraud"].mean() * 100 html = ( '

Data Prepared

' + rh.stat_grid([ (f"{len(df):,}", "Transactions"), (f"{n_fraud:,}", "Fraudulent"), (f"{fraud_pct:.2f}%", "Fraud Rate"), (f"{user_stats['user_id'].nunique():,}", "Users"), (f"{len(categories)}", "Categories"), ]) + rh.class_distribution_bar(n_legit, n_fraud) ) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() return await flyte.io.Dir.from_local(data_dir) # ------------------------------------------------------------------ # Task 2: Set up Feast and materialize user profiles to online store # ------------------------------------------------------------------ @env.task(report=True) async def materialize_features(data_dir: flyte.io.Dir) -> flyte.io.Dir: """Apply Feast definitions and materialize user profiles to SQLite online store.""" from feast import Entity, FeatureStore, FeatureView, Field, FileSource from feast.types import Float64, Int64 data_path = await data_dir.download() # Create a self-contained Feast repo in a temp directory feast_dir = tempfile.mkdtemp() # Copy parquet into feast dir so the repo is fully self-contained shutil.copy2( os.path.join(data_path, "user_features.parquet"), os.path.join(feast_dir, "user_features.parquet"), ) # Write feature_store.yaml yaml_content = ( "project: fraud_detection\n" f"registry: {feast_dir}/registry.db\n" "provider: local\n" "online_store:\n" " type: sqlite\n" f" path: {feast_dir}/online_store.db\n" "offline_store:\n" " type: file\n" "entity_key_serialization_version: 3\n" ) yaml_path = os.path.join(feast_dir, "feature_store.yaml") with open(yaml_path, "w") as f: f.write(yaml_content) store = FeatureStore(repo_path=feast_dir) # Define entity and feature view user = Entity(name="user", join_keys=["user_id"], description="Credit card holder") user_source = FileSource( path=os.path.join(feast_dir, "user_features.parquet"), timestamp_field="event_timestamp", ) user_stats = FeatureView( name="user_stats", entities=[user], ttl=timedelta(days=0), # No expiry โ€” workshop data has old timestamps schema=[ Field(name="txn_count", dtype=Int64), Field(name="mean_amt", dtype=Float64), Field(name="std_amt", dtype=Float64), Field(name="max_amt", dtype=Float64), Field(name="home_lat", dtype=Float64), Field(name="home_long", dtype=Float64), Field(name="age", dtype=Int64), ], online=True, source=user_source, ) # Apply and materialize log.info("Applying Feast definitions...") store.apply([user, user_stats]) log.info("Materializing user profiles to online store...") store.materialize( start_date=datetime(2018, 1, 1, tzinfo=timezone.utc), end_date=datetime.now(timezone.utc), ) # Re-apply with relative paths so the registry is portable across workers portable_yaml = ( "project: fraud_detection\n" "registry: registry.db\n" "provider: local\n" "online_store:\n" " type: sqlite\n" " path: online_store.db\n" "offline_store:\n" " type: file\n" "entity_key_serialization_version: 3\n" ) with open(yaml_path, "w") as f: f.write(portable_yaml) # Re-apply with relative source path so get_historical_features works on other workers store = FeatureStore(repo_path=feast_dir) user_source = FileSource( path="user_features.parquet", timestamp_field="event_timestamp", ) user_stats = FeatureView( name="user_stats", entities=[user], ttl=timedelta(days=0), schema=[ Field(name="txn_count", dtype=Int64), Field(name="mean_amt", dtype=Float64), Field(name="std_amt", dtype=Float64), Field(name="max_amt", dtype=Float64), Field(name="home_lat", dtype=Float64), Field(name="home_long", dtype=Float64), Field(name="age", dtype=Int64), ], online=True, source=user_source, ) store.apply([user, user_stats]) features = ["txn_count", "mean_amt", "std_amt", "max_amt", "home_lat", "home_long", "age"] html = ( '

Feature Store Materialized

' + rh.stat_grid([ ("user_stats", "Feature View"), (str(len(features)), "Features"), ("SQLite", "Online Store"), ]) + '

Materialized Features

' '' '' '' '' '' '' '' '' '' '
FeatureTypeDescription
txn_countInt64Total transactions
mean_amtFloat64Average transaction amount
std_amtFloat64Std dev of amounts
max_amtFloat64Max transaction amount
home_latFloat64Home latitude (median)
home_longFloat64Home longitude (median)
ageInt64User age
' '
User profiles are ready for real-time serving via the scoring app.
' ) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() return await flyte.io.Dir.from_local(feast_dir) # ------------------------------------------------------------------ # Task 3: Train XGBoost model # ------------------------------------------------------------------ @env.task(report=True) async def train_model( data_dir: flyte.io.Dir, feast_dir: flyte.io.Dir, n_estimators: int = 300, max_depth: int = 6, learning_rate: float = 0.1, min_child_weight: int = 5, gamma: float = 1.0, ) -> flyte.io.File: """Train an XGBoost classifier using Feast for feature retrieval.""" from feast import FeatureStore from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, roc_auc_score, confusion_matrix from xgboost import XGBClassifier data_path = await data_dir.download() feast_path = await feast_dir.download() txn_df = pd.read_parquet(os.path.join(data_path, "transactions.parquet")) with open(os.path.join(data_path, "category_mapping.json")) as f: category_mapping = json.load(f) # Fetch user features from Feast (same path as serving) store = FeatureStore(repo_path=feast_path) entity_df = txn_df[["user_id", "event_timestamp"]].copy() log.info("Fetching user features from Feast (get_historical_features)...") training_data = store.get_historical_features( entity_df=entity_df, features=[ "user_stats:txn_count", "user_stats:mean_amt", "user_stats:std_amt", "user_stats:max_amt", "user_stats:home_lat", "user_stats:home_long", "user_stats:age", ], ).to_df() # Merge back transaction features (Feast only returns user profile) training_data = training_data.merge( txn_df[["user_id", "event_timestamp", "amt", "amt_log", "category_encoded", "merch_lat", "merch_long", "hour", "day_of_week", "is_fraud"]], on=["user_id", "event_timestamp"], how="inner", ) # Derived features: compare this transaction to the user's profile training_data["amt_zscore"] = ( (training_data["amt"] - training_data["mean_amt"]) / training_data["std_amt"].replace(0, 1) ) training_data["amt_ratio"] = ( training_data["amt"] / training_data["mean_amt"].replace(0, 1) ) training_data["distance_from_home"] = haversine( training_data["home_lat"], training_data["home_long"], training_data["merch_lat"], training_data["merch_long"], ) training_data = training_data.dropna(subset=ALL_FEATURE_COLS) X = training_data[ALL_FEATURE_COLS].values y = training_data["is_fraud"].values log.info(f"Training on {len(X):,} rows, {int(y.sum()):,} fraud") X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y, ) n_legit = int((y_train == 0).sum()) n_fraud = int((y_train == 1).sum()) scale_pos_weight = n_legit / max(n_fraud, 1) model = XGBClassifier( n_estimators=n_estimators, max_depth=max_depth, learning_rate=learning_rate, scale_pos_weight=scale_pos_weight, min_child_weight=min_child_weight, gamma=gamma, random_state=42, eval_metric="logloss", ) model.fit(X_train, y_train) # Evaluate y_pred = model.predict(X_test) y_proba = model.predict_proba(X_test)[:, 1] auc = roc_auc_score(y_test, y_proba) cm = confusion_matrix(y_test, y_pred) report = classification_report(y_test, y_pred, target_names=["Legit", "Fraud"]) log.info(f"AUC-ROC: {auc:.4f}") log.info(f"\n{report}") # Report precision_fraud = cm[1][1] / max(cm[1][1] + cm[0][1], 1) * 100 recall_fraud = cm[1][1] / max(cm[1][1] + cm[1][0], 1) * 100 html = ( '

Model Performance

' + rh.stat_grid([ (f"{auc:.4f}", "AUC-ROC"), (f"{len(X_train):,}", "Training Samples"), (f"{len(X_test):,}", "Test Samples"), (f"{precision_fraud:.1f}%", "Fraud Precision"), (f"{recall_fraud:.1f}%", "Fraud Recall"), ]) + rh.confusion_matrix_html(cm) ) # Feature importance bar chart importance = model.feature_importances_ top_idx = np.argsort(importance)[::-1] top_labels = [ALL_FEATURE_COLS[i] for i in top_idx] top_values = [float(importance[i]) for i in top_idx] html += '

Feature Importance

' html += f'
{rh.horizontal_bar_chart(top_labels, top_values)}
' await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() # Save model + metadata model_path = os.path.join(tempfile.mkdtemp(), "model.joblib") joblib.dump({ "model": model, "auc_roc": auc, "feature_cols": ALL_FEATURE_COLS, "category_mapping": category_mapping, }, model_path) return await flyte.io.File.from_local(model_path) # ------------------------------------------------------------------ # Orchestrator: prepare โ†’ materialize โ†’ train # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @env.task(report=True) async def fraud_detection_pipeline( n_estimators: int = 300, max_depth: int = 6, learning_rate: float = 0.1, min_child_weight: int = 5, gamma: float = 1.0, ) -> tuple[flyte.io.File, flyte.io.Dir]: """ Full fraud detection pipeline: 1. Download and prepare data 2. Materialize user profiles to Feast 3. Train model using Feast for feature retrieval Returns model file and Feast artifacts for serving. """ log.info("Starting fraud detection pipeline") steps = ["Prepare Data", "Materialize Features", "Train Model", "Done"] html = '

Fraud Detection Pipeline

' + rh.pipeline_step_indicator(0, steps) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() data_dir = await prepare_data() html = '

Fraud Detection Pipeline

' + rh.pipeline_step_indicator(1, steps) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() # Materialize features first so training can use Feast feast_dir = await materialize_features(data_dir) html = '

Fraud Detection Pipeline

' + rh.pipeline_step_indicator(2, steps) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() # Train model using Feast for user feature retrieval model_file = await train_model( data_dir, feast_dir, n_estimators=n_estimators, max_depth=max_depth, learning_rate=learning_rate, min_child_weight=min_child_weight, gamma=gamma, ) # Save copies to working directory for local app testing model_local = await model_file.download() feast_local = await feast_dir.download() shutil.copy2(model_local, "model.joblib") if os.path.exists("feast_artifacts"): shutil.rmtree("feast_artifacts") shutil.copytree(feast_local, "feast_artifacts") log.info("Saved local copies: model.joblib, feast_artifacts/") html = ( '

Fraud Detection Pipeline

' + rh.pipeline_step_indicator(4, steps) + '
' '
Pipeline Complete
' '

Model and feature store artifacts are ready for serving.

' '' '' '' '' '' '
Next StepCommand
Run locallypython app.py
Deploy scoring appflyte deploy app.py serving_env
Deploy dashboardflyte deploy dashboard.py dashboard_env
' ) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() log.info("Pipeline complete") return model_file, feast_dir # {{/docs-fragment pipeline}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(fraud_detection_pipeline) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/fraud_detection_feast/fraud_detection_feast.py* ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "feast==0.63.0", # "xgboost==3.2.0", # "scikit-learn==1.8.0", # "kagglehub==0.3.12", # ... # ] # /// ``` ## Orchestrate the pipeline The `fraud_detection_pipeline` task downloads data, trains XGBoost, applies Feast feature definitions, and materializes features. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "feast==0.63.0", # "scikit-learn==1.8.0", # "xgboost==3.2.0", # "joblib", # "pandas", # "pyarrow", # "kagglehub==0.3.12", # ] # main = "fraud_detection_pipeline" # params = "" # /// import json import logging import math import os import shutil import tempfile from datetime import datetime, timedelta, timezone import joblib import numpy as np import pandas as pd import flyte import flyte.io import flyte.report # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="fraud-detection-feast", pre=True) env = flyte.TaskEnvironment( name="fraud-detection-feast", image=main_img, resources=flyte.Resources(cpu=2, memory="4Gi"), ) # {{/docs-fragment env}} import report_helpers as rh logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Feature definitions # # Transaction features: known at scoring time (from the request) # User features: pre-computed aggregates stored in Feast # Derived features: computed at both training and scoring time by # comparing the transaction to the user's profile # ------------------------------------------------------------------ TXN_FEATURE_COLS = ["amt", "amt_log", "category_encoded", "merch_lat", "merch_long"] USER_FEATURE_COLS = [ "txn_count", "mean_amt", "std_amt", "max_amt", "home_lat", "home_long", "age", ] DERIVED_FEATURE_COLS = [ "amt_zscore", "amt_ratio", "distance_from_home", "hour", "day_of_week", ] ALL_FEATURE_COLS = TXN_FEATURE_COLS + USER_FEATURE_COLS + DERIVED_FEATURE_COLS def haversine(lat1, lon1, lat2, lon2): """Compute distance in miles between two (lat, lon) points.""" R = 3959 # Earth radius in miles lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2]) dlat = lat2 - lat1 dlon = lon2 - lon1 a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2 return 2 * R * np.arcsin(np.sqrt(a)) # ------------------------------------------------------------------ # Task 1: Download dataset and engineer features # ------------------------------------------------------------------ @env.task(report=True, cache="auto") async def prepare_data() -> flyte.io.Dir: """Download the Sparkov credit card fraud dataset and prepare parquets.""" import kagglehub log.info("Downloading dataset...") dataset_path = kagglehub.dataset_download("kartik2112/fraud-detection") csv_path = os.path.join(dataset_path, "fraudTrain.csv") df = pd.read_csv(csv_path) log.info(f"Loaded {len(df):,} transactions ({int(df['is_fraud'].sum()):,} fraudulent)") # Sample for workshop speed (stratified to preserve fraud ratio) if len(df) > 500_000: from sklearn.model_selection import train_test_split df, _ = train_test_split(df, train_size=500_000, stratify=df["is_fraud"], random_state=42) log.info(f"Sampled to {len(df):,} transactions") # ------------------------------------------------------------------ # Parse timestamps # ------------------------------------------------------------------ df["event_timestamp"] = pd.to_datetime(df["trans_date_trans_time"]) df["event_timestamp"] = df["event_timestamp"].dt.tz_localize("UTC") df["hour"] = df["event_timestamp"].dt.hour df["day_of_week"] = df["event_timestamp"].dt.dayofweek # ------------------------------------------------------------------ # Map cc_num โ†’ sequential user_id for clean API # ------------------------------------------------------------------ cc_nums = df["cc_num"].unique() cc_to_user = {cc: i for i, cc in enumerate(sorted(cc_nums))} df["user_id"] = df["cc_num"].map(cc_to_user) # ------------------------------------------------------------------ # Feature engineering # ------------------------------------------------------------------ df["amt_log"] = np.log1p(df["amt"]) # Label-encode merchant category categories = sorted(df["category"].unique()) cat_to_int = {cat: i for i, cat in enumerate(categories)} df["category_encoded"] = df["category"].map(cat_to_int) # Compute age from dob df["dob"] = pd.to_datetime(df["dob"]).dt.tz_localize("UTC") ref_date = df["event_timestamp"].max() df["age"] = ((ref_date - df["dob"]).dt.days / 365.25).astype(int) # Distance between buyer and merchant df["distance"] = haversine(df["lat"], df["long"], df["merch_lat"], df["merch_long"]) # ------------------------------------------------------------------ # Build user aggregates # ------------------------------------------------------------------ user_stats = df.groupby("user_id").agg( txn_count=("amt", "count"), mean_amt=("amt", "mean"), std_amt=("amt", "std"), max_amt=("amt", "max"), home_lat=("lat", "median"), home_long=("long", "median"), age=("age", "first"), ).reset_index() user_stats["std_amt"] = user_stats["std_amt"].fillna(0) # Use earliest timestamp so Feast point-in-time joins work for all transactions earliest_ts = df.groupby("user_id")["event_timestamp"].min().reset_index() user_stats = user_stats.merge(earliest_ts, on="user_id") # ------------------------------------------------------------------ # Save to temp directory # ------------------------------------------------------------------ data_dir = tempfile.mkdtemp() txn_cols = [ "user_id", "event_timestamp", "amt", "amt_log", "category_encoded", "merch_lat", "merch_long", "hour", "day_of_week", "lat", "long", "distance", "is_fraud", ] df[txn_cols].to_parquet(os.path.join(data_dir, "transactions.parquet"), index=False) user_stats.to_parquet(os.path.join(data_dir, "user_features.parquet"), index=False) # Save category mapping + cc_num mapping for the app with open(os.path.join(data_dir, "category_mapping.json"), "w") as f: json.dump(cat_to_int, f) with open(os.path.join(data_dir, "user_mapping.json"), "w") as f: json.dump({str(k): v for k, v in cc_to_user.items()}, f) n_fraud = int(df["is_fraud"].sum()) n_legit = len(df) - n_fraud fraud_pct = df["is_fraud"].mean() * 100 html = ( '

Data Prepared

' + rh.stat_grid([ (f"{len(df):,}", "Transactions"), (f"{n_fraud:,}", "Fraudulent"), (f"{fraud_pct:.2f}%", "Fraud Rate"), (f"{user_stats['user_id'].nunique():,}", "Users"), (f"{len(categories)}", "Categories"), ]) + rh.class_distribution_bar(n_legit, n_fraud) ) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() return await flyte.io.Dir.from_local(data_dir) # ------------------------------------------------------------------ # Task 2: Set up Feast and materialize user profiles to online store # ------------------------------------------------------------------ @env.task(report=True) async def materialize_features(data_dir: flyte.io.Dir) -> flyte.io.Dir: """Apply Feast definitions and materialize user profiles to SQLite online store.""" from feast import Entity, FeatureStore, FeatureView, Field, FileSource from feast.types import Float64, Int64 data_path = await data_dir.download() # Create a self-contained Feast repo in a temp directory feast_dir = tempfile.mkdtemp() # Copy parquet into feast dir so the repo is fully self-contained shutil.copy2( os.path.join(data_path, "user_features.parquet"), os.path.join(feast_dir, "user_features.parquet"), ) # Write feature_store.yaml yaml_content = ( "project: fraud_detection\n" f"registry: {feast_dir}/registry.db\n" "provider: local\n" "online_store:\n" " type: sqlite\n" f" path: {feast_dir}/online_store.db\n" "offline_store:\n" " type: file\n" "entity_key_serialization_version: 3\n" ) yaml_path = os.path.join(feast_dir, "feature_store.yaml") with open(yaml_path, "w") as f: f.write(yaml_content) store = FeatureStore(repo_path=feast_dir) # Define entity and feature view user = Entity(name="user", join_keys=["user_id"], description="Credit card holder") user_source = FileSource( path=os.path.join(feast_dir, "user_features.parquet"), timestamp_field="event_timestamp", ) user_stats = FeatureView( name="user_stats", entities=[user], ttl=timedelta(days=0), # No expiry โ€” workshop data has old timestamps schema=[ Field(name="txn_count", dtype=Int64), Field(name="mean_amt", dtype=Float64), Field(name="std_amt", dtype=Float64), Field(name="max_amt", dtype=Float64), Field(name="home_lat", dtype=Float64), Field(name="home_long", dtype=Float64), Field(name="age", dtype=Int64), ], online=True, source=user_source, ) # Apply and materialize log.info("Applying Feast definitions...") store.apply([user, user_stats]) log.info("Materializing user profiles to online store...") store.materialize( start_date=datetime(2018, 1, 1, tzinfo=timezone.utc), end_date=datetime.now(timezone.utc), ) # Re-apply with relative paths so the registry is portable across workers portable_yaml = ( "project: fraud_detection\n" "registry: registry.db\n" "provider: local\n" "online_store:\n" " type: sqlite\n" " path: online_store.db\n" "offline_store:\n" " type: file\n" "entity_key_serialization_version: 3\n" ) with open(yaml_path, "w") as f: f.write(portable_yaml) # Re-apply with relative source path so get_historical_features works on other workers store = FeatureStore(repo_path=feast_dir) user_source = FileSource( path="user_features.parquet", timestamp_field="event_timestamp", ) user_stats = FeatureView( name="user_stats", entities=[user], ttl=timedelta(days=0), schema=[ Field(name="txn_count", dtype=Int64), Field(name="mean_amt", dtype=Float64), Field(name="std_amt", dtype=Float64), Field(name="max_amt", dtype=Float64), Field(name="home_lat", dtype=Float64), Field(name="home_long", dtype=Float64), Field(name="age", dtype=Int64), ], online=True, source=user_source, ) store.apply([user, user_stats]) features = ["txn_count", "mean_amt", "std_amt", "max_amt", "home_lat", "home_long", "age"] html = ( '

Feature Store Materialized

' + rh.stat_grid([ ("user_stats", "Feature View"), (str(len(features)), "Features"), ("SQLite", "Online Store"), ]) + '

Materialized Features

' '' '' '' '' '' '' '' '' '' '
FeatureTypeDescription
txn_countInt64Total transactions
mean_amtFloat64Average transaction amount
std_amtFloat64Std dev of amounts
max_amtFloat64Max transaction amount
home_latFloat64Home latitude (median)
home_longFloat64Home longitude (median)
ageInt64User age
' '
User profiles are ready for real-time serving via the scoring app.
' ) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() return await flyte.io.Dir.from_local(feast_dir) # ------------------------------------------------------------------ # Task 3: Train XGBoost model # ------------------------------------------------------------------ @env.task(report=True) async def train_model( data_dir: flyte.io.Dir, feast_dir: flyte.io.Dir, n_estimators: int = 300, max_depth: int = 6, learning_rate: float = 0.1, min_child_weight: int = 5, gamma: float = 1.0, ) -> flyte.io.File: """Train an XGBoost classifier using Feast for feature retrieval.""" from feast import FeatureStore from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, roc_auc_score, confusion_matrix from xgboost import XGBClassifier data_path = await data_dir.download() feast_path = await feast_dir.download() txn_df = pd.read_parquet(os.path.join(data_path, "transactions.parquet")) with open(os.path.join(data_path, "category_mapping.json")) as f: category_mapping = json.load(f) # Fetch user features from Feast (same path as serving) store = FeatureStore(repo_path=feast_path) entity_df = txn_df[["user_id", "event_timestamp"]].copy() log.info("Fetching user features from Feast (get_historical_features)...") training_data = store.get_historical_features( entity_df=entity_df, features=[ "user_stats:txn_count", "user_stats:mean_amt", "user_stats:std_amt", "user_stats:max_amt", "user_stats:home_lat", "user_stats:home_long", "user_stats:age", ], ).to_df() # Merge back transaction features (Feast only returns user profile) training_data = training_data.merge( txn_df[["user_id", "event_timestamp", "amt", "amt_log", "category_encoded", "merch_lat", "merch_long", "hour", "day_of_week", "is_fraud"]], on=["user_id", "event_timestamp"], how="inner", ) # Derived features: compare this transaction to the user's profile training_data["amt_zscore"] = ( (training_data["amt"] - training_data["mean_amt"]) / training_data["std_amt"].replace(0, 1) ) training_data["amt_ratio"] = ( training_data["amt"] / training_data["mean_amt"].replace(0, 1) ) training_data["distance_from_home"] = haversine( training_data["home_lat"], training_data["home_long"], training_data["merch_lat"], training_data["merch_long"], ) training_data = training_data.dropna(subset=ALL_FEATURE_COLS) X = training_data[ALL_FEATURE_COLS].values y = training_data["is_fraud"].values log.info(f"Training on {len(X):,} rows, {int(y.sum()):,} fraud") X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y, ) n_legit = int((y_train == 0).sum()) n_fraud = int((y_train == 1).sum()) scale_pos_weight = n_legit / max(n_fraud, 1) model = XGBClassifier( n_estimators=n_estimators, max_depth=max_depth, learning_rate=learning_rate, scale_pos_weight=scale_pos_weight, min_child_weight=min_child_weight, gamma=gamma, random_state=42, eval_metric="logloss", ) model.fit(X_train, y_train) # Evaluate y_pred = model.predict(X_test) y_proba = model.predict_proba(X_test)[:, 1] auc = roc_auc_score(y_test, y_proba) cm = confusion_matrix(y_test, y_pred) report = classification_report(y_test, y_pred, target_names=["Legit", "Fraud"]) log.info(f"AUC-ROC: {auc:.4f}") log.info(f"\n{report}") # Report precision_fraud = cm[1][1] / max(cm[1][1] + cm[0][1], 1) * 100 recall_fraud = cm[1][1] / max(cm[1][1] + cm[1][0], 1) * 100 html = ( '

Model Performance

' + rh.stat_grid([ (f"{auc:.4f}", "AUC-ROC"), (f"{len(X_train):,}", "Training Samples"), (f"{len(X_test):,}", "Test Samples"), (f"{precision_fraud:.1f}%", "Fraud Precision"), (f"{recall_fraud:.1f}%", "Fraud Recall"), ]) + rh.confusion_matrix_html(cm) ) # Feature importance bar chart importance = model.feature_importances_ top_idx = np.argsort(importance)[::-1] top_labels = [ALL_FEATURE_COLS[i] for i in top_idx] top_values = [float(importance[i]) for i in top_idx] html += '

Feature Importance

' html += f'
{rh.horizontal_bar_chart(top_labels, top_values)}
' await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() # Save model + metadata model_path = os.path.join(tempfile.mkdtemp(), "model.joblib") joblib.dump({ "model": model, "auc_roc": auc, "feature_cols": ALL_FEATURE_COLS, "category_mapping": category_mapping, }, model_path) return await flyte.io.File.from_local(model_path) # ------------------------------------------------------------------ # Orchestrator: prepare โ†’ materialize โ†’ train # ------------------------------------------------------------------ # {{docs-fragment pipeline}} @env.task(report=True) async def fraud_detection_pipeline( n_estimators: int = 300, max_depth: int = 6, learning_rate: float = 0.1, min_child_weight: int = 5, gamma: float = 1.0, ) -> tuple[flyte.io.File, flyte.io.Dir]: """ Full fraud detection pipeline: 1. Download and prepare data 2. Materialize user profiles to Feast 3. Train model using Feast for feature retrieval Returns model file and Feast artifacts for serving. """ log.info("Starting fraud detection pipeline") steps = ["Prepare Data", "Materialize Features", "Train Model", "Done"] html = '

Fraud Detection Pipeline

' + rh.pipeline_step_indicator(0, steps) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() data_dir = await prepare_data() html = '

Fraud Detection Pipeline

' + rh.pipeline_step_indicator(1, steps) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() # Materialize features first so training can use Feast feast_dir = await materialize_features(data_dir) html = '

Fraud Detection Pipeline

' + rh.pipeline_step_indicator(2, steps) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() # Train model using Feast for user feature retrieval model_file = await train_model( data_dir, feast_dir, n_estimators=n_estimators, max_depth=max_depth, learning_rate=learning_rate, min_child_weight=min_child_weight, gamma=gamma, ) # Save copies to working directory for local app testing model_local = await model_file.download() feast_local = await feast_dir.download() shutil.copy2(model_local, "model.joblib") if os.path.exists("feast_artifacts"): shutil.rmtree("feast_artifacts") shutil.copytree(feast_local, "feast_artifacts") log.info("Saved local copies: model.joblib, feast_artifacts/") html = ( '

Fraud Detection Pipeline

' + rh.pipeline_step_indicator(4, steps) + '
' '
Pipeline Complete
' '

Model and feature store artifacts are ready for serving.

' '' '' '' '' '' '
Next StepCommand
Run locallypython app.py
Deploy scoring appflyte deploy app.py serving_env
Deploy dashboardflyte deploy dashboard.py dashboard_env
' ) await flyte.report.replace.aio(rh.wrap(html)) await flyte.report.flush.aio() log.info("Pipeline complete") return model_file, feast_dir # {{/docs-fragment pipeline}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(fraud_detection_pipeline) print(run.url) run.wait() ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/fraud_detection_feast/fraud_detection_feast.py* ## Run the workflow From the [example directory](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/fraud_detection_feast): ``` cd v2/tutorials/fraud_detection_feast uv run --script fraud_detection_feast.py ``` The first run downloads the dataset via `kagglehub` (public dataset, no API key required). Open the run report to review the confusion matrix and feature-importance summary when training completes. === PAGE: https://www.union.ai/docs/v2/union/tutorials/financial-services/financial-research-agent === Prep equity briefings for the earnings cycle with grounded You.com Research synthesis and fresh news from the Search API. # Financial research agent > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/financial_research_agent). This example demonstrates how to build a financial research and earnings-cycle agent on Flyte. For each company, the agent runs grounded, source-cited research and fresh news, then synthesizes an analyst-ready equity briefing. Financial research benefits from **low-latency, ranked, source-cited results** across both the general web and news streams. The [You.com Research API](https://you.com/docs/research/overview) produces a grounded, citation-backed synthesis, and the [You.com Search API](https://you.com/docs/search/overview) adds a fresh-news layer. [Claude](https://docs.anthropic.com/) via [LiteLLM](https://docs.litellm.ai/) turns that evidence into an analyst-ready briefing. Flyte's `cache="auto"` reuses prior results when runs converge on the same companies. Flyte provides: - **Fan-out parallelism** across companies - **`cache="auto"`** to reuse prior You.com and LLM results across converging runs - **`@flyte.trace`** on every external call for full prompt โ†’ citation lineage - **Flyte reports** with thesis, risks, watch items, and source citations per company ![Financial research agent report](../../../_static/images/tutorials/financial_research_agent/financial-research-agent.png) ## Setting up the environment The agent runs in a `TaskEnvironment` with secrets for the You.com and Anthropic API keys, automatic caching, and a container image built from the `uv` script dependencies. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.4.0", # "httpx>=0.27.0", # "litellm>=1.72.0", # ] # main = "financial_research" # params = "" # /// """Financial research & earnings-cycle agent. For each company, runs grounded, source-cited research via the You.com Research API plus a fresh-news layer via the Search API, then uses Claude to synthesize an analyst-ready equity briefing that preserves citations. Flyte caching cuts duplicate spend when runs converge. """ # {{docs-fragment env}} import asyncio import json import os from dataclasses import dataclass, field import flyte MODEL = "anthropic/claude-haiku-4-5" env = flyte.TaskEnvironment( name="financial-research", secrets=[ flyte.Secret(key="youdotcom-api-key", as_env_var="YDC_API_KEY"), flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], image=flyte.Image.from_uv_script(__file__, name="financial-research", pre=True), resources=flyte.Resources(cpu="1", memory="1Gi"), cache="auto", ) # {{/docs-fragment env}} # {{docs-fragment data_types}} @dataclass class Source: title: str url: str domain: str = "" snippet: str = "" published: str = "" favicon: str = "" section: str = "research" # "research", "news", or "web" def _domain(url: str) -> str: from urllib.parse import urlparse try: return urlparse(url).netloc.replace("www.", "") except Exception: return "" def _favicon_for(url: str) -> str: return f"https://ydc-index.io/favicon?domain={_domain(url)}&size=128" @dataclass class Briefing: company: str thesis: str recent_developments: list[str] = field(default_factory=list) risks: list[str] = field(default_factory=list) watch_items: list[str] = field(default_factory=list) sources: list[Source] = field(default_factory=list) @dataclass class ResearchReport: briefings: list[Briefing] = field(default_factory=list) # {{/docs-fragment data_types}} # {{docs-fragment you_apis}} YOU_RESEARCH_URL = "https://api.you.com/v1/research" YOU_SEARCH_URL = "https://ydc-index.io/v1/search" async def _you_request(method: str, url: str, timeout: float, **kwargs) -> dict: """HTTP wrapper with exponential backoff + jitter on 429 rate limits. Fanned-out tasks run in separate pods, so we retry on the client side to smooth out bursts against the You.com API rate limit. """ import asyncio import random import httpx # YDC_API_KEY is canonical; YOU_API_KEY accepted as a backwards-compatible fallback. headers = {"X-API-Key": os.environ.get("YDC_API_KEY") or os.environ["YOU_API_KEY"]} if method == "POST": headers["Content-Type"] = "application/json" async with httpx.AsyncClient(timeout=timeout) as client: for attempt in range(7): resp = await client.request(method, url, headers=headers, **kwargs) if resp.status_code == 429 and attempt < 6: wait = float(resp.headers.get("retry-after") or 0) or min(2**attempt, 30) await asyncio.sleep(wait + random.uniform(0, 2)) continue resp.raise_for_status() return resp.json() resp.raise_for_status() return resp.json() @flyte.trace async def you_research(question: str, research_effort: str, freshness: str) -> dict: """Grounded, citation-backed research answer.""" body = { "input": question, "research_effort": research_effort, "source_control": {"freshness": freshness}, } return await _you_request("POST", YOU_RESEARCH_URL, 300.0, json=body) @flyte.trace async def you_news( query: str, count: int = 10, freshness: str = "week", boost_domains: str = "", ) -> list[dict]: """Fresh news headlines for a company. ``boost_domains`` (comma-separated) lifts authoritative financial outlets in ranking without restricting results to only those domains, so company press releases and niche coverage still surface when relevant. """ params: dict = {"query": query, "count": count, "freshness": freshness} if boost_domains: params["boost_domains"] = boost_domains data = await _you_request("GET", YOU_SEARCH_URL, 60.0, params=params) results = data.get("results", {}) out: list[dict] = [] for section in ("news", "web"): for item in results.get(section, []) or []: snippets = item.get("snippets") or [] url = item.get("url", "") out.append( { "title": item.get("title", ""), "url": url, "domain": _domain(url), "snippet": snippets[0] if snippets else item.get("description", ""), "published": item.get("page_age", "") or "", "favicon": item.get("favicon_url") or _favicon_for(url), "section": section, } ) return out # {{/docs-fragment you_apis}} # {{docs-fragment llm}} @flyte.trace async def synthesize_briefing(company: str, focus: str, research: str, news: str) -> dict: """Use Claude to synthesize a structured equity briefing.""" from litellm import acompletion system = ( "You are an equity research analyst. Using ONLY the grounded research " "and news provided, write a concise briefing. Respond ONLY with JSON: " '{"thesis": str, "recent_developments": [str], "risks": [str], ' '"watch_items": [str]}. Keep each list to 3-5 short, specific bullets.' ) user = ( f"Company: {company}\nFocus: {focus}\n\n" f"Grounded research:\n{research}\n\nRecent news:\n{news}" ) resp = await acompletion( model=MODEL, messages=[ {"role": "system", "content": system}, {"role": "user", "content": user}, ], temperature=0.0, max_tokens=1536, ) parsed = _parse_json(resp.choices[0].message.content) return parsed if isinstance(parsed, dict) else {} def _parse_json(text: str) -> dict | list: text = text.strip() if text.startswith("CODE0", 2)[1] if text.lstrip().startswith("json"): text = text.lstrip()[4:] start = min((i for i in (text.find("{"), text.find("[")) if i != -1), default=0) end = max(text.rfind("}"), text.rfind("]")) + 1 return json.loads(text[start:end]) # {{/docs-fragment llm}} # {{docs-fragment research_company}} # Tier-1 financial outlets that consistently break earnings, M&A, and # analyst-moving news. boost_domains lifts these in ranking without excluding # other sources, so company press releases and trade-press coverage still # surface when relevant. FINANCE_BOOST_DOMAINS = "reuters.com,bloomberg.com,wsj.com,marketwatch.com,cnbc.com,ft.com" @env.task(retries=3) async def research_company( company: str, focus: str, research_effort: str, freshness: str, ) -> Briefing: """Research one company and synthesize a cited briefing.""" question = ( f"Provide a grounded analysis of {company} with respect to: {focus}. " f"Cover recent financial performance, strategic moves, competitive " f"positioning, and risks." ) research_result, news = await asyncio.gather( you_research(question, research_effort, freshness), you_news( f"{company} earnings news", freshness=freshness, boost_domains=FINANCE_BOOST_DOMAINS, ), ) output = research_result.get("output", {}) research_text = output.get("content", "") if not isinstance(research_text, str): research_text = json.dumps(research_text) sources: list[Source] = [] for s in output.get("sources", []) or []: url = str(s.get("url", "")) sources.append( Source( title=str(s.get("title", "") or url), url=url, domain=_domain(url), snippet=str((s.get("snippets") or [""])[0]), favicon=_favicon_for(url), section="research", ) ) for n in news: sources.append( Source( title=str(n.get("title", "")), url=str(n.get("url", "")), domain=str(n.get("domain", "")), snippet=str(n.get("snippet", "")), published=str(n.get("published", "")), favicon=str(n.get("favicon", "")), section=str(n.get("section", "web")), ) ) news_text = "\n".join( f"- {n['title']} ({n['published']}) {n['domain']}: {n['snippet'][:120]}" for n in news ) parsed = await synthesize_briefing(company, focus, research_text, news_text) def _list(key: str) -> list[str]: return [str(x) for x in (parsed.get(key) or [])] return Briefing( company=company, thesis=str(parsed.get("thesis", "")), recent_developments=_list("recent_developments"), risks=_list("risks"), watch_items=_list("watch_items"), sources=sources, ) # {{/docs-fragment research_company}} # {{docs-fragment report}} REPORT_CSS = """ """ def _cite(s: Source) -> str: """Render a rich You.com citation (Research or Search source).""" if not s.url: return "" tag_cls = s.section if s.section in ("research", "news") else "web" meta_bits = [] if s.published: meta_bits.append(s.published[:10]) if s.title: meta_bits.append(s.title) meta = " · ".join(meta_bits) snip = f"
“{s.snippet}”
" if s.snippet else "" return ( f"
" f"
" f"{s.domain or 'source'}" f"{s.section}" f"
{meta}
{snip}
" ) def _render_report(report: ResearchReport) -> str: def _ul(items: list[str]) -> str: if not items: return "

None reported.

" return "
    " + "".join(f"
  • {x}
  • " for x in items) + "
" cards = [] for b in report.briefings: src = "".join(_cite(s) for s in b.sources[:10]) cards.append( f"

{b.company}

" f"
{b.thesis or 'No thesis generated.'}
" f"
" f"

Recent developments

{_ul(b.recent_developments)}
" f"

Risks

{_ul(b.risks)}
" f"

Watch items

{_ul(b.watch_items)}
" f"
" + (f"

You.com sources ({len(b.sources)})

{src}
" if src else "") + "
" ) total_sources = sum(len(b.sources) for b in report.briefings) return f""" {REPORT_CSS}

Financial Research Briefings

Grounded, citation-backed equity briefings โ€” each company backed by You.com Research synthesis plus fresh Search news.

{len(report.briefings)} companies {total_sources} You.com sources cited
{''.join(cards) or "

No briefings generated.

"}

Research answers from the You.com Research API (grounded synthesis with inline citations) plus fresh headlines from the You.com Search API (web + auto-classified news with timestamps and snippets).

""" # {{/docs-fragment report}} # {{docs-fragment driver}} @env.task(report=True) async def financial_research( companies: list[str] = [ "NVIDIA", "Advanced Micro Devices", "Microsoft", "Alphabet", "Amazon", "Meta Platforms", "Broadcom", "Taiwan Semiconductor Manufacturing", ], focus: str = "Q4 earnings preview and competitive positioning", research_effort: str = "standard", freshness: str = "month", ) -> ResearchReport: """Fan out across companies and aggregate cited equity briefings.""" with flyte.group("research-companies"): briefings = await asyncio.gather( *[ research_company(c, focus, research_effort, freshness) for c in companies ] ) report = ResearchReport(briefings=list(briefings)) await flyte.report.replace.aio(_render_report(report), do_flush=True) await flyte.report.flush.aio() return report # {{/docs-fragment driver}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(financial_research) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/financial_research_agent/main.py* The Python packages are declared at the top of the file using the `uv` script style: CODE1 ## Data types Each `Briefing` carries a thesis, recent developments, risks, watch items, and a list of `Source` objects from both the Research and Search APIs. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.4.0", # "httpx>=0.27.0", # "litellm>=1.72.0", # ] # main = "financial_research" # params = "" # /// """Financial research & earnings-cycle agent. For each company, runs grounded, source-cited research via the You.com Research API plus a fresh-news layer via the Search API, then uses Claude to synthesize an analyst-ready equity briefing that preserves citations. Flyte caching cuts duplicate spend when runs converge. """ # {{docs-fragment env}} import asyncio import json import os from dataclasses import dataclass, field import flyte MODEL = "anthropic/claude-haiku-4-5" env = flyte.TaskEnvironment( name="financial-research", secrets=[ flyte.Secret(key="youdotcom-api-key", as_env_var="YDC_API_KEY"), flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], image=flyte.Image.from_uv_script(__file__, name="financial-research", pre=True), resources=flyte.Resources(cpu="1", memory="1Gi"), cache="auto", ) # {{/docs-fragment env}} # {{docs-fragment data_types}} @dataclass class Source: title: str url: str domain: str = "" snippet: str = "" published: str = "" favicon: str = "" section: str = "research" # "research", "news", or "web" def _domain(url: str) -> str: from urllib.parse import urlparse try: return urlparse(url).netloc.replace("www.", "") except Exception: return "" def _favicon_for(url: str) -> str: return f"https://ydc-index.io/favicon?domain={_domain(url)}&size=128" @dataclass class Briefing: company: str thesis: str recent_developments: list[str] = field(default_factory=list) risks: list[str] = field(default_factory=list) watch_items: list[str] = field(default_factory=list) sources: list[Source] = field(default_factory=list) @dataclass class ResearchReport: briefings: list[Briefing] = field(default_factory=list) # {{/docs-fragment data_types}} # {{docs-fragment you_apis}} YOU_RESEARCH_URL = "https://api.you.com/v1/research" YOU_SEARCH_URL = "https://ydc-index.io/v1/search" async def _you_request(method: str, url: str, timeout: float, **kwargs) -> dict: """HTTP wrapper with exponential backoff + jitter on 429 rate limits. Fanned-out tasks run in separate pods, so we retry on the client side to smooth out bursts against the You.com API rate limit. """ import asyncio import random import httpx # YDC_API_KEY is canonical; YOU_API_KEY accepted as a backwards-compatible fallback. headers = {"X-API-Key": os.environ.get("YDC_API_KEY") or os.environ["YOU_API_KEY"]} if method == "POST": headers["Content-Type"] = "application/json" async with httpx.AsyncClient(timeout=timeout) as client: for attempt in range(7): resp = await client.request(method, url, headers=headers, **kwargs) if resp.status_code == 429 and attempt < 6: wait = float(resp.headers.get("retry-after") or 0) or min(2**attempt, 30) await asyncio.sleep(wait + random.uniform(0, 2)) continue resp.raise_for_status() return resp.json() resp.raise_for_status() return resp.json() @flyte.trace async def you_research(question: str, research_effort: str, freshness: str) -> dict: """Grounded, citation-backed research answer.""" body = { "input": question, "research_effort": research_effort, "source_control": {"freshness": freshness}, } return await _you_request("POST", YOU_RESEARCH_URL, 300.0, json=body) @flyte.trace async def you_news( query: str, count: int = 10, freshness: str = "week", boost_domains: str = "", ) -> list[dict]: """Fresh news headlines for a company. ``boost_domains`` (comma-separated) lifts authoritative financial outlets in ranking without restricting results to only those domains, so company press releases and niche coverage still surface when relevant. """ params: dict = {"query": query, "count": count, "freshness": freshness} if boost_domains: params["boost_domains"] = boost_domains data = await _you_request("GET", YOU_SEARCH_URL, 60.0, params=params) results = data.get("results", {}) out: list[dict] = [] for section in ("news", "web"): for item in results.get(section, []) or []: snippets = item.get("snippets") or [] url = item.get("url", "") out.append( { "title": item.get("title", ""), "url": url, "domain": _domain(url), "snippet": snippets[0] if snippets else item.get("description", ""), "published": item.get("page_age", "") or "", "favicon": item.get("favicon_url") or _favicon_for(url), "section": section, } ) return out # {{/docs-fragment you_apis}} # {{docs-fragment llm}} @flyte.trace async def synthesize_briefing(company: str, focus: str, research: str, news: str) -> dict: """Use Claude to synthesize a structured equity briefing.""" from litellm import acompletion system = ( "You are an equity research analyst. Using ONLY the grounded research " "and news provided, write a concise briefing. Respond ONLY with JSON: " '{"thesis": str, "recent_developments": [str], "risks": [str], ' '"watch_items": [str]}. Keep each list to 3-5 short, specific bullets.' ) user = ( f"Company: {company}\nFocus: {focus}\n\n" f"Grounded research:\n{research}\n\nRecent news:\n{news}" ) resp = await acompletion( model=MODEL, messages=[ {"role": "system", "content": system}, {"role": "user", "content": user}, ], temperature=0.0, max_tokens=1536, ) parsed = _parse_json(resp.choices[0].message.content) return parsed if isinstance(parsed, dict) else {} def _parse_json(text: str) -> dict | list: text = text.strip() if text.startswith("CODE2", 2)[1] if text.lstrip().startswith("json"): text = text.lstrip()[4:] start = min((i for i in (text.find("{"), text.find("[")) if i != -1), default=0) end = max(text.rfind("}"), text.rfind("]")) + 1 return json.loads(text[start:end]) # {{/docs-fragment llm}} # {{docs-fragment research_company}} # Tier-1 financial outlets that consistently break earnings, M&A, and # analyst-moving news. boost_domains lifts these in ranking without excluding # other sources, so company press releases and trade-press coverage still # surface when relevant. FINANCE_BOOST_DOMAINS = "reuters.com,bloomberg.com,wsj.com,marketwatch.com,cnbc.com,ft.com" @env.task(retries=3) async def research_company( company: str, focus: str, research_effort: str, freshness: str, ) -> Briefing: """Research one company and synthesize a cited briefing.""" question = ( f"Provide a grounded analysis of {company} with respect to: {focus}. " f"Cover recent financial performance, strategic moves, competitive " f"positioning, and risks." ) research_result, news = await asyncio.gather( you_research(question, research_effort, freshness), you_news( f"{company} earnings news", freshness=freshness, boost_domains=FINANCE_BOOST_DOMAINS, ), ) output = research_result.get("output", {}) research_text = output.get("content", "") if not isinstance(research_text, str): research_text = json.dumps(research_text) sources: list[Source] = [] for s in output.get("sources", []) or []: url = str(s.get("url", "")) sources.append( Source( title=str(s.get("title", "") or url), url=url, domain=_domain(url), snippet=str((s.get("snippets") or [""])[0]), favicon=_favicon_for(url), section="research", ) ) for n in news: sources.append( Source( title=str(n.get("title", "")), url=str(n.get("url", "")), domain=str(n.get("domain", "")), snippet=str(n.get("snippet", "")), published=str(n.get("published", "")), favicon=str(n.get("favicon", "")), section=str(n.get("section", "web")), ) ) news_text = "\n".join( f"- {n['title']} ({n['published']}) {n['domain']}: {n['snippet'][:120]}" for n in news ) parsed = await synthesize_briefing(company, focus, research_text, news_text) def _list(key: str) -> list[str]: return [str(x) for x in (parsed.get(key) or [])] return Briefing( company=company, thesis=str(parsed.get("thesis", "")), recent_developments=_list("recent_developments"), risks=_list("risks"), watch_items=_list("watch_items"), sources=sources, ) # {{/docs-fragment research_company}} # {{docs-fragment report}} REPORT_CSS = """ """ def _cite(s: Source) -> str: """Render a rich You.com citation (Research or Search source).""" if not s.url: return "" tag_cls = s.section if s.section in ("research", "news") else "web" meta_bits = [] if s.published: meta_bits.append(s.published[:10]) if s.title: meta_bits.append(s.title) meta = " · ".join(meta_bits) snip = f"
“{s.snippet}”
" if s.snippet else "" return ( f"
" f"
" f"{s.domain or 'source'}" f"{s.section}" f"
{meta}
{snip}
" ) def _render_report(report: ResearchReport) -> str: def _ul(items: list[str]) -> str: if not items: return "

None reported.

" return "
    " + "".join(f"
  • {x}
  • " for x in items) + "
" cards = [] for b in report.briefings: src = "".join(_cite(s) for s in b.sources[:10]) cards.append( f"

{b.company}

" f"
{b.thesis or 'No thesis generated.'}
" f"
" f"

Recent developments

{_ul(b.recent_developments)}
" f"

Risks

{_ul(b.risks)}
" f"

Watch items

{_ul(b.watch_items)}
" f"
" + (f"

You.com sources ({len(b.sources)})

{src}
" if src else "") + "
" ) total_sources = sum(len(b.sources) for b in report.briefings) return f""" {REPORT_CSS}

Financial Research Briefings

Grounded, citation-backed equity briefings โ€” each company backed by You.com Research synthesis plus fresh Search news.

{len(report.briefings)} companies {total_sources} You.com sources cited
{''.join(cards) or "

No briefings generated.

"}

Research answers from the You.com Research API (grounded synthesis with inline citations) plus fresh headlines from the You.com Search API (web + auto-classified news with timestamps and snippets).

""" # {{/docs-fragment report}} # {{docs-fragment driver}} @env.task(report=True) async def financial_research( companies: list[str] = [ "NVIDIA", "Advanced Micro Devices", "Microsoft", "Alphabet", "Amazon", "Meta Platforms", "Broadcom", "Taiwan Semiconductor Manufacturing", ], focus: str = "Q4 earnings preview and competitive positioning", research_effort: str = "standard", freshness: str = "month", ) -> ResearchReport: """Fan out across companies and aggregate cited equity briefings.""" with flyte.group("research-companies"): briefings = await asyncio.gather( *[ research_company(c, focus, research_effort, freshness) for c in companies ] ) report = ResearchReport(briefings=list(briefings)) await flyte.report.replace.aio(_render_report(report), do_flush=True) await flyte.report.flush.aio() return report # {{/docs-fragment driver}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(financial_research) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/financial_research_agent/main.py* ## You.com Research and Search APIs The agent uses both You.com APIs in parallel for each company: - **Research API** (`https://api.you.com/v1/research`): grounded, citation-backed analysis with configurable `research_effort` (`lite`, `standard`, `deep`, `exhaustive`). See the [Research API reference](https://you.com/docs/api-reference/research/v1-research). - **Search API** (`https://ydc-index.io/v1/search`): fresh news headlines with `freshness` filtering. See the [Search API reference](https://you.com/docs/api-reference/search/v1-search). ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.4.0", # "httpx>=0.27.0", # "litellm>=1.72.0", # ] # main = "financial_research" # params = "" # /// """Financial research & earnings-cycle agent. For each company, runs grounded, source-cited research via the You.com Research API plus a fresh-news layer via the Search API, then uses Claude to synthesize an analyst-ready equity briefing that preserves citations. Flyte caching cuts duplicate spend when runs converge. """ # {{docs-fragment env}} import asyncio import json import os from dataclasses import dataclass, field import flyte MODEL = "anthropic/claude-haiku-4-5" env = flyte.TaskEnvironment( name="financial-research", secrets=[ flyte.Secret(key="youdotcom-api-key", as_env_var="YDC_API_KEY"), flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], image=flyte.Image.from_uv_script(__file__, name="financial-research", pre=True), resources=flyte.Resources(cpu="1", memory="1Gi"), cache="auto", ) # {{/docs-fragment env}} # {{docs-fragment data_types}} @dataclass class Source: title: str url: str domain: str = "" snippet: str = "" published: str = "" favicon: str = "" section: str = "research" # "research", "news", or "web" def _domain(url: str) -> str: from urllib.parse import urlparse try: return urlparse(url).netloc.replace("www.", "") except Exception: return "" def _favicon_for(url: str) -> str: return f"https://ydc-index.io/favicon?domain={_domain(url)}&size=128" @dataclass class Briefing: company: str thesis: str recent_developments: list[str] = field(default_factory=list) risks: list[str] = field(default_factory=list) watch_items: list[str] = field(default_factory=list) sources: list[Source] = field(default_factory=list) @dataclass class ResearchReport: briefings: list[Briefing] = field(default_factory=list) # {{/docs-fragment data_types}} # {{docs-fragment you_apis}} YOU_RESEARCH_URL = "https://api.you.com/v1/research" YOU_SEARCH_URL = "https://ydc-index.io/v1/search" async def _you_request(method: str, url: str, timeout: float, **kwargs) -> dict: """HTTP wrapper with exponential backoff + jitter on 429 rate limits. Fanned-out tasks run in separate pods, so we retry on the client side to smooth out bursts against the You.com API rate limit. """ import asyncio import random import httpx # YDC_API_KEY is canonical; YOU_API_KEY accepted as a backwards-compatible fallback. headers = {"X-API-Key": os.environ.get("YDC_API_KEY") or os.environ["YOU_API_KEY"]} if method == "POST": headers["Content-Type"] = "application/json" async with httpx.AsyncClient(timeout=timeout) as client: for attempt in range(7): resp = await client.request(method, url, headers=headers, **kwargs) if resp.status_code == 429 and attempt < 6: wait = float(resp.headers.get("retry-after") or 0) or min(2**attempt, 30) await asyncio.sleep(wait + random.uniform(0, 2)) continue resp.raise_for_status() return resp.json() resp.raise_for_status() return resp.json() @flyte.trace async def you_research(question: str, research_effort: str, freshness: str) -> dict: """Grounded, citation-backed research answer.""" body = { "input": question, "research_effort": research_effort, "source_control": {"freshness": freshness}, } return await _you_request("POST", YOU_RESEARCH_URL, 300.0, json=body) @flyte.trace async def you_news( query: str, count: int = 10, freshness: str = "week", boost_domains: str = "", ) -> list[dict]: """Fresh news headlines for a company. ``boost_domains`` (comma-separated) lifts authoritative financial outlets in ranking without restricting results to only those domains, so company press releases and niche coverage still surface when relevant. """ params: dict = {"query": query, "count": count, "freshness": freshness} if boost_domains: params["boost_domains"] = boost_domains data = await _you_request("GET", YOU_SEARCH_URL, 60.0, params=params) results = data.get("results", {}) out: list[dict] = [] for section in ("news", "web"): for item in results.get(section, []) or []: snippets = item.get("snippets") or [] url = item.get("url", "") out.append( { "title": item.get("title", ""), "url": url, "domain": _domain(url), "snippet": snippets[0] if snippets else item.get("description", ""), "published": item.get("page_age", "") or "", "favicon": item.get("favicon_url") or _favicon_for(url), "section": section, } ) return out # {{/docs-fragment you_apis}} # {{docs-fragment llm}} @flyte.trace async def synthesize_briefing(company: str, focus: str, research: str, news: str) -> dict: """Use Claude to synthesize a structured equity briefing.""" from litellm import acompletion system = ( "You are an equity research analyst. Using ONLY the grounded research " "and news provided, write a concise briefing. Respond ONLY with JSON: " '{"thesis": str, "recent_developments": [str], "risks": [str], ' '"watch_items": [str]}. Keep each list to 3-5 short, specific bullets.' ) user = ( f"Company: {company}\nFocus: {focus}\n\n" f"Grounded research:\n{research}\n\nRecent news:\n{news}" ) resp = await acompletion( model=MODEL, messages=[ {"role": "system", "content": system}, {"role": "user", "content": user}, ], temperature=0.0, max_tokens=1536, ) parsed = _parse_json(resp.choices[0].message.content) return parsed if isinstance(parsed, dict) else {} def _parse_json(text: str) -> dict | list: text = text.strip() if text.startswith("CODE3", 2)[1] if text.lstrip().startswith("json"): text = text.lstrip()[4:] start = min((i for i in (text.find("{"), text.find("[")) if i != -1), default=0) end = max(text.rfind("}"), text.rfind("]")) + 1 return json.loads(text[start:end]) # {{/docs-fragment llm}} # {{docs-fragment research_company}} # Tier-1 financial outlets that consistently break earnings, M&A, and # analyst-moving news. boost_domains lifts these in ranking without excluding # other sources, so company press releases and trade-press coverage still # surface when relevant. FINANCE_BOOST_DOMAINS = "reuters.com,bloomberg.com,wsj.com,marketwatch.com,cnbc.com,ft.com" @env.task(retries=3) async def research_company( company: str, focus: str, research_effort: str, freshness: str, ) -> Briefing: """Research one company and synthesize a cited briefing.""" question = ( f"Provide a grounded analysis of {company} with respect to: {focus}. " f"Cover recent financial performance, strategic moves, competitive " f"positioning, and risks." ) research_result, news = await asyncio.gather( you_research(question, research_effort, freshness), you_news( f"{company} earnings news", freshness=freshness, boost_domains=FINANCE_BOOST_DOMAINS, ), ) output = research_result.get("output", {}) research_text = output.get("content", "") if not isinstance(research_text, str): research_text = json.dumps(research_text) sources: list[Source] = [] for s in output.get("sources", []) or []: url = str(s.get("url", "")) sources.append( Source( title=str(s.get("title", "") or url), url=url, domain=_domain(url), snippet=str((s.get("snippets") or [""])[0]), favicon=_favicon_for(url), section="research", ) ) for n in news: sources.append( Source( title=str(n.get("title", "")), url=str(n.get("url", "")), domain=str(n.get("domain", "")), snippet=str(n.get("snippet", "")), published=str(n.get("published", "")), favicon=str(n.get("favicon", "")), section=str(n.get("section", "web")), ) ) news_text = "\n".join( f"- {n['title']} ({n['published']}) {n['domain']}: {n['snippet'][:120]}" for n in news ) parsed = await synthesize_briefing(company, focus, research_text, news_text) def _list(key: str) -> list[str]: return [str(x) for x in (parsed.get(key) or [])] return Briefing( company=company, thesis=str(parsed.get("thesis", "")), recent_developments=_list("recent_developments"), risks=_list("risks"), watch_items=_list("watch_items"), sources=sources, ) # {{/docs-fragment research_company}} # {{docs-fragment report}} REPORT_CSS = """ """ def _cite(s: Source) -> str: """Render a rich You.com citation (Research or Search source).""" if not s.url: return "" tag_cls = s.section if s.section in ("research", "news") else "web" meta_bits = [] if s.published: meta_bits.append(s.published[:10]) if s.title: meta_bits.append(s.title) meta = " · ".join(meta_bits) snip = f"
“{s.snippet}”
" if s.snippet else "" return ( f"
" f"
" f"{s.domain or 'source'}" f"{s.section}" f"
{meta}
{snip}
" ) def _render_report(report: ResearchReport) -> str: def _ul(items: list[str]) -> str: if not items: return "

None reported.

" return "
    " + "".join(f"
  • {x}
  • " for x in items) + "
" cards = [] for b in report.briefings: src = "".join(_cite(s) for s in b.sources[:10]) cards.append( f"

{b.company}

" f"
{b.thesis or 'No thesis generated.'}
" f"
" f"

Recent developments

{_ul(b.recent_developments)}
" f"

Risks

{_ul(b.risks)}
" f"

Watch items

{_ul(b.watch_items)}
" f"
" + (f"

You.com sources ({len(b.sources)})

{src}
" if src else "") + "
" ) total_sources = sum(len(b.sources) for b in report.briefings) return f""" {REPORT_CSS}

Financial Research Briefings

Grounded, citation-backed equity briefings โ€” each company backed by You.com Research synthesis plus fresh Search news.

{len(report.briefings)} companies {total_sources} You.com sources cited
{''.join(cards) or "

No briefings generated.

"}

Research answers from the You.com Research API (grounded synthesis with inline citations) plus fresh headlines from the You.com Search API (web + auto-classified news with timestamps and snippets).

""" # {{/docs-fragment report}} # {{docs-fragment driver}} @env.task(report=True) async def financial_research( companies: list[str] = [ "NVIDIA", "Advanced Micro Devices", "Microsoft", "Alphabet", "Amazon", "Meta Platforms", "Broadcom", "Taiwan Semiconductor Manufacturing", ], focus: str = "Q4 earnings preview and competitive positioning", research_effort: str = "standard", freshness: str = "month", ) -> ResearchReport: """Fan out across companies and aggregate cited equity briefings.""" with flyte.group("research-companies"): briefings = await asyncio.gather( *[ research_company(c, focus, research_effort, freshness) for c in companies ] ) report = ResearchReport(briefings=list(briefings)) await flyte.report.replace.aio(_render_report(report), do_flush=True) await flyte.report.flush.aio() return report # {{/docs-fragment driver}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(financial_research) print(run.url) run.wait() # {{/docs-fragment main}} CODE4 # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.4.0", # "httpx>=0.27.0", # "litellm>=1.72.0", # ] # main = "financial_research" # params = "" # /// """Financial research & earnings-cycle agent. For each company, runs grounded, source-cited research via the You.com Research API plus a fresh-news layer via the Search API, then uses Claude to synthesize an analyst-ready equity briefing that preserves citations. Flyte caching cuts duplicate spend when runs converge. """ # {{docs-fragment env}} import asyncio import json import os from dataclasses import dataclass, field import flyte MODEL = "anthropic/claude-haiku-4-5" env = flyte.TaskEnvironment( name="financial-research", secrets=[ flyte.Secret(key="youdotcom-api-key", as_env_var="YDC_API_KEY"), flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], image=flyte.Image.from_uv_script(__file__, name="financial-research", pre=True), resources=flyte.Resources(cpu="1", memory="1Gi"), cache="auto", ) # {{/docs-fragment env}} # {{docs-fragment data_types}} @dataclass class Source: title: str url: str domain: str = "" snippet: str = "" published: str = "" favicon: str = "" section: str = "research" # "research", "news", or "web" def _domain(url: str) -> str: from urllib.parse import urlparse try: return urlparse(url).netloc.replace("www.", "") except Exception: return "" def _favicon_for(url: str) -> str: return f"https://ydc-index.io/favicon?domain={_domain(url)}&size=128" @dataclass class Briefing: company: str thesis: str recent_developments: list[str] = field(default_factory=list) risks: list[str] = field(default_factory=list) watch_items: list[str] = field(default_factory=list) sources: list[Source] = field(default_factory=list) @dataclass class ResearchReport: briefings: list[Briefing] = field(default_factory=list) # {{/docs-fragment data_types}} # {{docs-fragment you_apis}} YOU_RESEARCH_URL = "https://api.you.com/v1/research" YOU_SEARCH_URL = "https://ydc-index.io/v1/search" async def _you_request(method: str, url: str, timeout: float, **kwargs) -> dict: """HTTP wrapper with exponential backoff + jitter on 429 rate limits. Fanned-out tasks run in separate pods, so we retry on the client side to smooth out bursts against the You.com API rate limit. """ import asyncio import random import httpx # YDC_API_KEY is canonical; YOU_API_KEY accepted as a backwards-compatible fallback. headers = {"X-API-Key": os.environ.get("YDC_API_KEY") or os.environ["YOU_API_KEY"]} if method == "POST": headers["Content-Type"] = "application/json" async with httpx.AsyncClient(timeout=timeout) as client: for attempt in range(7): resp = await client.request(method, url, headers=headers, **kwargs) if resp.status_code == 429 and attempt < 6: wait = float(resp.headers.get("retry-after") or 0) or min(2**attempt, 30) await asyncio.sleep(wait + random.uniform(0, 2)) continue resp.raise_for_status() return resp.json() resp.raise_for_status() return resp.json() @flyte.trace async def you_research(question: str, research_effort: str, freshness: str) -> dict: """Grounded, citation-backed research answer.""" body = { "input": question, "research_effort": research_effort, "source_control": {"freshness": freshness}, } return await _you_request("POST", YOU_RESEARCH_URL, 300.0, json=body) @flyte.trace async def you_news( query: str, count: int = 10, freshness: str = "week", boost_domains: str = "", ) -> list[dict]: """Fresh news headlines for a company. ``boost_domains`` (comma-separated) lifts authoritative financial outlets in ranking without restricting results to only those domains, so company press releases and niche coverage still surface when relevant. """ params: dict = {"query": query, "count": count, "freshness": freshness} if boost_domains: params["boost_domains"] = boost_domains data = await _you_request("GET", YOU_SEARCH_URL, 60.0, params=params) results = data.get("results", {}) out: list[dict] = [] for section in ("news", "web"): for item in results.get(section, []) or []: snippets = item.get("snippets") or [] url = item.get("url", "") out.append( { "title": item.get("title", ""), "url": url, "domain": _domain(url), "snippet": snippets[0] if snippets else item.get("description", ""), "published": item.get("page_age", "") or "", "favicon": item.get("favicon_url") or _favicon_for(url), "section": section, } ) return out # {{/docs-fragment you_apis}} # {{docs-fragment llm}} @flyte.trace async def synthesize_briefing(company: str, focus: str, research: str, news: str) -> dict: """Use Claude to synthesize a structured equity briefing.""" from litellm import acompletion system = ( "You are an equity research analyst. Using ONLY the grounded research " "and news provided, write a concise briefing. Respond ONLY with JSON: " '{"thesis": str, "recent_developments": [str], "risks": [str], ' '"watch_items": [str]}. Keep each list to 3-5 short, specific bullets.' ) user = ( f"Company: {company}\nFocus: {focus}\n\n" f"Grounded research:\n{research}\n\nRecent news:\n{news}" ) resp = await acompletion( model=MODEL, messages=[ {"role": "system", "content": system}, {"role": "user", "content": user}, ], temperature=0.0, max_tokens=1536, ) parsed = _parse_json(resp.choices[0].message.content) return parsed if isinstance(parsed, dict) else {} def _parse_json(text: str) -> dict | list: text = text.strip() if text.startswith("CODE5", 2)[1] if text.lstrip().startswith("json"): text = text.lstrip()[4:] start = min((i for i in (text.find("{"), text.find("[")) if i != -1), default=0) end = max(text.rfind("}"), text.rfind("]")) + 1 return json.loads(text[start:end]) # {{/docs-fragment llm}} # {{docs-fragment research_company}} # Tier-1 financial outlets that consistently break earnings, M&A, and # analyst-moving news. boost_domains lifts these in ranking without excluding # other sources, so company press releases and trade-press coverage still # surface when relevant. FINANCE_BOOST_DOMAINS = "reuters.com,bloomberg.com,wsj.com,marketwatch.com,cnbc.com,ft.com" @env.task(retries=3) async def research_company( company: str, focus: str, research_effort: str, freshness: str, ) -> Briefing: """Research one company and synthesize a cited briefing.""" question = ( f"Provide a grounded analysis of {company} with respect to: {focus}. " f"Cover recent financial performance, strategic moves, competitive " f"positioning, and risks." ) research_result, news = await asyncio.gather( you_research(question, research_effort, freshness), you_news( f"{company} earnings news", freshness=freshness, boost_domains=FINANCE_BOOST_DOMAINS, ), ) output = research_result.get("output", {}) research_text = output.get("content", "") if not isinstance(research_text, str): research_text = json.dumps(research_text) sources: list[Source] = [] for s in output.get("sources", []) or []: url = str(s.get("url", "")) sources.append( Source( title=str(s.get("title", "") or url), url=url, domain=_domain(url), snippet=str((s.get("snippets") or [""])[0]), favicon=_favicon_for(url), section="research", ) ) for n in news: sources.append( Source( title=str(n.get("title", "")), url=str(n.get("url", "")), domain=str(n.get("domain", "")), snippet=str(n.get("snippet", "")), published=str(n.get("published", "")), favicon=str(n.get("favicon", "")), section=str(n.get("section", "web")), ) ) news_text = "\n".join( f"- {n['title']} ({n['published']}) {n['domain']}: {n['snippet'][:120]}" for n in news ) parsed = await synthesize_briefing(company, focus, research_text, news_text) def _list(key: str) -> list[str]: return [str(x) for x in (parsed.get(key) or [])] return Briefing( company=company, thesis=str(parsed.get("thesis", "")), recent_developments=_list("recent_developments"), risks=_list("risks"), watch_items=_list("watch_items"), sources=sources, ) # {{/docs-fragment research_company}} # {{docs-fragment report}} REPORT_CSS = """ """ def _cite(s: Source) -> str: """Render a rich You.com citation (Research or Search source).""" if not s.url: return "" tag_cls = s.section if s.section in ("research", "news") else "web" meta_bits = [] if s.published: meta_bits.append(s.published[:10]) if s.title: meta_bits.append(s.title) meta = " · ".join(meta_bits) snip = f"
“{s.snippet}”
" if s.snippet else "" return ( f"
" f"
" f"{s.domain or 'source'}" f"{s.section}" f"
{meta}
{snip}
" ) def _render_report(report: ResearchReport) -> str: def _ul(items: list[str]) -> str: if not items: return "

None reported.

" return "
    " + "".join(f"
  • {x}
  • " for x in items) + "
" cards = [] for b in report.briefings: src = "".join(_cite(s) for s in b.sources[:10]) cards.append( f"

{b.company}

" f"
{b.thesis or 'No thesis generated.'}
" f"
" f"

Recent developments

{_ul(b.recent_developments)}
" f"

Risks

{_ul(b.risks)}
" f"

Watch items

{_ul(b.watch_items)}
" f"
" + (f"

You.com sources ({len(b.sources)})

{src}
" if src else "") + "
" ) total_sources = sum(len(b.sources) for b in report.briefings) return f""" {REPORT_CSS}

Financial Research Briefings

Grounded, citation-backed equity briefings โ€” each company backed by You.com Research synthesis plus fresh Search news.

{len(report.briefings)} companies {total_sources} You.com sources cited
{''.join(cards) or "

No briefings generated.

"}

Research answers from the You.com Research API (grounded synthesis with inline citations) plus fresh headlines from the You.com Search API (web + auto-classified news with timestamps and snippets).

""" # {{/docs-fragment report}} # {{docs-fragment driver}} @env.task(report=True) async def financial_research( companies: list[str] = [ "NVIDIA", "Advanced Micro Devices", "Microsoft", "Alphabet", "Amazon", "Meta Platforms", "Broadcom", "Taiwan Semiconductor Manufacturing", ], focus: str = "Q4 earnings preview and competitive positioning", research_effort: str = "standard", freshness: str = "month", ) -> ResearchReport: """Fan out across companies and aggregate cited equity briefings.""" with flyte.group("research-companies"): briefings = await asyncio.gather( *[ research_company(c, focus, research_effort, freshness) for c in companies ] ) report = ResearchReport(briefings=list(briefings)) await flyte.report.replace.aio(_render_report(report), do_flush=True) await flyte.report.flush.aio() return report # {{/docs-fragment driver}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(financial_research) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/financial_research_agent/main.py* ## Research one company The `research_company` task calls both You.com APIs in parallel, collects sources, and synthesizes a structured briefing. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.4.0", # "httpx>=0.27.0", # "litellm>=1.72.0", # ] # main = "financial_research" # params = "" # /// """Financial research & earnings-cycle agent. For each company, runs grounded, source-cited research via the You.com Research API plus a fresh-news layer via the Search API, then uses Claude to synthesize an analyst-ready equity briefing that preserves citations. Flyte caching cuts duplicate spend when runs converge. """ # {{docs-fragment env}} import asyncio import json import os from dataclasses import dataclass, field import flyte MODEL = "anthropic/claude-haiku-4-5" env = flyte.TaskEnvironment( name="financial-research", secrets=[ flyte.Secret(key="youdotcom-api-key", as_env_var="YDC_API_KEY"), flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], image=flyte.Image.from_uv_script(__file__, name="financial-research", pre=True), resources=flyte.Resources(cpu="1", memory="1Gi"), cache="auto", ) # {{/docs-fragment env}} # {{docs-fragment data_types}} @dataclass class Source: title: str url: str domain: str = "" snippet: str = "" published: str = "" favicon: str = "" section: str = "research" # "research", "news", or "web" def _domain(url: str) -> str: from urllib.parse import urlparse try: return urlparse(url).netloc.replace("www.", "") except Exception: return "" def _favicon_for(url: str) -> str: return f"https://ydc-index.io/favicon?domain={_domain(url)}&size=128" @dataclass class Briefing: company: str thesis: str recent_developments: list[str] = field(default_factory=list) risks: list[str] = field(default_factory=list) watch_items: list[str] = field(default_factory=list) sources: list[Source] = field(default_factory=list) @dataclass class ResearchReport: briefings: list[Briefing] = field(default_factory=list) # {{/docs-fragment data_types}} # {{docs-fragment you_apis}} YOU_RESEARCH_URL = "https://api.you.com/v1/research" YOU_SEARCH_URL = "https://ydc-index.io/v1/search" async def _you_request(method: str, url: str, timeout: float, **kwargs) -> dict: """HTTP wrapper with exponential backoff + jitter on 429 rate limits. Fanned-out tasks run in separate pods, so we retry on the client side to smooth out bursts against the You.com API rate limit. """ import asyncio import random import httpx # YDC_API_KEY is canonical; YOU_API_KEY accepted as a backwards-compatible fallback. headers = {"X-API-Key": os.environ.get("YDC_API_KEY") or os.environ["YOU_API_KEY"]} if method == "POST": headers["Content-Type"] = "application/json" async with httpx.AsyncClient(timeout=timeout) as client: for attempt in range(7): resp = await client.request(method, url, headers=headers, **kwargs) if resp.status_code == 429 and attempt < 6: wait = float(resp.headers.get("retry-after") or 0) or min(2**attempt, 30) await asyncio.sleep(wait + random.uniform(0, 2)) continue resp.raise_for_status() return resp.json() resp.raise_for_status() return resp.json() @flyte.trace async def you_research(question: str, research_effort: str, freshness: str) -> dict: """Grounded, citation-backed research answer.""" body = { "input": question, "research_effort": research_effort, "source_control": {"freshness": freshness}, } return await _you_request("POST", YOU_RESEARCH_URL, 300.0, json=body) @flyte.trace async def you_news( query: str, count: int = 10, freshness: str = "week", boost_domains: str = "", ) -> list[dict]: """Fresh news headlines for a company. ``boost_domains`` (comma-separated) lifts authoritative financial outlets in ranking without restricting results to only those domains, so company press releases and niche coverage still surface when relevant. """ params: dict = {"query": query, "count": count, "freshness": freshness} if boost_domains: params["boost_domains"] = boost_domains data = await _you_request("GET", YOU_SEARCH_URL, 60.0, params=params) results = data.get("results", {}) out: list[dict] = [] for section in ("news", "web"): for item in results.get(section, []) or []: snippets = item.get("snippets") or [] url = item.get("url", "") out.append( { "title": item.get("title", ""), "url": url, "domain": _domain(url), "snippet": snippets[0] if snippets else item.get("description", ""), "published": item.get("page_age", "") or "", "favicon": item.get("favicon_url") or _favicon_for(url), "section": section, } ) return out # {{/docs-fragment you_apis}} # {{docs-fragment llm}} @flyte.trace async def synthesize_briefing(company: str, focus: str, research: str, news: str) -> dict: """Use Claude to synthesize a structured equity briefing.""" from litellm import acompletion system = ( "You are an equity research analyst. Using ONLY the grounded research " "and news provided, write a concise briefing. Respond ONLY with JSON: " '{"thesis": str, "recent_developments": [str], "risks": [str], ' '"watch_items": [str]}. Keep each list to 3-5 short, specific bullets.' ) user = ( f"Company: {company}\nFocus: {focus}\n\n" f"Grounded research:\n{research}\n\nRecent news:\n{news}" ) resp = await acompletion( model=MODEL, messages=[ {"role": "system", "content": system}, {"role": "user", "content": user}, ], temperature=0.0, max_tokens=1536, ) parsed = _parse_json(resp.choices[0].message.content) return parsed if isinstance(parsed, dict) else {} def _parse_json(text: str) -> dict | list: text = text.strip() if text.startswith("CODE6", 2)[1] if text.lstrip().startswith("json"): text = text.lstrip()[4:] start = min((i for i in (text.find("{"), text.find("[")) if i != -1), default=0) end = max(text.rfind("}"), text.rfind("]")) + 1 return json.loads(text[start:end]) # {{/docs-fragment llm}} # {{docs-fragment research_company}} # Tier-1 financial outlets that consistently break earnings, M&A, and # analyst-moving news. boost_domains lifts these in ranking without excluding # other sources, so company press releases and trade-press coverage still # surface when relevant. FINANCE_BOOST_DOMAINS = "reuters.com,bloomberg.com,wsj.com,marketwatch.com,cnbc.com,ft.com" @env.task(retries=3) async def research_company( company: str, focus: str, research_effort: str, freshness: str, ) -> Briefing: """Research one company and synthesize a cited briefing.""" question = ( f"Provide a grounded analysis of {company} with respect to: {focus}. " f"Cover recent financial performance, strategic moves, competitive " f"positioning, and risks." ) research_result, news = await asyncio.gather( you_research(question, research_effort, freshness), you_news( f"{company} earnings news", freshness=freshness, boost_domains=FINANCE_BOOST_DOMAINS, ), ) output = research_result.get("output", {}) research_text = output.get("content", "") if not isinstance(research_text, str): research_text = json.dumps(research_text) sources: list[Source] = [] for s in output.get("sources", []) or []: url = str(s.get("url", "")) sources.append( Source( title=str(s.get("title", "") or url), url=url, domain=_domain(url), snippet=str((s.get("snippets") or [""])[0]), favicon=_favicon_for(url), section="research", ) ) for n in news: sources.append( Source( title=str(n.get("title", "")), url=str(n.get("url", "")), domain=str(n.get("domain", "")), snippet=str(n.get("snippet", "")), published=str(n.get("published", "")), favicon=str(n.get("favicon", "")), section=str(n.get("section", "web")), ) ) news_text = "\n".join( f"- {n['title']} ({n['published']}) {n['domain']}: {n['snippet'][:120]}" for n in news ) parsed = await synthesize_briefing(company, focus, research_text, news_text) def _list(key: str) -> list[str]: return [str(x) for x in (parsed.get(key) or [])] return Briefing( company=company, thesis=str(parsed.get("thesis", "")), recent_developments=_list("recent_developments"), risks=_list("risks"), watch_items=_list("watch_items"), sources=sources, ) # {{/docs-fragment research_company}} # {{docs-fragment report}} REPORT_CSS = """ """ def _cite(s: Source) -> str: """Render a rich You.com citation (Research or Search source).""" if not s.url: return "" tag_cls = s.section if s.section in ("research", "news") else "web" meta_bits = [] if s.published: meta_bits.append(s.published[:10]) if s.title: meta_bits.append(s.title) meta = " · ".join(meta_bits) snip = f"
“{s.snippet}”
" if s.snippet else "" return ( f"
" f"
" f"{s.domain or 'source'}" f"{s.section}" f"
{meta}
{snip}
" ) def _render_report(report: ResearchReport) -> str: def _ul(items: list[str]) -> str: if not items: return "

None reported.

" return "
    " + "".join(f"
  • {x}
  • " for x in items) + "
" cards = [] for b in report.briefings: src = "".join(_cite(s) for s in b.sources[:10]) cards.append( f"

{b.company}

" f"
{b.thesis or 'No thesis generated.'}
" f"
" f"

Recent developments

{_ul(b.recent_developments)}
" f"

Risks

{_ul(b.risks)}
" f"

Watch items

{_ul(b.watch_items)}
" f"
" + (f"

You.com sources ({len(b.sources)})

{src}
" if src else "") + "
" ) total_sources = sum(len(b.sources) for b in report.briefings) return f""" {REPORT_CSS}

Financial Research Briefings

Grounded, citation-backed equity briefings โ€” each company backed by You.com Research synthesis plus fresh Search news.

{len(report.briefings)} companies {total_sources} You.com sources cited
{''.join(cards) or "

No briefings generated.

"}

Research answers from the You.com Research API (grounded synthesis with inline citations) plus fresh headlines from the You.com Search API (web + auto-classified news with timestamps and snippets).

""" # {{/docs-fragment report}} # {{docs-fragment driver}} @env.task(report=True) async def financial_research( companies: list[str] = [ "NVIDIA", "Advanced Micro Devices", "Microsoft", "Alphabet", "Amazon", "Meta Platforms", "Broadcom", "Taiwan Semiconductor Manufacturing", ], focus: str = "Q4 earnings preview and competitive positioning", research_effort: str = "standard", freshness: str = "month", ) -> ResearchReport: """Fan out across companies and aggregate cited equity briefings.""" with flyte.group("research-companies"): briefings = await asyncio.gather( *[ research_company(c, focus, research_effort, freshness) for c in companies ] ) report = ResearchReport(briefings=list(briefings)) await flyte.report.replace.aio(_render_report(report), do_flush=True) await flyte.report.flush.aio() return report # {{/docs-fragment driver}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(financial_research) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/financial_research_agent/main.py* ## Orchestration The `financial_research` driver task fans out across all companies and renders a Flyte report with per-company briefings and citations. ``` # /// script # requires-python = "==3.13" # dependencies = [ # "flyte>=2.4.0", # "httpx>=0.27.0", # "litellm>=1.72.0", # ] # main = "financial_research" # params = "" # /// """Financial research & earnings-cycle agent. For each company, runs grounded, source-cited research via the You.com Research API plus a fresh-news layer via the Search API, then uses Claude to synthesize an analyst-ready equity briefing that preserves citations. Flyte caching cuts duplicate spend when runs converge. """ # {{docs-fragment env}} import asyncio import json import os from dataclasses import dataclass, field import flyte MODEL = "anthropic/claude-haiku-4-5" env = flyte.TaskEnvironment( name="financial-research", secrets=[ flyte.Secret(key="youdotcom-api-key", as_env_var="YDC_API_KEY"), flyte.Secret(key="internal-anthropic-api-key", as_env_var="ANTHROPIC_API_KEY"), ], image=flyte.Image.from_uv_script(__file__, name="financial-research", pre=True), resources=flyte.Resources(cpu="1", memory="1Gi"), cache="auto", ) # {{/docs-fragment env}} # {{docs-fragment data_types}} @dataclass class Source: title: str url: str domain: str = "" snippet: str = "" published: str = "" favicon: str = "" section: str = "research" # "research", "news", or "web" def _domain(url: str) -> str: from urllib.parse import urlparse try: return urlparse(url).netloc.replace("www.", "") except Exception: return "" def _favicon_for(url: str) -> str: return f"https://ydc-index.io/favicon?domain={_domain(url)}&size=128" @dataclass class Briefing: company: str thesis: str recent_developments: list[str] = field(default_factory=list) risks: list[str] = field(default_factory=list) watch_items: list[str] = field(default_factory=list) sources: list[Source] = field(default_factory=list) @dataclass class ResearchReport: briefings: list[Briefing] = field(default_factory=list) # {{/docs-fragment data_types}} # {{docs-fragment you_apis}} YOU_RESEARCH_URL = "https://api.you.com/v1/research" YOU_SEARCH_URL = "https://ydc-index.io/v1/search" async def _you_request(method: str, url: str, timeout: float, **kwargs) -> dict: """HTTP wrapper with exponential backoff + jitter on 429 rate limits. Fanned-out tasks run in separate pods, so we retry on the client side to smooth out bursts against the You.com API rate limit. """ import asyncio import random import httpx # YDC_API_KEY is canonical; YOU_API_KEY accepted as a backwards-compatible fallback. headers = {"X-API-Key": os.environ.get("YDC_API_KEY") or os.environ["YOU_API_KEY"]} if method == "POST": headers["Content-Type"] = "application/json" async with httpx.AsyncClient(timeout=timeout) as client: for attempt in range(7): resp = await client.request(method, url, headers=headers, **kwargs) if resp.status_code == 429 and attempt < 6: wait = float(resp.headers.get("retry-after") or 0) or min(2**attempt, 30) await asyncio.sleep(wait + random.uniform(0, 2)) continue resp.raise_for_status() return resp.json() resp.raise_for_status() return resp.json() @flyte.trace async def you_research(question: str, research_effort: str, freshness: str) -> dict: """Grounded, citation-backed research answer.""" body = { "input": question, "research_effort": research_effort, "source_control": {"freshness": freshness}, } return await _you_request("POST", YOU_RESEARCH_URL, 300.0, json=body) @flyte.trace async def you_news( query: str, count: int = 10, freshness: str = "week", boost_domains: str = "", ) -> list[dict]: """Fresh news headlines for a company. ``boost_domains`` (comma-separated) lifts authoritative financial outlets in ranking without restricting results to only those domains, so company press releases and niche coverage still surface when relevant. """ params: dict = {"query": query, "count": count, "freshness": freshness} if boost_domains: params["boost_domains"] = boost_domains data = await _you_request("GET", YOU_SEARCH_URL, 60.0, params=params) results = data.get("results", {}) out: list[dict] = [] for section in ("news", "web"): for item in results.get(section, []) or []: snippets = item.get("snippets") or [] url = item.get("url", "") out.append( { "title": item.get("title", ""), "url": url, "domain": _domain(url), "snippet": snippets[0] if snippets else item.get("description", ""), "published": item.get("page_age", "") or "", "favicon": item.get("favicon_url") or _favicon_for(url), "section": section, } ) return out # {{/docs-fragment you_apis}} # {{docs-fragment llm}} @flyte.trace async def synthesize_briefing(company: str, focus: str, research: str, news: str) -> dict: """Use Claude to synthesize a structured equity briefing.""" from litellm import acompletion system = ( "You are an equity research analyst. Using ONLY the grounded research " "and news provided, write a concise briefing. Respond ONLY with JSON: " '{"thesis": str, "recent_developments": [str], "risks": [str], ' '"watch_items": [str]}. Keep each list to 3-5 short, specific bullets.' ) user = ( f"Company: {company}\nFocus: {focus}\n\n" f"Grounded research:\n{research}\n\nRecent news:\n{news}" ) resp = await acompletion( model=MODEL, messages=[ {"role": "system", "content": system}, {"role": "user", "content": user}, ], temperature=0.0, max_tokens=1536, ) parsed = _parse_json(resp.choices[0].message.content) return parsed if isinstance(parsed, dict) else {} def _parse_json(text: str) -> dict | list: text = text.strip() if text.startswith("CODE7", 2)[1] if text.lstrip().startswith("json"): text = text.lstrip()[4:] start = min((i for i in (text.find("{"), text.find("[")) if i != -1), default=0) end = max(text.rfind("}"), text.rfind("]")) + 1 return json.loads(text[start:end]) # {{/docs-fragment llm}} # {{docs-fragment research_company}} # Tier-1 financial outlets that consistently break earnings, M&A, and # analyst-moving news. boost_domains lifts these in ranking without excluding # other sources, so company press releases and trade-press coverage still # surface when relevant. FINANCE_BOOST_DOMAINS = "reuters.com,bloomberg.com,wsj.com,marketwatch.com,cnbc.com,ft.com" @env.task(retries=3) async def research_company( company: str, focus: str, research_effort: str, freshness: str, ) -> Briefing: """Research one company and synthesize a cited briefing.""" question = ( f"Provide a grounded analysis of {company} with respect to: {focus}. " f"Cover recent financial performance, strategic moves, competitive " f"positioning, and risks." ) research_result, news = await asyncio.gather( you_research(question, research_effort, freshness), you_news( f"{company} earnings news", freshness=freshness, boost_domains=FINANCE_BOOST_DOMAINS, ), ) output = research_result.get("output", {}) research_text = output.get("content", "") if not isinstance(research_text, str): research_text = json.dumps(research_text) sources: list[Source] = [] for s in output.get("sources", []) or []: url = str(s.get("url", "")) sources.append( Source( title=str(s.get("title", "") or url), url=url, domain=_domain(url), snippet=str((s.get("snippets") or [""])[0]), favicon=_favicon_for(url), section="research", ) ) for n in news: sources.append( Source( title=str(n.get("title", "")), url=str(n.get("url", "")), domain=str(n.get("domain", "")), snippet=str(n.get("snippet", "")), published=str(n.get("published", "")), favicon=str(n.get("favicon", "")), section=str(n.get("section", "web")), ) ) news_text = "\n".join( f"- {n['title']} ({n['published']}) {n['domain']}: {n['snippet'][:120]}" for n in news ) parsed = await synthesize_briefing(company, focus, research_text, news_text) def _list(key: str) -> list[str]: return [str(x) for x in (parsed.get(key) or [])] return Briefing( company=company, thesis=str(parsed.get("thesis", "")), recent_developments=_list("recent_developments"), risks=_list("risks"), watch_items=_list("watch_items"), sources=sources, ) # {{/docs-fragment research_company}} # {{docs-fragment report}} REPORT_CSS = """ """ def _cite(s: Source) -> str: """Render a rich You.com citation (Research or Search source).""" if not s.url: return "" tag_cls = s.section if s.section in ("research", "news") else "web" meta_bits = [] if s.published: meta_bits.append(s.published[:10]) if s.title: meta_bits.append(s.title) meta = " · ".join(meta_bits) snip = f"
“{s.snippet}”
" if s.snippet else "" return ( f"
" f"
" f"{s.domain or 'source'}" f"{s.section}" f"
{meta}
{snip}
" ) def _render_report(report: ResearchReport) -> str: def _ul(items: list[str]) -> str: if not items: return "

None reported.

" return "
    " + "".join(f"
  • {x}
  • " for x in items) + "
" cards = [] for b in report.briefings: src = "".join(_cite(s) for s in b.sources[:10]) cards.append( f"

{b.company}

" f"
{b.thesis or 'No thesis generated.'}
" f"
" f"

Recent developments

{_ul(b.recent_developments)}
" f"

Risks

{_ul(b.risks)}
" f"

Watch items

{_ul(b.watch_items)}
" f"
" + (f"

You.com sources ({len(b.sources)})

{src}
" if src else "") + "
" ) total_sources = sum(len(b.sources) for b in report.briefings) return f""" {REPORT_CSS}

Financial Research Briefings

Grounded, citation-backed equity briefings โ€” each company backed by You.com Research synthesis plus fresh Search news.

{len(report.briefings)} companies {total_sources} You.com sources cited
{''.join(cards) or "

No briefings generated.

"}

Research answers from the You.com Research API (grounded synthesis with inline citations) plus fresh headlines from the You.com Search API (web + auto-classified news with timestamps and snippets).

""" # {{/docs-fragment report}} # {{docs-fragment driver}} @env.task(report=True) async def financial_research( companies: list[str] = [ "NVIDIA", "Advanced Micro Devices", "Microsoft", "Alphabet", "Amazon", "Meta Platforms", "Broadcom", "Taiwan Semiconductor Manufacturing", ], focus: str = "Q4 earnings preview and competitive positioning", research_effort: str = "standard", freshness: str = "month", ) -> ResearchReport: """Fan out across companies and aggregate cited equity briefings.""" with flyte.group("research-companies"): briefings = await asyncio.gather( *[ research_company(c, focus, research_effort, freshness) for c in companies ] ) report = ResearchReport(briefings=list(briefings)) await flyte.report.replace.aio(_render_report(report), do_flush=True) await flyte.report.flush.aio() return report # {{/docs-fragment driver}} # {{docs-fragment main}} if __name__ == "__main__": flyte.init_from_config() run = flyte.run(financial_research) print(run.url) run.wait() # {{/docs-fragment main}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/financial_research_agent/main.py* ## Run the agent ### Create secrets Get a You.com API key from the [You.com platform](https://you.com/platform) (see the [quickstart guide](https://you.com/docs/quickstart)). Get an Anthropic API key from the [Anthropic console](https://console.anthropic.com/). Register both keys as Flyte secrets. The secret key names must match those declared in the `TaskEnvironment`: ``` flyte create secret youdotcom-api-key --value flyte create secret internal-anthropic-api-key --value ``` See **Tasks > Configure tasks > Secrets** for scoping and file-based secrets. ### Run locally or remotely From the [example directory](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/financial_research_agent): ``` cd v2/tutorials/financial_research_agent uv run --script main.py ``` To test locally without Flyte secrets: ``` export YOU_API_KEY= export ANTHROPIC_API_KEY= uv run --script main.py ``` When the run completes, open the Flyte report to review equity briefings with thesis, risks, and You.com source citations for each company. === PAGE: https://www.union.ai/docs/v2/union/tutorials/frontier-ai === The everyday workloads of frontier AI labs: pretraining, data curation for text and video, evals on every checkpoint, interpretability, and AI-driven science. # Frontier AI Tutorials for the workloads of frontier AI labs. The headline training run is a small part of what a frontier AI lab does. Most of the work around it falls into three kinds: - **Data factories:** turning raw web text, video, audio, or lab measurements into training data, with every filter versioned and every document or clip traceable to the stage that kept it. - **Decisions from many small runs:** which checkpoint to ship, which data to keep, which candidate to send to an expensive experiment. - **Continuous measurement:** benchmarks on every checkpoint, and interpretability tools that look inside the model. These tutorials follow those workloads at a scale that runs in minutes, each tested end to end on a Union cluster. Each one names the labs and papers it is modeled on. | Tutorial | Who does this | What makes it hard at scale | | --- | --- | --- | | [Distributed LLM pretraining](./distributed-pretraining/_index) | Every foundation model lab | Multi-GPU training that has to survive failures and stream data | | [Refine a pretraining corpus](./pretraining-data-refinery/_index) | Pretraining data teams, as in FineWeb-Edu, Essential-Web, and Zyda-2 | Billions of documents, CPU and GPU stages, and LLM labels that cost too much to run on everything | | [Evaluate every checkpoint](./checkpoint-evals/_index) | Post-training and evals teams, as in OLMo and OLMES | Evals that must keep up with training without slowing it, and never re-run when nothing changed | | [Curate a video dataset for generative video](./video-data-curation/_index) | Generative video and world-model labs, as in Open-Sora and Stable Video Diffusion | Hours of footage through decoders, scoring models, and captioners on different hardware | | [Find features in a language model with sparse autoencoders](./sparse-autoencoders/_index) | Interpretability teams, as in Scaling Monosemanticity and Gemma Scope | Terabytes of activations, a grid of training runs, and thousands of LLM calls to label features | | [Closed-loop molecular discovery](./closed-loop-discovery/_index) | AI-for-science labs that run autonomous experiments | A slow, failure-prone oracle, a loop that runs for days, and a scientist who approves each batch | ### **Frontier AI > Distributed LLM pretraining** Pretrain large language models at scale with PyTorch Lightning, FSDP, and H200 GPUs, featuring streaming data and real-time metrics. ### **Frontier AI > Refine a pretraining corpus** Turn raw web text into pretraining data with heuristic filters, global deduplication, eval decontamination, and a quality classifier distilled from LLM labels. ### **Frontier AI > Evaluate every checkpoint** Publish every checkpoint of a fine-tuning run as an artifact version, let an artifact trigger run a benchmark suite on each one while training continues, and promote the checkpoint that wins a ship rule. ### **Frontier AI > Curate a video dataset for generative video** Cut long-form films into shots, score every clip for exposure, blur, on-screen text, aesthetics and motion on pools of CPU and GPU workers, caption the keepers with a small vision-language model, and publish the result as a dataset artifact. ### **Frontier AI > Find features in a language model with sparse autoencoders** Harvest a language model's activations once, train a grid of TopK sparse autoencoders in parallel on GPUs, and have Claude label and score the features they find. ### **Frontier AI > Closed-loop molecular discovery** An active learning loop where a surrogate model proposes molecules, a quantum chemistry oracle measures them on a warm CPU pool, and a scientist approves each batch before it runs. ## Related - [Reinforcement learning](../reinforcement-learning/_index): RL for LLMs, agents, robots, and games, including durable agentic RL with SkyRL and Harbor. - [Speculative decoding models](../speculative-decoding/_index): train and serve draft models that make an LLM generate faster. ## Subpages - **Frontier AI > Distributed LLM pretraining** - Pretrain large language models at scale with PyTorch Lightning, FSDP, and H200 GPUs, featuring streaming data and real-time metrics. - **Frontier AI > Refine a pretraining corpus** - Turn raw web text into pretraining data with heuristic filters, global deduplication, eval decontamination, and a quality classifier distilled from LLM labels. - **Frontier AI > Evaluate every checkpoint** - Publish every checkpoint of a fine-tuning run as an artifact version, let an artifact trigger run a benchmark suite on each one while training continues, and promote the checkpoint that wins a ship rule. - **Frontier AI > Curate a video dataset for generative video** - Cut long-form films into shots, score every clip for exposure, blur, on-screen text, aesthetics and motion on pools of CPU and GPU workers, caption the keepers with a small vision-language model, and publish the result as a dataset artifact. - **Frontier AI > Find features in a language model with sparse autoencoders** - Harvest a language model's activations once, train a grid of TopK sparse autoencoders in parallel on GPUs, and have Claude label and score the features they find. - **Frontier AI > Closed-loop molecular discovery** - An active learning loop where a surrogate model proposes molecules, a quantum chemistry oracle measures them on a warm CPU pool, and a scientist approves each batch before it runs. === PAGE: https://www.union.ai/docs/v2/union/tutorials/frontier-ai/distributed-pretraining === Pretrain large language models at scale with PyTorch Lightning, FSDP, and H200 GPUs, featuring streaming data and real-time metrics. # Distributed LLM pretraining When training large models, infrastructure should not be the hardest part. The real work is in the model architecture, the data, and the hyperparameters. In practice, though, teams often spend weeks just trying to get distributed training to run reliably. And when it breaks, it usually breaks in familiar ways: out-of-memory crashes, corrupted checkpoints, data loaders that silently fail, or runs that hang with no obvious explanation. Most distributed training tutorials focus on PyTorch primitives. This one focuses on getting something that actually ships. We go into the technical details, such as how FSDP shards parameters, why gradient clipping behaves differently at scale, and how streaming datasets reduce memory pressure, but always with the goal of building a system that works in production. Real training jobs need more than a training loop. They need checkpointing, fault tolerance, data streaming, visibility into whatโ€™s happening, and the ability to recover from failures. In this tutorial, we build all of that using Flyte, without having to stand up or manage any additional infrastructure. > [!NOTE] > Full code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/pretraining/train.py). ## Overview We're going to pretrain a GPT-2 style language model from scratch. This involves training on raw text data starting from randomly initialized weights, rather than fine-tuning or adapting a pretrained model. This is the same process used to train the original GPT-2, LLaMA, and most other foundation models. The model learns by predicting the next token. Given "The cat sat on the", it learns to predict "mat". Do this billions of times across terabytes of text, and the model develops surprisingly sophisticated language understanding. That's pretraining. The challenge is scale. A 30B parameter model doesn't fit on a single GPU. The training dataset, [SlimPajama](https://huggingface.co/datasets/cerebras/SlimPajama-627B) in our case, is 627 billion tokens. Training runs last for days or even weeks. To make this work, you need: - **Distributed training**: Split the model across multiple GPUs using [FSDP (Fully Sharded Data Parallel)](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) - **Data streaming**: Pull training data on-demand instead of downloading terabytes upfront - **Checkpointing**: Save progress regularly so a failure doesnโ€™t wipe out days of compute - **Observability**: See what's happening inside a multi-day training run Weโ€™ll build a Flyte pipeline that takes care of all of this, using three tasks with clearly defined responsibilities: 1. **Data preparation**: Tokenizes your dataset and converts it to MDS (MosaicML Data Shard) format for streaming. This Flyte task is cached, so it only needs to be run once and can be reused across runs. 2. **Distributed training**: Runs FSDP across 8 H200 GPUs. A `ClusteredTaskEnvironment` launches the training nodes together and starts torchrun on each one. Checkpoints upload to S3 automatically via Flyte's `File` abstraction. 3. **Real-time reporting**: Streams loss curves and training metrics to Flyte Reports, a live dashboard integrated into the Flyte UI. Why three separate tasks? Flyte makes this separation efficient: - **Caching**: The data preparation step runs once. On subsequent runs, Flyte skips it entirely. - **Resource isolation**: Training uses expensive H200 GPUs only while actively training, while the driver runs on inexpensive CPU instances. - **Fault boundaries**: If training fails, the data preparation step does not re-run. Training can resume directly from the most recent checkpoint. ## Implementation Let's walk through the code. We'll start with the infrastructure setup, build the model, then wire everything together into a pipeline. ### Setting up the environment Every distributed training job needs a consistent environment across all nodes. Flyte handles this with container images: ``` import logging import math import os from pathlib import Path from typing import Optional import flyte import flyte.report import lightning as L import numpy as np import torch import torch.nn as nn from flyte.clustered import ClusteredTaskEnvironment, ClusterFailurePolicy, TorchRun from flyte.io import Dir, File ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* The imports tell the story: `flyte` for orchestration, `flyte.report` for live dashboards, `lightning` for training loop management, and `flyte.clustered` for multi-node training. That last one is built into the Flyte SDK. It launches PyTorch's distributed training across nodes, so you write no distributed setup code. ``` # Cluster shapes for the training task. "h200" is the full setup: one node with # 8 H200 GPUs. "l4-test" is a cheap test of the same code on 2 nodes with one L4 # GPU each. Pick one with PRETRAIN_CLUSTER=. CLUSTER_SHAPES = { "h200": dict( nodes=1, gpus_per_node=8, gpu="H200", cpu=64, memory="512Gi", disk="1Ti", shm="16Gi", data_cpu=5, data_memory="28Gi", ), "l4-test": dict( nodes=2, gpus_per_node=1, gpu="L4", cpu=4, memory="24Gi", disk="100Gi", shm="4Gi", data_cpu=4, data_memory="16Gi", ), } CLUSTER = os.getenv("PRETRAIN_CLUSTER", "h200") SHAPE = CLUSTER_SHAPES[CLUSTER] NUM_NODES = SHAPE["nodes"] DEVICES_PER_NODE = SHAPE["gpus_per_node"] VOCAB_SIZE = ( 50257 # GPT-2 BPE tokenizer vocabulary size (constant across all model sizes) ) N_POSITIONS = 2048 # Maximum sequence length (constant across all model sizes) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* These constants define the distributed topology. The `h200` shape is the full setup: 1 node with 8 H200 GPUs. You can scale it up by changing `nodes`. The `l4-test` shape runs the same code on 2 nodes with one L4 GPU each, a cheap way to test the multi-node setup before you rent H200s. Set `PRETRAIN_CLUSTER` to choose a shape. The vocabulary size (50,257 tokens) and sequence length (2,048 tokens) match GPT-2's [Byte Pair Encoding (BPE) tokenizer](https://huggingface.co/learn/llm-course/en/chapter6/5). ``` image = flyte.Image.from_debian_base( name="distributed_training_h200" ).with_pip_packages( "transformers==4.57.3", "datasets==4.4.1", "tokenizers==0.22.1", "huggingface-hub==0.34.0", "mosaicml-streaming>=0.7.0", "pyarrow==22.0.0", "torch==2.9.1", "lightning==2.5.6", "tensorboard==2.20.0", "sentencepiece==0.2.1", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* Flyte builds this container automatically when the pipeline is run. All dependencies required for distributed training, including PyTorch, Lightning, the streaming library, and NCCL for GPU communication, are baked in. There's no Dockerfile to maintain and no "works on my machine" debugging. ### Declaring resource requirements Different parts of the pipeline need different resources. Data tokenization needs CPU and memory. Training needs GPUs. The driver just coordinates. Each task gets its own environment that declares exactly what it needs: ``` data_loading_env = flyte.TaskEnvironment( name="data_loading_h200", image=image, resources=flyte.Resources(cpu=SHAPE["data_cpu"], memory=SHAPE["data_memory"], disk="100Gi"), env_vars={ "HF_DATASETS_CACHE": "/tmp/hf_cache", # Cache directory for datasets "TOKENIZERS_PARALLELISM": "true", # Enable parallel tokenization }, cache="auto", ) distributed_llm_training_env = ClusteredTaskEnvironment( name="distributed_llm_training_h200", image=image, # Resources are per node: each replica gets its own GPUs, CPUs, and memory. resources=flyte.Resources( cpu=SHAPE["cpu"], memory=SHAPE["memory"], gpu=f"{SHAPE['gpu']}:{DEVICES_PER_NODE}", disk=SHAPE["disk"], shm=SHAPE["shm"], # Explicit shared memory for NCCL communication ), replicas=NUM_NODES, # One pod per node, scheduled together nproc_per_node=DEVICES_PER_NODE, # One torchrun process per GPU runtime=TorchRun(), failure_policy=ClusterFailurePolicy(max_restarts=1), env_vars={ "TORCH_DISTRIBUTED_DEBUG": "INFO", "NCCL_DEBUG": "WARN", }, cache="auto", ) driver_env = flyte.TaskEnvironment( name="llm_training_driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), # The driver builds the training task's spec when it calls it, so it must # see the same cluster shape as your machine. env_vars={"PRETRAIN_CLUSTER": CLUSTER}, cache="auto", depends_on=[data_loading_env, distributed_llm_training_env], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* Let's break down the training environment, since this is where most of the complexity lives: - **`ClusteredTaskEnvironment`**: Runs the training task on `replicas` identical pods, one per node, and starts them as a group. On each pod it runs torchrun with `nproc_per_node` processes, one per GPU. torchrun assigns each process its rank and sets the master address and world size, which replaces the launch scripts you would otherwise write. - **`resources`**: These apply to each node. With the `h200` shape, `gpu="H200:8"` gives each node 8 H200 GPUs with 141GB of memory each, enough to train 30B+ parameter models with FSDP. Two replicas would be a 16-GPU job. - **`shm="16Gi"`**: This allocates explicit shared memory. NCCL (NVIDIA's communication library) uses shared memory for inter-GPU communication on the same node. Without this, you'll see cryptic errors like "NCCL error: unhandled system error", which can be difficult to debug. - **`failure_policy=ClusterFailurePolicy(max_restarts=1)`**: If a worker fails, Flyte recreates every pod in the group once before failing the task. A restarted group starts training from scratch unless you resume from a checkpoint; see **Model training > Durable training**. The `driver_env` is intentionally lightweight, using 2 CPUs and 4 GB of memory. Its role is limited to orchestrating tasks and passing data between them, so allocating GPUs here would be unnecessary. It also gets `PRETRAIN_CLUSTER`, because the driver builds the training task's spec when it calls the task, so it must pick the same cluster shape as your machine. ### Model configurations Training a 1.5B model uses different hyperparameters than training a 65B model. Rather than hardcoding values, we define presets: ``` MODEL_CONFIGS = { "125M": { "n_embd": 768, "n_layer": 12, "n_head": 12, "batch_size": 8, "learning_rate": 6e-4, "checkpoint_every_n_steps": 50, "report_every_n_steps": 5, "val_check_interval": 320, }, # Small enough for the l4-test cluster shape "1.5B": { "n_embd": 2048, "n_layer": 24, "n_head": 16, "batch_size": 8, "learning_rate": 6e-4, "checkpoint_every_n_steps": 10, "report_every_n_steps": 5, "val_check_interval": 100, }, # Good for testing and debugging "30B": { "n_embd": 6656, "n_layer": 48, "n_head": 52, "batch_size": 1, "learning_rate": 1.6e-4, "checkpoint_every_n_steps": 7500, "report_every_n_steps": 200, "val_check_interval": 1000, }, "65B": { "n_embd": 8192, "n_layer": 80, "n_head": 64, "batch_size": 1, "learning_rate": 1.5e-4, "checkpoint_every_n_steps": 10000, "report_every_n_steps": 250, "val_check_interval": 2000, }, } def get_model_config(model_size: str) -> dict: if model_size not in MODEL_CONFIGS: available = ", ".join(MODEL_CONFIGS.keys()) raise ValueError(f"Unknown model size: {model_size}. Available: {available}") return MODEL_CONFIGS[model_size] ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* A few things to notice: - **Batch size decreases with model size**: For a fixed GPU memory budget, larger models consume more memory for parameters, optimizer state, and activations, leaving less room for per-GPU batch size. For example, a 1.5B parameter model may fit a batch size of 8 per GPU, while a 65B model may only fit a batch size of 1. This is typically compensated for using gradient accumulation to maintain a larger effective batch size. - **Learning rate decreases with model size**: Larger models are more sensitive to optimization instability and typically require lower learning rates. The values here follow empirical best practices used in large-scale language model training, informed by work such as the [Chinchilla study](https://arxiv.org/pdf/2203.15556) on compute-optimal scaling. - **Checkpoint interval increases with model size**: Checkpointing a 65B model is expensive (the checkpoint is huge). We do it less often but make sure we don't lose too much progress if something fails. The 1.5B config is good for testing your setup before committing to a serious training run. ### Building the GPT model Now for the model itself. We're building a GPT-2 style decoder-only transformer from scratch. First, the configuration class: ``` class GPTConfig: """Configuration for GPT model.""" def __init__( self, vocab_size: int = VOCAB_SIZE, n_positions: int = N_POSITIONS, n_embd: int = 2048, n_layer: int = 24, n_head: int = 16, n_inner: Optional[int] = None, activation_function: str = "gelu_new", dropout: float = 0.1, layer_norm_epsilon: float = 1e-5, ): self.vocab_size = vocab_size self.n_positions = n_positions self.n_embd = n_embd self.n_layer = n_layer self.n_head = n_head self.n_inner = n_inner if n_inner is not None else 4 * n_embd self.activation_function = activation_function self.dropout = dropout self.layer_norm_epsilon = layer_norm_epsilon ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* The key architectural parameters: - **`n_embd`**: The hidden (embedding) dimension. Larger values increase model capacity but also increase memory and compute requirements. - **`n_layer`**: The number of transformer blocks. Model depth strongly influences expressiveness and performance. - **`n_head`**: The number of attention heads. Each head can attend to different patterns or relationships in the input. - **`n_inner`**: The hidden dimension of the feed-forward network (MLP), typically set to 4x the embedding dimension. Next, we define a single transformer block: ``` class GPTBlock(nn.Module): """Transformer block with causal self-attention.""" def __init__(self, config: GPTConfig): super().__init__() self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon) self.attn = nn.MultiheadAttention( config.n_embd, config.n_head, dropout=config.dropout, batch_first=True, ) self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon) # Get activation function from config ACT_FNS = { "gelu": nn.GELU(), "gelu_new": nn.GELU(approximate="tanh"), # GPT-2 uses approximate GELU "relu": nn.ReLU(), "silu": nn.SiLU(), "swish": nn.SiLU(), # SiLU = Swish } act_fn = ACT_FNS.get(config.activation_function, nn.GELU()) self.mlp = nn.Sequential( nn.Linear(config.n_embd, config.n_inner), act_fn, nn.Linear(config.n_inner, config.n_embd), nn.Dropout(config.dropout), ) def forward(self, x, causal_mask, key_padding_mask=None): x_normed = self.ln_1(x) # Self-attention with causal and padding masks attn_output, _ = self.attn( x_normed, # query x_normed, # key x_normed, # value attn_mask=causal_mask, # Causal mask: (seq_len, seq_len) key_padding_mask=key_padding_mask, # Padding mask: (batch, seq_len) need_weights=False, ) x = x + attn_output # MLP with residual x = x + self.mlp(self.ln_2(x)) return x ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* Each block has two sub-layers: causal self-attention and a feed-forward MLP. The causal mask ensures the model can only attend to previous tokens in the sequence, so it can't "cheat" by looking at the answer. This is what makes it *autoregressive*. The full `GPTModel` class (see the complete code) stacks these blocks and adds token and positional embeddings. One important detail is that the input token embedding matrix is shared with the output projection layer (often called [weight tying](https://mbrenndoerfer.com/writing/weight-tying-shared-embeddings-transformers)). This reduces the number of parameters by roughly 50 million for typical vocabulary sizes and often leads to better generalization and more stable training. ### The Lightning training module PyTorch Lightning handles the training loop boilerplate. We wrap our model in a `LightningModule` that defines how to train it: ``` class GPTPreTrainingModule(L.LightningModule): """PyTorch Lightning module for GPT pre-training.""" def __init__( self, vocab_size: int = 50257, n_positions: int = 2048, n_embd: int = 2048, n_layer: int = 24, n_head: int = 16, learning_rate: float = 6e-4, weight_decay: float = 0.1, warmup_steps: int = 2000, max_steps: int = 100000, ): super().__init__() self.save_hyperparameters() config = GPTConfig( vocab_size=vocab_size, n_positions=n_positions, n_embd=n_embd, n_layer=n_layer, n_head=n_head, ) self.model = GPTModel(config) def forward(self, input_ids, attention_mask=None): return self.model(input_ids, attention_mask) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* The `save_hyperparameters()` call is important because it stores all constructor arguments in the checkpoint. This allows the model to be reloaded later without having to manually reconstruct the original configuration. The training and validation steps implement standard causal language modeling, where the model is trained to predict the next token given all previous tokens in the sequence. ``` def training_step(self, batch, _batch_idx): # Convert int32 to int64 (long) - MDS stores as int32 but PyTorch expects long input_ids = batch["input_ids"].long() labels = batch["labels"].long() # Get attention mask if present (optional, for padded sequences) # attention_mask: 1 = real token, 0 = padding # Note: Current data pipeline creates fixed-length sequences without padding, # so attention_mask is not present. If using padded sequences, ensure: # - Padded positions in labels are set to -100 (ignored by cross_entropy) # - attention_mask marks real tokens (1) vs padding (0) attention_mask = batch.get("attention_mask", None) # Forward pass (causal mask is created internally in GPTModel) logits = self(input_ids, attention_mask=attention_mask) # Shift logits and labels for causal language modeling # Before shift: labels[i] = input_ids[i] # After shift: predict input_ids[i+1] from input_ids[:i+1] shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Calculate loss loss = nn.functional.cross_entropy( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), ignore_index=-100, ) # Log loss self.log( "train/loss", loss, on_step=True, on_epoch=True, prog_bar=True, sync_dist=True, ) # Calculate and log perplexity only on epoch (exp is costly, less frequent is fine) perplexity = torch.exp(torch.clamp(loss, max=20.0)) self.log( "train/perplexity", perplexity, on_step=False, on_epoch=True, prog_bar=True, sync_dist=True, ) return loss def validation_step(self, batch, _batch_idx): # Convert int32 to int64 (long) - MDS stores as int32 but PyTorch expects long input_ids = batch["input_ids"].long() labels = batch["labels"].long() # Get attention mask if present (optional, for padded sequences) attention_mask = batch.get("attention_mask", None) # Forward pass (causal mask is created internally in GPTModel) logits = self(input_ids, attention_mask=attention_mask) # Shift logits and labels shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Calculate loss loss = nn.functional.cross_entropy( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), ignore_index=-100, ) # Log loss self.log("val/loss", loss, prog_bar=True, sync_dist=True) # Calculate and log perplexity (exp is costly, but validation is infrequent so OK) perplexity = torch.exp(torch.clamp(loss, max=20.0)) self.log("val/perplexity", perplexity, prog_bar=True, sync_dist=True) return loss ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* The model performs a forward pass with a causal (autoregressive) mask created internally, ensuring each token can only attend to earlier positions. To align predictions with targets, the logits and labels are shifted so that the representation at position `i` is used to predict token `i + 1`. Loss is computed using cross-entropy over the shifted logits and labels. Training loss and perplexity are logged during execution, with metrics synchronized across distributed workers. The optimizer setup is where a lot of training stability comes from: ``` def configure_optimizers(self): # Separate parameters into weight decay and no weight decay groups decay_params = [] no_decay_params = [] for param in self.model.parameters(): if param.requires_grad: # 1D parameters (biases, LayerNorm) don't get weight decay # 2D+ parameters (weight matrices) get weight decay if param.ndim == 1: no_decay_params.append(param) else: decay_params.append(param) optimizer_grouped_parameters = [ {"params": decay_params, "weight_decay": self.hparams.weight_decay}, {"params": no_decay_params, "weight_decay": 0.0}, ] # AdamW optimizer optimizer = torch.optim.AdamW( optimizer_grouped_parameters, lr=self.hparams.learning_rate, betas=(0.9, 0.95), eps=1e-8, ) # Learning rate scheduler: warmup + cosine decay # Warmup: linear increase from 0 to 1.0 over warmup_steps # Decay: cosine decay from 1.0 to 0.0 over remaining steps def lr_lambda(current_step): if current_step < self.hparams.warmup_steps: # Linear warmup return float(current_step) / float(max(1, self.hparams.warmup_steps)) # Cosine decay after warmup progress = (current_step - self.hparams.warmup_steps) / max( 1, self.hparams.max_steps - self.hparams.warmup_steps ) # Cosine annealing from 1.0 to 0.0 (returns float, not tensor) return 0.5 * (1.0 + math.cos(progress * math.pi)) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": scheduler, "interval": "step", }, } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* Two important choices here: 1. **Separate weight decay groups**: We only apply weight decay to the weight matrices, not to biases or LayerNorm parameters. This follows the original BERT paper and is now standard practice, as regularizing biases and normalization parameters does not improve performance and can be harmful. 2. **Cosine learning rate schedule with warmup**: We start with a low learning rate, ramp up linearly during warmup (helps stabilize early training when gradients are noisy), then decay following a cosine curve. This schedule outperforms constant or step decay for transformer training. ### Checkpointing for fault tolerance Training a 30B-parameter model for 15,000 steps can take days. Hardware failures and spot instance preemptions are inevitable, which makes checkpointing essential. ``` class S3CheckpointCallback(L.Callback): """ Periodically upload checkpoints to S3 for durability and resumption. This ensures checkpoints are safely stored in remote storage even if the training job is interrupted or the instance fails. """ def __init__(self, checkpoint_dir: Path, upload_every_n_steps: int): super().__init__() self.checkpoint_dir = checkpoint_dir self.upload_every_n_steps = upload_every_n_steps self.last_uploaded_step = -1 def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): """Upload checkpoint to S3 every N steps.""" if trainer.global_rank != 0: return # Only upload from rank 0 current_step = trainer.global_step # Upload every N steps (aligns with ModelCheckpoint's every_n_train_steps) if ( current_step % self.upload_every_n_steps == 0 and current_step > self.last_uploaded_step and current_step > 0 ): try: # Find the most recent checkpoint file checkpoint_files = list(self.checkpoint_dir.glob("*.ckpt")) if not checkpoint_files: print("No checkpoint files found to upload") return # Get the latest checkpoint (by modification time) latest_checkpoint = max( checkpoint_files, key=lambda p: p.stat().st_mtime ) # Upload the checkpoint file directly to S3 using File.from_local_sync checkpoint_file = File.from_local_sync(str(latest_checkpoint)) print(f"Checkpoint uploaded to S3 at: {checkpoint_file.path}") self.last_uploaded_step = current_step except Exception as e: print(f"Warning: Failed to upload checkpoint to S3: {e}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* This callback runs every `N` training steps and uploads the checkpoint to durable storage. The key line is `File.from_local_sync()` which is a Flyte abstraction for uploading files. There are no blob store credentials to manage and no bucket paths to hardcode. Flyte automatically uses the storage backend configured for your cluster. The callback only runs on rank 0. Each GPU holds only a shard of the model. The FSDP strategy below sets `state_dict_type="full"`, so Lightning gathers the full model and optimizer state onto rank 0. Only rank 0 saves the checkpoint file. Running the callback on rank 0 alone uploads that file once. When you restart a failed run, pass the checkpoint via `resume_checkpoint` so training resumes exactly where it left off, including the same step count, optimizer state, and learning rate schedule position. ### Real-time metrics with Flyte reports Multi-day training runs need observability. Is the loss decreasing? Did training diverge? Is the learning rate schedule behaving correctly? Flyte Reports let you build live dashboards directly in the UI: ``` class FlyteReportingCallback(L.Callback): """Custom Lightning callback to report training metrics to Flyte Report.""" def __init__(self, report_every_n_steps: int = 100): super().__init__() self.report_every_n_steps = report_every_n_steps self.metrics_history = { "step": [], "train_loss": [], "learning_rate": [], "val_loss": [], "val_perplexity": [], } self.initialized_report = False self.last_logged_step = -1 def on_train_start(self, trainer, pl_module): """Initialize the live dashboard on training start.""" if trainer.global_rank == 0 and not self.initialized_report: self._initialize_report() self.initialized_report = True ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* The `_initialize_report` method (see complete code) creates an HTML/JavaScript dashboard with interactive charts. The callback then calls `flyte.report.log()` every `N` steps to push new metrics. The charts update in real-time so you can watch your loss curve descend while training runs. There is no need to deploy Grafana, configure Prometheus, or keep a TensorBoard server running. Using `flyte.report.log()` is sufficient to get live training metrics directly in the Flyte UI. ![Metrics viz](../../../_static/images/tutorials/distributed-llm-pretraining/metrics.png) ### Streaming data at scale Training datasets are massive. SlimPajama contains 627 billion tokens and spans hundreds of gigabytes even when compressed. Downloading the entire dataset to each training node before starting would take hours and waste storage. Instead, we convert the data to MDS (MosaicML Data Shard) format and stream it during training: ``` @data_loading_env.task async def load_and_prepare_streaming_dataset( dataset_name: str, dataset_config: Optional[str], max_length: int, train_split: str, val_split: Optional[str], max_train_samples: Optional[int], max_val_samples: Optional[int], shard_size_mb: int, ) -> Dir: """Tokenize dataset and convert to MDS format for streaming.""" from datasets import load_dataset from streaming import MDSWriter from transformers import GPT2TokenizerFast output_dir = Path("/tmp/streaming_dataset") output_dir.mkdir(parents=True, exist_ok=True) tokenizer = GPT2TokenizerFast.from_pretrained("gpt2") tokenizer.pad_token = tokenizer.eos_token # MDS schema: what each sample contains columns = { "input_ids": "ndarray:int32", "labels": "ndarray:int32", } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* This task does three things: 1. **Tokenizes the text** using GPT-2's BPE tokenizer 2. **Concatenates documents** into fixed-length sequences (no padding waste) 3. **Writes shards** to storage in a format optimized for streaming The task returns a Flyte `Dir` object, which is a reference to the output location. It's not the data itself, just a pointer. When the training task receives this `Dir`, it streams shards on-demand rather than downloading everything upfront. Flyte caches this task automatically. Run the pipeline twice with the same dataset config, and Flyte skips tokenization entirely on the second run. Change the dataset or sequence length, and it re-runs. ### Distributed training with FSDP Now we get to the core: actually training the model across multiple GPUs. FSDP is what makes this possible for large models. ``` @distributed_llm_training_env.task(report=True) def train_distributed_llm( prepared_dataset: Dir, resume_checkpoint: Optional[Dir], vocab_size: int, n_positions: int, n_embd: int, n_layer: int, n_head: int, batch_size: int, num_workers: int, max_steps: int, learning_rate: float, weight_decay: float, warmup_steps: int, use_fsdp: bool, checkpoint_upload_steps: int, checkpoint_every_n_steps: int, report_every_n_steps: int, val_check_interval: int, grad_accumulation_steps: int = 1, ) -> Optional[Dir]: # ... setup code ... ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* Notice `report=True` on the task decorator. It enables Flyte Reports for this specific task. The training task receives the prepared dataset as a `Dir` and streams data directly from storage: ``` # StreamingDataset streams shards from the remote Flyte storage on-demand # It automatically detects torch.distributed context # and shards data across GPUs - each rank gets different data automatically train_dataset = StreamingDataset( remote=f"{remote_path}/train", # Remote MDS shard location local=str(local_cache / "train"), # Local cache for downloaded shards shuffle=True, # Shuffle samples shuffle_algo="naive", # Shuffling algorithm batch_size=batch_size, # Used for shuffle buffer sizing ) # Create validation StreamingDataset if it exists val_dataset = None try: val_dataset = StreamingDataset( remote=f"{remote_path}/validation", local=str(local_cache / "validation"), shuffle=False, # No shuffling for validation batch_size=batch_size, ) print( f"Validation dataset initialized with streaming from: {remote_path}/validation" ) except Exception as e: print(f"No validation dataset found: {e}") # Create data loaders # StreamingDataset handles distributed sampling internally by detecting # torch.distributed.get_rank() and torch.distributed.get_world_size() train_loader = DataLoader( train_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, persistent_workers=True, drop_last=True, # Drop incomplete batches for distributed training collate_fn=mds_collate_fn, # Handle read-only arrays ) # Create validation loader if validation dataset exists val_loader = None if val_dataset is not None: val_loader = DataLoader( val_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, persistent_workers=True, drop_last=False, collate_fn=mds_collate_fn, ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* `prepared_dataset.path` provides the remote storage path for the dataset. MosaicML's `StreamingDataset` automatically shards data across GPUs so that each rank sees different samples, without requiring a manual distributed sampler. The credentials are already in the environment because Flyte set them up. FSDP is where the memory magic happens. Instead of each GPU holding a full copy of the model (like Distributed Data Parallel (DDP)), FSDP shards the parameters, gradients, and optimizer states across all GPUs. Each GPU only holds 1/8th of the model. When a layer needs to run, FSDP all-gathers the full parameters, runs the computation, then discards them. ``` # Configure distributed strategy if use_fsdp: from torch.distributed.fsdp.wrap import ModuleWrapPolicy strategy = FSDPStrategy( auto_wrap_policy=ModuleWrapPolicy([GPTBlock]), activation_checkpointing_policy=None, cpu_offload=False, # H200 has 141GB - no CPU offload needed state_dict_type="full", sharding_strategy="FULL_SHARD", process_group_backend="nccl", ) else: from lightning.pytorch.strategies import DDPStrategy strategy = DDPStrategy(process_group_backend="nccl") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* We wrap at the `GPTBlock` level because each transformer block becomes an FSDP unit. This balances communication overhead (more units = more all-gathers) against memory savings (smaller units = more granular sharding). One subtle detail: gradient clipping. With FSDP, gradients are sharded across ranks, so computing a global gradient norm would require an expensive all-reduce operation. Instead of norm-based clipping, we use value-based gradient clipping, which clamps each individual gradient element to a fixed range. This can be done independently on each rank with no coordination overhead and is commonly used for large-scale FSDP training. ``` # torchrun has already started one process per GPU on every node. Lightning # attaches to that process group, so devices and num_nodes must match the # cluster topology, which flyte.ctx() reports. ctx = flyte.ctx() trainer = L.Trainer( strategy=strategy, accelerator="gpu", devices=ctx.local_world_size or DEVICES_PER_NODE, num_nodes=ctx.nnodes or NUM_NODES, # Training configuration max_steps=max_steps, precision="bf16-mixed", # BFloat16 for better numerical stability # Optimization gradient_clip_val=1.0, gradient_clip_algorithm=( "value" if use_fsdp else "norm" ), # FSDP requires 'value', DDP can use 'norm' accumulate_grad_batches=grad_accumulation_steps, # Logging and checkpointing callbacks=callbacks, log_every_n_steps=report_every_n_steps, val_check_interval=val_check_interval, # Performance benchmark=True, deterministic=False, # Enable gradient checkpointing for memory efficiency enable_checkpointing=True, use_distributed_sampler=False, # StreamingDataset handles distributed sampling ) # Train the model (resume from checkpoint if provided) trainer.fit(model, train_loader, val_loader, ckpt_path=ckpt_path) # Print final results if trainer.global_rank == 0: if val_loader is not None: print( f"Final validation loss: {trainer.callback_metrics.get('val/loss', 0.0):.4f}" ) print( f"Final validation perplexity: {trainer.callback_metrics.get('val/perplexity', 0.0):.4f}" ) print(f"Checkpoints saved to: {checkpoint_dir}") return Dir.from_local_sync(output_dir) return None ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* The trainer configuration brings together all the pieces we've discussed: - **`devices` and `num_nodes`**: torchrun has already started one process per GPU on every node, and Lightning attaches to those processes instead of spawning its own. The two values must match the cluster, so they come from `flyte.ctx()`, which reports the processes per node and the node count. - **`precision="bf16-mixed"`**: BFloat16 mixed precision training. BF16 has the same dynamic range as FP32 (unlike FP16), so you don't need loss scaling. This is the standard choice for modern GPU training. - **`gradient_clip_val=1.0`**: Clips gradients to prevent exploding gradients during training. Combined with value-based clipping for FSDP compatibility. - **`accumulate_grad_batches`**: Accumulates gradients over multiple forward passes before updating weights. This lets us hit a larger effective batch size than what fits in GPU memory. - **`val_check_interval`**: How often to run validation. For long training runs, you don't want to validate every epoch. That would be too infrequent. Instead, validate every `N` training steps. - **`use_distributed_sampler=False`**: We disable Lightning's built-in distributed sampler because `StreamingDataset` handles data sharding internally. Using both would cause conflicts. - **`benchmark=True`**: Enables cuDNN autotuning. PyTorch will benchmark different convolution algorithms on the first batch and pick the fastest one for your specific input sizes. The trainer then calls `fit()` with the model, data loaders, and optionally a checkpoint path to resume from. ### Tying it together The pipeline task orchestrates everything: ``` @driver_env.task async def distributed_llm_pipeline( model_size: str, dataset_name: str = "Salesforce/wikitext", dataset_config: str = "wikitext-103-raw-v1", max_length: int = 2048, max_train_samples: Optional[int] = 10000, max_val_samples: Optional[int] = 1000, max_steps: int = 100000, resume_checkpoint: Optional[Dir] = None, checkpoint_upload_steps: int = 1000, # Optional overrides (if None, uses model preset defaults) batch_size: Optional[int] = None, learning_rate: Optional[float] = None, use_fsdp: bool = True, ) -> Optional[Dir]: # Get model configuration model_config = get_model_config(model_size) # Use preset values if not overridden actual_batch_size = ( batch_size if batch_size is not None else model_config["batch_size"] ) actual_learning_rate = ( learning_rate if learning_rate is not None else model_config["learning_rate"] ) # Step 1: Load and prepare streaming dataset prepared_dataset = await load_and_prepare_streaming_dataset( dataset_name=dataset_name, dataset_config=dataset_config, max_length=max_length, train_split="train", val_split="validation", max_train_samples=max_train_samples, max_val_samples=max_val_samples, shard_size_mb=64, # 64MB shards ) # Step 2: Run distributed training if resume_checkpoint is not None: print("\nStep 2: Resuming distributed training from checkpoint...") else: print("\nStep 2: Starting distributed training from scratch...") target_global_batch = 256 world_size = NUM_NODES * DEVICES_PER_NODE effective_per_step = world_size * actual_batch_size grad_accumulation_steps = max( 1, math.ceil(target_global_batch / max(1, effective_per_step)) ) checkpoint_dir = await train_distributed_llm.aio( prepared_dataset=prepared_dataset, resume_checkpoint=resume_checkpoint, vocab_size=VOCAB_SIZE, n_positions=N_POSITIONS, n_embd=model_config["n_embd"], n_layer=model_config["n_layer"], n_head=model_config["n_head"], batch_size=actual_batch_size, num_workers=min(8, SHAPE["cpu"]), max_steps=max_steps, learning_rate=actual_learning_rate, weight_decay=0.1, warmup_steps=min(500, max_steps // 10), use_fsdp=use_fsdp, checkpoint_upload_steps=checkpoint_upload_steps, checkpoint_every_n_steps=model_config["checkpoint_every_n_steps"], report_every_n_steps=model_config["report_every_n_steps"], val_check_interval=model_config["val_check_interval"], grad_accumulation_steps=grad_accumulation_steps, ) return checkpoint_dir ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* The flow is straightforward: load the configuration, prepare the data, and run training. Flyte automatically manages the execution graph so data preparation runs first and training waits until it completes. If data preparation is cached from a previous run, training starts immediately. The gradient accumulation calculation balances two constraints. We want a global batch size of 256 (this affects training dynamics), but each GPU can only fit a small batch. With 8 GPUs and batch size 1 each, we need 32 accumulation steps to hit 256. ## Running the pipeline With everything defined, running is simple: ``` if __name__ == "__main__": flyte.init_from_config() if CLUSTER == "l4-test": # A short run that tests the multi-node setup on small GPUs. run = flyte.run( distributed_llm_pipeline, model_size="125M", dataset_name="Salesforce/wikitext", dataset_config="wikitext-103-raw-v1", max_length=512, max_train_samples=400_000, max_val_samples=5_000, max_steps=200, use_fsdp=True, checkpoint_upload_steps=100, ) else: run = flyte.run( distributed_llm_pipeline, model_size="30B", dataset_name="cerebras/SlimPajama-627B", dataset_config=None, max_length=2048, max_train_samples=5_000_000, max_val_samples=50_000, max_steps=15_000, use_fsdp=True, checkpoint_upload_steps=1000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining/train.py* The `h200` configuration is designed for testing and demonstration at real model sizes. Notice `max_train_samples=5_000_000`: that's 5 million samples from a dataset with 627 billion tokens. A tiny fraction, enough to verify everything works without burning through compute. For a real pretraining run, you would remove this limit by setting `max_train_samples=None`, or increase it significantly. You would also increase `max_steps` to match your compute budget, likely scale to multiple nodes by setting `nodes` to 4 or higher in the `h200` shape, and allocate more resources. The rest of the pipeline remains unchanged. ```bash flyte create config --endpoint --project --domain --builder remote uv run train.py ``` When you run this, Flyte: 1. **Builds the container** (cached after first run) 2. **Schedules data prep** on CPU nodes 3. **Waits for data prep** (or skips if cached) 4. **Provisions the training nodes** and starts them together, then launches torchrun on each one 5. **Streams logs and metrics** to the UI in real-time ### Test on small GPUs first Before you rent H200s, run the same code on the `l4-test` shape: ```bash PRETRAIN_CLUSTER=l4-test uv run train.py ``` This trains the 125M model on 2 nodes with one L4 GPU each, on 512-token sequences from WikiText-103, for 200 steps. The two nodes form one torchrun group, so it exercises the same multi-node path as a larger job: rendezvous across pods, FSDP sharding over the network, and checkpoint upload from rank 0. In our test run, data prep produced 51,315 training samples (26.3 million tokens) in about four minutes. The 200 training steps took 30 minutes and covered roughly one pass over the data. Validation loss fell from 7.51 to 6.27, which shows the model learning but is far from a useful language model. Open the Flyte UI to observe the workflow execution. The data preparation task completes first, followed by the training task spinning up. As training begins, the Flyte Reports dashboard starts plotting loss curves. If anything goes wrong, the logs are immediately available in the UI. ![Training Log](../../../_static/images/tutorials/distributed-llm-pretraining/logs.png) If training fails due to an out-of-memory error, a GPU driver error, or a hardware issue, check the logs, fix the problem, and restart the run with `resume_checkpoint` pointing to the most recent checkpoint. Training resumes from where it left off. Flyte tracks the full execution history, so it is easy to see exactly what happened. ## Going further If you've run through this tutorial, here's where to go next depending on what you're trying to do: **You want to train on your own data.** The data prep task accepts any HuggingFace dataset with a `text` column. If your data isn't on HuggingFace, you can modify `load_and_prepare_streaming_dataset` to read from S3, local files, or any other source. The key is getting your data into MDS format. Once it's there, the streaming and sharding just works. For production training, look at SlimPajama, [RedPajama](https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T), or [The Pile](https://huggingface.co/datasets/EleutherAI/pile) as starting points. **You want to scale to more GPUs.** Raise `nodes` in the cluster shape and Flyte handles the rest: the `ClusteredTaskEnvironment` starts that many pods together. The main thing to watch is the effective batch size. As you add more GPUs, you may want to reduce gradient accumulation steps to keep the same global batch size, or increase them if you want to experiment with larger batches. **Your training keeps failing.** Add `retries=3` to your task decorator for automatic retry on transient failures. This handles spot instance preemption, temporary network issues, and the occasional GPU that decides to stop working. Combined with checkpointing, you get fault-tolerant training that can survive most infrastructure hiccups. For persistent failures, the Flyte UI logs are your friend as they capture stdout/stderr from all ranks. **You want better visibility into what's happening.** We're actively working on surfacing GPU driver logs (xid/sxid errors), memory utilization breakdowns, and NCCL communication metrics directly in the Flyte UI. If you're hitting issues that the current logs don't explain, reach out. Your feedback helps us prioritize what observability features to build next! === PAGE: https://www.union.ai/docs/v2/union/tutorials/frontier-ai/pretraining-data-refinery === Turn raw web text into pretraining data with heuristic filters, global deduplication, eval decontamination, and a quality classifier distilled from LLM labels. # Refine a pretraining corpus > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/pretraining_data_refinery). Most of the work that goes into a language model happens before training starts, on the data. The data teams at LLM labs take raw web crawl, tens of billions of pages, and decide which of them the model will read. Public pipelines show the shape of this work. [FineWeb](https://arxiv.org/abs/2406.17557) extracts text from Common Crawl, filters it with heuristic rules, and removes near-duplicates. Its educational subset, FineWeb-Edu, then had Llama-3-70B-Instruct score about 450,000 pages for educational value, trained a small [classifier](https://huggingface.co/HuggingFaceFW/fineweb-edu-classifier) on those scores, and used the classifier to filter 15 trillion tokens down to 1.3 trillion. [Essential-Web](https://arxiv.org/abs/2506.14111) labels 24 trillion tokens with a taxonomy the same way, with a 0.5B model distilled from a 32B one. [Zyda-2](https://arxiv.org/abs/2411.06068) deduplicates across source datasets and filters by quality, and [OLMo 3](https://arxiv.org/abs/2512.13961) decontaminates its training data against its evaluation suite. The pattern is the same everywhere: cheap rules on every document, a global step that needs to see every shard at once, an expensive LLM on a small sample, and a cheap model that carries the LLM's judgment to the rest. At scale it is hard because each stage wants different hardware, a full pass is expensive, and the thresholds change: you want to rerun the last step without paying for the first ones again. This tutorial runs that pipeline, scaled down to 300,000 FineWeb documents: - heuristic filters, exact hashes, and MinHash signatures on a warm pool of CPU workers, one cached task per shard; - a global step that removes exact and near duplicates across shards, and documents that overlap the GSM8K, MMLU, or ARC test sets; - an open LLM, Qwen2.5-14B-Instruct under vLLM on a warm L40S, that scores 4,000 sampled documents on the FineWeb-Edu rubric; - a classifier distilled from those labels, trained and run on L4 GPUs, that scores every surviving document; - measurements of how well the classifier agrees with the LLM and with the public FineWeb-Edu classifier, and what each costs per document; - the curated corpus, published as an artifact with a dataset card, and a report. ## The pipeline ```mermaid flowchart LR S["N x refine_shard
warm CPU pool, cached"] --> G["global_dedup
exact, MinHash LSH, eval overlap"] G --> P["sample_for_labeling"] P --> L["K x label_chunk
vLLM on a warm L40S"] L --> T["train_classifier
frozen encoder + head, L4"] T --> C["N x score_shard
warm L4 pool"] G --> C C --> U["curate
threshold"] --> A["artifact:
edu-web-corpus"] classDef gpu fill:#3b82f633,stroke:#3b82f6,stroke-width:1.5px classDef cpu fill:#94a3b826,stroke:#94a3b8,stroke-width:1px class L,T,C gpu class S,G,P,U,A cpu ``` | Need | Construct | | --- | --- | | Filter hundreds of shards in parallel without a pod per shard | A reusable CPU environment, `flyte.ReusePolicy(replicas=(2, 8))`, and `asyncio.gather` over the shards | | Change a threshold without redoing the expensive stages | `cache="auto"` on every stage; the filter settings are a task input, and a version string salts the cache of the stages that use the labeler and classifier modules | | Keep an LLM loaded between labeling calls | A reusable GPU environment with one L40S replica that keeps the vLLM server running | | Run a small encoder on a cheaper GPU | A second GPU environment on L4s | | Pass shards between stages | `flyte.io.File` for Parquet shards, `flyte.io.DataFrame` for the result | | Publish the result with its provenance | `flyte.artifacts` with a dataset card | | See what each stage did | A report with the funnel, rejected examples, and the classifier's agreement | ## Getting started You need a Union cluster with L40S and L4 GPUs. The data and models are public, so no Hugging Face token is needed. ```bash git clone https://github.com/unionai/unionai-examples cd unionai-examples/v2/tutorials/pretraining_data_refinery python refinery.py # 15 shards of 20,000 documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold ``` ## Images and environments The CPU stages need Arrow, xxhash for stable token hashes, and SciPy for connected components. The GPU stages share one image with vLLM, which also brings PyTorch and Transformers for the classifier. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} CODE2 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/refinery.py* The stages hand each other small dataclasses. The documents themselves travel as Parquet files (`flyte.io.File`), so a dataclass carries only a reference, counts, and a few examples for the report: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/refinery.py* ## Heuristic filters, per shard The input is `HuggingFaceFW/fineweb`, `sample-10BT`, read straight from the Hugging Face Hub as Parquet row groups. Each shard is 20 row groups, about 20,000 documents, and the shards are spread over the sample's 14 files. The sample is drawn from every snapshot, so each shard mixes documents from several Common Crawl snapshots (8 in each 20,000-document slice checked for this tutorial). The filters are the document-level rules from Gopher, C4, and FineWeb, with their published thresholds. They are a dataclass, and the dataclass is an input of every shard task, so changing a threshold gives every shard a new cache key. The cache does not see edits to the code in `filters.py`, because `cache="auto"` hashes only the task's own source: when you change a rule, bump `FILTERS_VERSION`, which is a field of the dataclass. ``` """Document-level filters and signatures for web text: Gopher, C4 and FineWeb heuristics, MinHash, n-grams. Pure Python and NumPy, so the same code runs in a shard task, a notebook, or a test. Every function works on one document at a time; the shard task loops over its documents. words = tokens(text) # normalized word tokens reason = heuristic_reject(text, config) # None, or the name of the first rule that fired hashes = token_hashes(words) # one uint64 per token sig = minhash(hashes, config) # MinHash signature over word 5-grams keys = band_keys(sig, config) # LSH band keys for near-duplicate search grams = ngram_hashes(hashes, 13) # 13-gram hashes for decontamination The rules and their thresholds follow DataTrove's implementations of the Gopher quality and repetition filters, the document-level C4 rules, and FineWeb's own three extra rules. """ from __future__ import annotations import re from dataclasses import dataclass FILTERS_VERSION = "gopher-c4-fineweb/1" # {{docs-fragment config}} @dataclass class FilterConfig: """Every threshold the CPU stages use. It is an input of each shard task, so changing any value here gives new cache keys, and leaving it alone lets a rerun reuse every shard.""" # Gopher quality (Rae et al. 2021) min_words: int = 50 max_words: int = 100_000 min_avg_word_len: float = 3.0 max_avg_word_len: float = 10.0 max_symbol_word_ratio: float = 0.1 max_bullet_lines_ratio: float = 0.9 max_ellipsis_lines_ratio: float = 0.3 max_non_alpha_words_ratio: float = 0.8 min_stop_words: int = 2 # Gopher repetition max_dup_line_frac: float = 0.3 max_dup_para_frac: float = 0.3 max_dup_line_char_frac: float = 0.2 max_dup_para_char_frac: float = 0.2 # FineWeb's extra rules min_line_punct_ratio: float = 0.12 max_short_line_ratio: float = 0.67 max_newline_word_ratio: float = 0.3 # MinHash: 14 bands of 8 hashes over word 5-grams, as in FineWeb shingle: int = 5 bands: int = 14 rows: int = 8 seed: int = 1 # Decontamination contam_ngram: int = 13 version: str = FILTERS_VERSION # {{/docs-fragment config}} # Gopher's n-gram repetition limits: (n, max share of characters). TOP_NGRAM_MAX_FRAC = ((2, 0.20), (3, 0.18), (4, 0.16)) DUP_NGRAM_MAX_FRAC = ((5, 0.15), (6, 0.14), (7, 0.13), (8, 0.12), (9, 0.11), (10, 0.10)) STOP_WORDS = {"the", "be", "to", "of", "and", "that", "have", "with"} END_PUNCT = (".", "!", "?", '"', "'", "โ€", "โ€™", ":", ";", ")", "]") BULLETS = ("โ€ข", "โ—", "โ—‹", "โ– ", "โ–ก", "โ–ช", "โ–ซ", "*", "-", "โ€“", "โ€”") _WORD = re.compile(r"\w+", re.UNICODE) def tokens(text: str) -> list[str]: """Lowercased word tokens, the unit for n-grams, MinHash and decontamination.""" return _WORD.findall(text.lower()) def normalize(text: str) -> str: """The form used for exact duplicates: lowercase, whitespace collapsed.""" return " ".join(text.lower().split()) def exact_hash(text: str) -> int: """A 64-bit hash of the normalized text, for exact duplicates.""" import xxhash return xxhash.xxh3_64_intdigest(normalize(text).encode()) def _dup_frac(items: list[str]) -> tuple[float, float]: """Gopher: the share of elements, and of their characters, that repeat an earlier element.""" if not items: return 0.0, 0.0 seen: set[str] = set() dup, dup_chars = 0, 0 for it in items: if it in seen: dup += 1 dup_chars += len(it) seen.add(it) total_chars = sum(len(it) for it in items) or 1 return dup / len(items), dup_chars / total_chars # {{docs-fragment heuristics}} def heuristic_reject(text: str, c: FilterConfig, words: list[str], hashes) -> str | None: """Return the name of the first rule the document fails, or None if it passes them all. ``words`` and ``hashes`` are the document's tokens and their hashes.""" raw_words = text.split() n = len(raw_words) if n < c.min_words: return "gopher: too few words" if n > c.max_words: return "gopher: too many words" avg = sum(len(w) for w in raw_words) / n if not c.min_avg_word_len <= avg <= c.max_avg_word_len: return "gopher: mean word length" if (text.count("#") + text.count("...") + text.count("โ€ฆ")) / n > c.max_symbol_word_ratio: return "gopher: symbol-to-word ratio" lines = [ln.strip() for ln in text.split("\n")] nonempty = [ln for ln in lines if ln] if nonempty: if sum(ln.startswith(BULLETS) for ln in nonempty) / len(nonempty) > c.max_bullet_lines_ratio: return "gopher: bullet lines" if sum(ln.endswith(("...", "โ€ฆ")) for ln in nonempty) / len(nonempty) > c.max_ellipsis_lines_ratio: return "gopher: ellipsis lines" if sum(not any(ch.isalpha() for ch in w) for w in raw_words) / n > 1 - c.max_non_alpha_words_ratio: return "gopher: non-alphabetic words" if len(STOP_WORDS.intersection(words)) < c.min_stop_words: return "gopher: missing stop words" # C4: placeholder text and code low = text.lower() if "lorem ipsum" in low: return "c4: lorem ipsum" if "{" in text: return "c4: curly bracket" # Gopher repetition: whole lines and paragraphs, then n-grams paras = [p.strip() for p in re.split(r"\n{2,}", text) if p.strip()] line_frac, line_chars = _dup_frac(nonempty) para_frac, para_chars = _dup_frac(paras) if line_frac > c.max_dup_line_frac or para_frac > c.max_dup_para_frac: return "gopher: duplicate lines" if line_chars > c.max_dup_line_char_frac or para_chars > c.max_dup_para_char_frac: return "gopher: duplicate line characters" reason = _ngram_repetition(words, hashes) if reason: return reason # FineWeb's three rules if nonempty: if sum(ln.endswith(END_PUNCT) for ln in nonempty) / len(nonempty) < c.min_line_punct_ratio: return "fineweb: lines without end punctuation" if sum(len(ln) <= 30 for ln in nonempty) / len(nonempty) > c.max_short_line_ratio: return "fineweb: short lines" if text.count("\n") / n > c.max_newline_word_ratio: return "fineweb: newline-to-word ratio" return None # {{/docs-fragment heuristics}} def _ngram_repetition(words: list[str], h) -> str | None: """Gopher's n-gram rules, measured in characters of the words involved.""" import numpy as np lengths = np.fromiter((len(w) for w in words), dtype=np.int64, count=len(words)) total = int(lengths.sum()) or 1 for n, limit in TOP_NGRAM_MAX_FRAC: grams = ngram_hashes(h, n) if len(grams) == 0: continue _, first, counts = np.unique(grams, return_index=True, return_counts=True) top = counts.argmax() if counts[top] > 1 and lengths[first[top]:first[top] + n].sum() * counts[top] / total > limit: return f"gopher: top {n}-gram" for n, limit in DUP_NGRAM_MAX_FRAC: grams = ngram_hashes(h, n) if len(grams) == 0: continue repeat = np.ones(len(grams), dtype=np.int64) repeat[np.unique(grams, return_index=True)[1]] = 0 # first occurrences are not repeats covered = np.convolve(repeat, np.ones(n, dtype=np.int64))[: len(words)] > 0 if lengths[covered].sum() / total > limit: return f"gopher: duplicate {n}-grams" return None # โ”€โ”€ hashing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ _P = 0x100000001B3 # FNV prime, used as the base of the rolling n-gram hash def token_hashes(words: list[str]): """One stable 64-bit hash per token (Python's hash() is salted per process, so not that).""" import numpy as np import xxhash return np.fromiter((xxhash.xxh3_64_intdigest(w.encode()) for w in words), dtype=np.uint64, count=len(words)) def ngram_hashes(h, n: int): """A 64-bit hash for every contiguous n-gram of token hashes (polynomial, wrapping).""" import numpy as np if len(h) < n: return np.empty(0, dtype=np.uint64) m = len(h) - n + 1 out = np.zeros(m, dtype=np.uint64) with np.errstate(over="ignore"): for j in range(n): out = out * np.uint64(_P) + h[j:j + m] return out def _perms(c: FilterConfig): import numpy as np rng = np.random.default_rng(c.seed) k = c.bands * c.rows a = rng.integers(1, 2**63, size=k, dtype=np.uint64) | np.uint64(1) # odd multipliers b = rng.integers(0, 2**63, size=k, dtype=np.uint64) return a, b _PERM_CACHE: dict = {} # {{docs-fragment minhash}} def minhash(h, c: FilterConfig): """MinHash signature over word shingles: for each of bands*rows hash functions (multiply-shift: (a*x + b) >> 32), the minimum over the document's shingles.""" import numpy as np key = (c.seed, c.bands, c.rows) if key not in _PERM_CACHE: _PERM_CACHE[key] = _perms(c) a, b = _PERM_CACHE[key] shingles = np.unique(ngram_hashes(h, c.shingle)) with np.errstate(over="ignore"): return ((a[:, None] * shingles[None, :] + b[:, None]) >> np.uint64(32)).min(axis=1) def band_keys(sig, c: FilterConfig): """One 64-bit key per band of ``rows`` signature values. Two documents that share any band key are near-duplicate candidates. With 14 bands of 8, a pair with Jaccard similarity s becomes a candidate with probability 1 - (1 - s**8)**14: about 50% at s = 0.69, 77% at 0.75, 99% at 0.85, and about 5% at 0.5.""" import numpy as np rows = sig.reshape(c.bands, c.rows) key = np.arange(c.bands, dtype=np.uint64) # different bands never collide with np.errstate(over="ignore"): for j in range(c.rows): key = key * np.uint64(_P) + rows[:, j] return key # {{/docs-fragment minhash}} CODE3 """Document-level filters and signatures for web text: Gopher, C4 and FineWeb heuristics, MinHash, n-grams. Pure Python and NumPy, so the same code runs in a shard task, a notebook, or a test. Every function works on one document at a time; the shard task loops over its documents. words = tokens(text) # normalized word tokens reason = heuristic_reject(text, config) # None, or the name of the first rule that fired hashes = token_hashes(words) # one uint64 per token sig = minhash(hashes, config) # MinHash signature over word 5-grams keys = band_keys(sig, config) # LSH band keys for near-duplicate search grams = ngram_hashes(hashes, 13) # 13-gram hashes for decontamination The rules and their thresholds follow DataTrove's implementations of the Gopher quality and repetition filters, the document-level C4 rules, and FineWeb's own three extra rules. """ from __future__ import annotations import re from dataclasses import dataclass FILTERS_VERSION = "gopher-c4-fineweb/1" # {{docs-fragment config}} @dataclass class FilterConfig: """Every threshold the CPU stages use. It is an input of each shard task, so changing any value here gives new cache keys, and leaving it alone lets a rerun reuse every shard.""" # Gopher quality (Rae et al. 2021) min_words: int = 50 max_words: int = 100_000 min_avg_word_len: float = 3.0 max_avg_word_len: float = 10.0 max_symbol_word_ratio: float = 0.1 max_bullet_lines_ratio: float = 0.9 max_ellipsis_lines_ratio: float = 0.3 max_non_alpha_words_ratio: float = 0.8 min_stop_words: int = 2 # Gopher repetition max_dup_line_frac: float = 0.3 max_dup_para_frac: float = 0.3 max_dup_line_char_frac: float = 0.2 max_dup_para_char_frac: float = 0.2 # FineWeb's extra rules min_line_punct_ratio: float = 0.12 max_short_line_ratio: float = 0.67 max_newline_word_ratio: float = 0.3 # MinHash: 14 bands of 8 hashes over word 5-grams, as in FineWeb shingle: int = 5 bands: int = 14 rows: int = 8 seed: int = 1 # Decontamination contam_ngram: int = 13 version: str = FILTERS_VERSION # {{/docs-fragment config}} # Gopher's n-gram repetition limits: (n, max share of characters). TOP_NGRAM_MAX_FRAC = ((2, 0.20), (3, 0.18), (4, 0.16)) DUP_NGRAM_MAX_FRAC = ((5, 0.15), (6, 0.14), (7, 0.13), (8, 0.12), (9, 0.11), (10, 0.10)) STOP_WORDS = {"the", "be", "to", "of", "and", "that", "have", "with"} END_PUNCT = (".", "!", "?", '"', "'", "โ€", "โ€™", ":", ";", ")", "]") BULLETS = ("โ€ข", "โ—", "โ—‹", "โ– ", "โ–ก", "โ–ช", "โ–ซ", "*", "-", "โ€“", "โ€”") _WORD = re.compile(r"\w+", re.UNICODE) def tokens(text: str) -> list[str]: """Lowercased word tokens, the unit for n-grams, MinHash and decontamination.""" return _WORD.findall(text.lower()) def normalize(text: str) -> str: """The form used for exact duplicates: lowercase, whitespace collapsed.""" return " ".join(text.lower().split()) def exact_hash(text: str) -> int: """A 64-bit hash of the normalized text, for exact duplicates.""" import xxhash return xxhash.xxh3_64_intdigest(normalize(text).encode()) def _dup_frac(items: list[str]) -> tuple[float, float]: """Gopher: the share of elements, and of their characters, that repeat an earlier element.""" if not items: return 0.0, 0.0 seen: set[str] = set() dup, dup_chars = 0, 0 for it in items: if it in seen: dup += 1 dup_chars += len(it) seen.add(it) total_chars = sum(len(it) for it in items) or 1 return dup / len(items), dup_chars / total_chars # {{docs-fragment heuristics}} def heuristic_reject(text: str, c: FilterConfig, words: list[str], hashes) -> str | None: """Return the name of the first rule the document fails, or None if it passes them all. ``words`` and ``hashes`` are the document's tokens and their hashes.""" raw_words = text.split() n = len(raw_words) if n < c.min_words: return "gopher: too few words" if n > c.max_words: return "gopher: too many words" avg = sum(len(w) for w in raw_words) / n if not c.min_avg_word_len <= avg <= c.max_avg_word_len: return "gopher: mean word length" if (text.count("#") + text.count("...") + text.count("โ€ฆ")) / n > c.max_symbol_word_ratio: return "gopher: symbol-to-word ratio" lines = [ln.strip() for ln in text.split("\n")] nonempty = [ln for ln in lines if ln] if nonempty: if sum(ln.startswith(BULLETS) for ln in nonempty) / len(nonempty) > c.max_bullet_lines_ratio: return "gopher: bullet lines" if sum(ln.endswith(("...", "โ€ฆ")) for ln in nonempty) / len(nonempty) > c.max_ellipsis_lines_ratio: return "gopher: ellipsis lines" if sum(not any(ch.isalpha() for ch in w) for w in raw_words) / n > 1 - c.max_non_alpha_words_ratio: return "gopher: non-alphabetic words" if len(STOP_WORDS.intersection(words)) < c.min_stop_words: return "gopher: missing stop words" # C4: placeholder text and code low = text.lower() if "lorem ipsum" in low: return "c4: lorem ipsum" if "{" in text: return "c4: curly bracket" # Gopher repetition: whole lines and paragraphs, then n-grams paras = [p.strip() for p in re.split(r"\n{2,}", text) if p.strip()] line_frac, line_chars = _dup_frac(nonempty) para_frac, para_chars = _dup_frac(paras) if line_frac > c.max_dup_line_frac or para_frac > c.max_dup_para_frac: return "gopher: duplicate lines" if line_chars > c.max_dup_line_char_frac or para_chars > c.max_dup_para_char_frac: return "gopher: duplicate line characters" reason = _ngram_repetition(words, hashes) if reason: return reason # FineWeb's three rules if nonempty: if sum(ln.endswith(END_PUNCT) for ln in nonempty) / len(nonempty) < c.min_line_punct_ratio: return "fineweb: lines without end punctuation" if sum(len(ln) <= 30 for ln in nonempty) / len(nonempty) > c.max_short_line_ratio: return "fineweb: short lines" if text.count("\n") / n > c.max_newline_word_ratio: return "fineweb: newline-to-word ratio" return None # {{/docs-fragment heuristics}} def _ngram_repetition(words: list[str], h) -> str | None: """Gopher's n-gram rules, measured in characters of the words involved.""" import numpy as np lengths = np.fromiter((len(w) for w in words), dtype=np.int64, count=len(words)) total = int(lengths.sum()) or 1 for n, limit in TOP_NGRAM_MAX_FRAC: grams = ngram_hashes(h, n) if len(grams) == 0: continue _, first, counts = np.unique(grams, return_index=True, return_counts=True) top = counts.argmax() if counts[top] > 1 and lengths[first[top]:first[top] + n].sum() * counts[top] / total > limit: return f"gopher: top {n}-gram" for n, limit in DUP_NGRAM_MAX_FRAC: grams = ngram_hashes(h, n) if len(grams) == 0: continue repeat = np.ones(len(grams), dtype=np.int64) repeat[np.unique(grams, return_index=True)[1]] = 0 # first occurrences are not repeats covered = np.convolve(repeat, np.ones(n, dtype=np.int64))[: len(words)] > 0 if lengths[covered].sum() / total > limit: return f"gopher: duplicate {n}-grams" return None # โ”€โ”€ hashing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ _P = 0x100000001B3 # FNV prime, used as the base of the rolling n-gram hash def token_hashes(words: list[str]): """One stable 64-bit hash per token (Python's hash() is salted per process, so not that).""" import numpy as np import xxhash return np.fromiter((xxhash.xxh3_64_intdigest(w.encode()) for w in words), dtype=np.uint64, count=len(words)) def ngram_hashes(h, n: int): """A 64-bit hash for every contiguous n-gram of token hashes (polynomial, wrapping).""" import numpy as np if len(h) < n: return np.empty(0, dtype=np.uint64) m = len(h) - n + 1 out = np.zeros(m, dtype=np.uint64) with np.errstate(over="ignore"): for j in range(n): out = out * np.uint64(_P) + h[j:j + m] return out def _perms(c: FilterConfig): import numpy as np rng = np.random.default_rng(c.seed) k = c.bands * c.rows a = rng.integers(1, 2**63, size=k, dtype=np.uint64) | np.uint64(1) # odd multipliers b = rng.integers(0, 2**63, size=k, dtype=np.uint64) return a, b _PERM_CACHE: dict = {} # {{docs-fragment minhash}} def minhash(h, c: FilterConfig): """MinHash signature over word shingles: for each of bands*rows hash functions (multiply-shift: (a*x + b) >> 32), the minimum over the document's shingles.""" import numpy as np key = (c.seed, c.bands, c.rows) if key not in _PERM_CACHE: _PERM_CACHE[key] = _perms(c) a, b = _PERM_CACHE[key] shingles = np.unique(ngram_hashes(h, c.shingle)) with np.errstate(over="ignore"): return ((a[:, None] * shingles[None, :] + b[:, None]) >> np.uint64(32)).min(axis=1) def band_keys(sig, c: FilterConfig): """One 64-bit key per band of ``rows`` signature values. Two documents that share any band key are near-duplicate candidates. With 14 bands of 8, a pair with Jaccard similarity s becomes a candidate with probability 1 - (1 - s**8)**14: about 50% at s = 0.69, 77% at 0.75, 99% at 0.85, and about 5% at 0.5.""" import numpy as np rows = sig.reshape(c.bands, c.rows) key = np.arange(c.bands, dtype=np.uint64) # different bands never collide with np.errstate(over="ignore"): for j in range(c.rows): key = key * np.uint64(_P) + rows[:, j] return key # {{/docs-fragment minhash}} CODE4 """Document-level filters and signatures for web text: Gopher, C4 and FineWeb heuristics, MinHash, n-grams. Pure Python and NumPy, so the same code runs in a shard task, a notebook, or a test. Every function works on one document at a time; the shard task loops over its documents. words = tokens(text) # normalized word tokens reason = heuristic_reject(text, config) # None, or the name of the first rule that fired hashes = token_hashes(words) # one uint64 per token sig = minhash(hashes, config) # MinHash signature over word 5-grams keys = band_keys(sig, config) # LSH band keys for near-duplicate search grams = ngram_hashes(hashes, 13) # 13-gram hashes for decontamination The rules and their thresholds follow DataTrove's implementations of the Gopher quality and repetition filters, the document-level C4 rules, and FineWeb's own three extra rules. """ from __future__ import annotations import re from dataclasses import dataclass FILTERS_VERSION = "gopher-c4-fineweb/1" # {{docs-fragment config}} @dataclass class FilterConfig: """Every threshold the CPU stages use. It is an input of each shard task, so changing any value here gives new cache keys, and leaving it alone lets a rerun reuse every shard.""" # Gopher quality (Rae et al. 2021) min_words: int = 50 max_words: int = 100_000 min_avg_word_len: float = 3.0 max_avg_word_len: float = 10.0 max_symbol_word_ratio: float = 0.1 max_bullet_lines_ratio: float = 0.9 max_ellipsis_lines_ratio: float = 0.3 max_non_alpha_words_ratio: float = 0.8 min_stop_words: int = 2 # Gopher repetition max_dup_line_frac: float = 0.3 max_dup_para_frac: float = 0.3 max_dup_line_char_frac: float = 0.2 max_dup_para_char_frac: float = 0.2 # FineWeb's extra rules min_line_punct_ratio: float = 0.12 max_short_line_ratio: float = 0.67 max_newline_word_ratio: float = 0.3 # MinHash: 14 bands of 8 hashes over word 5-grams, as in FineWeb shingle: int = 5 bands: int = 14 rows: int = 8 seed: int = 1 # Decontamination contam_ngram: int = 13 version: str = FILTERS_VERSION # {{/docs-fragment config}} # Gopher's n-gram repetition limits: (n, max share of characters). TOP_NGRAM_MAX_FRAC = ((2, 0.20), (3, 0.18), (4, 0.16)) DUP_NGRAM_MAX_FRAC = ((5, 0.15), (6, 0.14), (7, 0.13), (8, 0.12), (9, 0.11), (10, 0.10)) STOP_WORDS = {"the", "be", "to", "of", "and", "that", "have", "with"} END_PUNCT = (".", "!", "?", '"', "'", "โ€", "โ€™", ":", ";", ")", "]") BULLETS = ("โ€ข", "โ—", "โ—‹", "โ– ", "โ–ก", "โ–ช", "โ–ซ", "*", "-", "โ€“", "โ€”") _WORD = re.compile(r"\w+", re.UNICODE) def tokens(text: str) -> list[str]: """Lowercased word tokens, the unit for n-grams, MinHash and decontamination.""" return _WORD.findall(text.lower()) def normalize(text: str) -> str: """The form used for exact duplicates: lowercase, whitespace collapsed.""" return " ".join(text.lower().split()) def exact_hash(text: str) -> int: """A 64-bit hash of the normalized text, for exact duplicates.""" import xxhash return xxhash.xxh3_64_intdigest(normalize(text).encode()) def _dup_frac(items: list[str]) -> tuple[float, float]: """Gopher: the share of elements, and of their characters, that repeat an earlier element.""" if not items: return 0.0, 0.0 seen: set[str] = set() dup, dup_chars = 0, 0 for it in items: if it in seen: dup += 1 dup_chars += len(it) seen.add(it) total_chars = sum(len(it) for it in items) or 1 return dup / len(items), dup_chars / total_chars # {{docs-fragment heuristics}} def heuristic_reject(text: str, c: FilterConfig, words: list[str], hashes) -> str | None: """Return the name of the first rule the document fails, or None if it passes them all. ``words`` and ``hashes`` are the document's tokens and their hashes.""" raw_words = text.split() n = len(raw_words) if n < c.min_words: return "gopher: too few words" if n > c.max_words: return "gopher: too many words" avg = sum(len(w) for w in raw_words) / n if not c.min_avg_word_len <= avg <= c.max_avg_word_len: return "gopher: mean word length" if (text.count("#") + text.count("...") + text.count("โ€ฆ")) / n > c.max_symbol_word_ratio: return "gopher: symbol-to-word ratio" lines = [ln.strip() for ln in text.split("\n")] nonempty = [ln for ln in lines if ln] if nonempty: if sum(ln.startswith(BULLETS) for ln in nonempty) / len(nonempty) > c.max_bullet_lines_ratio: return "gopher: bullet lines" if sum(ln.endswith(("...", "โ€ฆ")) for ln in nonempty) / len(nonempty) > c.max_ellipsis_lines_ratio: return "gopher: ellipsis lines" if sum(not any(ch.isalpha() for ch in w) for w in raw_words) / n > 1 - c.max_non_alpha_words_ratio: return "gopher: non-alphabetic words" if len(STOP_WORDS.intersection(words)) < c.min_stop_words: return "gopher: missing stop words" # C4: placeholder text and code low = text.lower() if "lorem ipsum" in low: return "c4: lorem ipsum" if "{" in text: return "c4: curly bracket" # Gopher repetition: whole lines and paragraphs, then n-grams paras = [p.strip() for p in re.split(r"\n{2,}", text) if p.strip()] line_frac, line_chars = _dup_frac(nonempty) para_frac, para_chars = _dup_frac(paras) if line_frac > c.max_dup_line_frac or para_frac > c.max_dup_para_frac: return "gopher: duplicate lines" if line_chars > c.max_dup_line_char_frac or para_chars > c.max_dup_para_char_frac: return "gopher: duplicate line characters" reason = _ngram_repetition(words, hashes) if reason: return reason # FineWeb's three rules if nonempty: if sum(ln.endswith(END_PUNCT) for ln in nonempty) / len(nonempty) < c.min_line_punct_ratio: return "fineweb: lines without end punctuation" if sum(len(ln) <= 30 for ln in nonempty) / len(nonempty) > c.max_short_line_ratio: return "fineweb: short lines" if text.count("\n") / n > c.max_newline_word_ratio: return "fineweb: newline-to-word ratio" return None # {{/docs-fragment heuristics}} def _ngram_repetition(words: list[str], h) -> str | None: """Gopher's n-gram rules, measured in characters of the words involved.""" import numpy as np lengths = np.fromiter((len(w) for w in words), dtype=np.int64, count=len(words)) total = int(lengths.sum()) or 1 for n, limit in TOP_NGRAM_MAX_FRAC: grams = ngram_hashes(h, n) if len(grams) == 0: continue _, first, counts = np.unique(grams, return_index=True, return_counts=True) top = counts.argmax() if counts[top] > 1 and lengths[first[top]:first[top] + n].sum() * counts[top] / total > limit: return f"gopher: top {n}-gram" for n, limit in DUP_NGRAM_MAX_FRAC: grams = ngram_hashes(h, n) if len(grams) == 0: continue repeat = np.ones(len(grams), dtype=np.int64) repeat[np.unique(grams, return_index=True)[1]] = 0 # first occurrences are not repeats covered = np.convolve(repeat, np.ones(n, dtype=np.int64))[: len(words)] > 0 if lengths[covered].sum() / total > limit: return f"gopher: duplicate {n}-grams" return None # โ”€โ”€ hashing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ _P = 0x100000001B3 # FNV prime, used as the base of the rolling n-gram hash def token_hashes(words: list[str]): """One stable 64-bit hash per token (Python's hash() is salted per process, so not that).""" import numpy as np import xxhash return np.fromiter((xxhash.xxh3_64_intdigest(w.encode()) for w in words), dtype=np.uint64, count=len(words)) def ngram_hashes(h, n: int): """A 64-bit hash for every contiguous n-gram of token hashes (polynomial, wrapping).""" import numpy as np if len(h) < n: return np.empty(0, dtype=np.uint64) m = len(h) - n + 1 out = np.zeros(m, dtype=np.uint64) with np.errstate(over="ignore"): for j in range(n): out = out * np.uint64(_P) + h[j:j + m] return out def _perms(c: FilterConfig): import numpy as np rng = np.random.default_rng(c.seed) k = c.bands * c.rows a = rng.integers(1, 2**63, size=k, dtype=np.uint64) | np.uint64(1) # odd multipliers b = rng.integers(0, 2**63, size=k, dtype=np.uint64) return a, b _PERM_CACHE: dict = {} # {{docs-fragment minhash}} def minhash(h, c: FilterConfig): """MinHash signature over word shingles: for each of bands*rows hash functions (multiply-shift: (a*x + b) >> 32), the minimum over the document's shingles.""" import numpy as np key = (c.seed, c.bands, c.rows) if key not in _PERM_CACHE: _PERM_CACHE[key] = _perms(c) a, b = _PERM_CACHE[key] shingles = np.unique(ngram_hashes(h, c.shingle)) with np.errstate(over="ignore"): return ((a[:, None] * shingles[None, :] + b[:, None]) >> np.uint64(32)).min(axis=1) def band_keys(sig, c: FilterConfig): """One 64-bit key per band of ``rows`` signature values. Two documents that share any band key are near-duplicate candidates. With 14 bands of 8, a pair with Jaccard similarity s becomes a candidate with probability 1 - (1 - s**8)**14: about 50% at s = 0.69, 77% at 0.75, 99% at 0.85, and about 5% at 0.5.""" import numpy as np rows = sig.reshape(c.bands, c.rows) key = np.arange(c.bands, dtype=np.uint64) # different bands never collide with np.errstate(over="ignore"): for j in range(c.rows): key = key * np.uint64(_P) + rows[:, j] return key # {{/docs-fragment minhash}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/filters.py* The shard task also checks every document against the eval sets. `build_eval_ngrams` hashes every 13-gram of every GSM8K, MMLU, and ARC test question followed by its answer options, the same way the shard task hashes documents. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} CODE5 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/refinery.py* The task is cached on its inputs: the shard's location, the filter settings, and the eval n-grams. A rerun with the same settings skips it. ## Global deduplication and decontamination Deduplication has to see every shard at once. `global_dedup` reads only the hash columns, drops exact duplicates, and then treats two documents as near duplicates when they share any band key. Candidate pairs become edges of a graph, each connected component is one cluster, and each cluster keeps its first document. Documents that survive both and overlap an eval set are removed last. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/refinery.py* ## Labeling with an LLM The labeler uses the prompt FineWeb-Edu used with Llama-3-70B-Instruct: an additive 0-5 rubric for educational value at primary and grade school level, a short justification, and a final `Educational score: N`. CODE6 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/labeler.py* vLLM runs as an OpenAI-compatible server inside the reusable container. The first call on the replica starts it; a later call with the same model finds it running. CODE7 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/labeler.py* CODE8 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/labeler.py* The driver splits the 4,000-document sample into four chunks and labels them one after another. Each chunk is a cached task, so a rerun never pays for labels it already has, and a failure costs at most the chunk in flight: a retry relabels that one chunk, not the sample. `cache="auto"` hashes the task's own source, not the modules it calls, so the task salts its cache with `labeler.VERSION`: change the prompt, bump the version, and the labels are recomputed. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/refinery.py* ## Distilling the labels into a classifier The classifier follows the FineWeb-Edu classifier's recipe: the [`snowflake-arctic-embed-m`](https://huggingface.co/Snowflake/snowflake-arctic-embed-m) encoder stays frozen, and only a small head on its `[CLS]` vector learns to predict the LLM's score. Because the encoder is frozen, each document is encoded once and the head trains in seconds. Web text is mostly scores 0 to 2, so the loss weights each document by the inverse frequency of its score; without that, the head learns to predict "about 1" for everything. ``` """The distilled quality classifier: a frozen text encoder and a small regression head. This is the FineWeb-Edu classifier's recipe at a smaller scale: Snowflake's arctic-embed-m encoder stays frozen, and only a head on its [CLS] vector (a dense layer, tanh, and one linear output, the same shape as BERT's pooler plus a regression layer) learns to predict the LLM's 0-5 score. Because the encoder is frozen, each document is encoded once and the head trains in seconds. """ from __future__ import annotations import time # Bump when the encoder, the head, or its training changes. Tasks that use this module salt # their cache with it, because cache="auto" hashes only a task's own source. VERSION = "arctic-embed-m/balanced-head/2" ENCODER = "Snowflake/snowflake-arctic-embed-m" PUBLIC_CLASSIFIER = "HuggingFaceFW/fineweb-edu-classifier" MAX_TOKENS = 512 _models: dict = {} def _load(name: str, head: bool = False): """Load a tokenizer and model onto the GPU once per container.""" if name not in _models: import torch from transformers import AutoModel, AutoModelForSequenceClassification, AutoTokenizer cls = AutoModelForSequenceClassification if head else AutoModel started = time.monotonic() tok = AutoTokenizer.from_pretrained(name) model = cls.from_pretrained(name, dtype=torch.float16).cuda().eval() _models[name] = (tok, model, time.monotonic() - started) return _models[name] # {{docs-fragment encode}} def _batches(tok, texts: list[str], batch_size: int): """Tokenize, then batch documents of similar length together so padding stays small.""" enc = tok(texts, truncation=True, max_length=MAX_TOKENS) order = sorted(range(len(texts)), key=lambda i: len(enc["input_ids"][i])) for s in range(0, len(order), batch_size): idx = order[s:s + batch_size] yield idx, tok.pad({"input_ids": [enc["input_ids"][i] for i in idx], "attention_mask": [enc["attention_mask"][i] for i in idx]}, return_tensors="pt") def embed(texts: list[str], batch_size: int = 128): """The encoder's last-layer [CLS] vector for every text, in input order (float32, N x 768).""" import numpy as np import torch tok, model, _ = _load(ENCODER) out = np.zeros((len(texts), model.config.hidden_size), dtype=np.float32) with torch.inference_mode(): for idx, batch in _batches(tok, texts, batch_size): hidden = model(**{k: v.cuda() for k, v in batch.items()}).last_hidden_state[:, 0] out[idx] = hidden.float().cpu().numpy() return out # {{/docs-fragment encode}} def public_scores(texts: list[str], batch_size: int = 128): """Scores from the public FineWeb-Edu classifier, distilled from Llama-3-70B labels.""" import numpy as np import torch tok, model, _ = _load(PUBLIC_CLASSIFIER, head=True) out = np.zeros(len(texts), dtype=np.float32) with torch.inference_mode(): for idx, batch in _batches(tok, texts, batch_size): out[idx] = model(**{k: v.cuda() for k, v in batch.items()}).logits.squeeze(-1).float().cpu().numpy() return out def warm_up(name: str = ENCODER) -> float: """Load a model if this container has not yet. Returns the seconds this call spent loading.""" if name in _models: return 0.0 return _load(name, head=name == PUBLIC_CLASSIFIER)[2] # {{docs-fragment head}} def make_head(dim: int = 768): from torch import nn return nn.Sequential(nn.Linear(dim, dim), nn.Tanh(), nn.Linear(dim, 1)) def train_head(x, y, epochs: int = 100, lr: float = 3e-4, batch_size: int = 256, seed: int = 0): """Fit the head to the LLM scores with a class-balanced MSE. Web text is mostly scores 0-2, so a plain MSE learns to predict "about 1" for everything and never reaches the threshold. Weighting each document by the inverse frequency of its score (capped at 20x) makes the rare high scores count. 10% of the rows pick the best epoch.""" import numpy as np import torch torch.manual_seed(seed) rng = np.random.default_rng(seed) counts = np.bincount(np.rint(y).astype(int), minlength=6).astype(float) weight = np.minimum(counts.max() / np.maximum(counts, 1), 20.0)[np.rint(y).astype(int)] perm = rng.permutation(len(x)) n_val = max(len(x) // 10, 1) val, tr = perm[:n_val], perm[n_val:] def t(a, idx): return torch.tensor(a[idx], dtype=torch.float32).cuda() xt, yt, wt = t(x, tr), t(y, tr), t(weight, tr) xv, yv, wv = t(x, val), t(y, val), t(weight, val) head = make_head(x.shape[1]).cuda() opt = torch.optim.AdamW(head.parameters(), lr=lr, weight_decay=0.05) best, best_state, curve = float("inf"), None, [] for epoch in range(epochs): head.train() for s in torch.randperm(len(xt)).split(batch_size): loss = (wt[s] * (head(xt[s]).squeeze(-1) - yt[s]) ** 2).sum() / wt[s].sum() opt.zero_grad() loss.backward() opt.step() head.eval() with torch.no_grad(): v = ((wv * (head(xv).squeeze(-1) - yv) ** 2).sum() / wv.sum()).item() curve.append(v) if v < best: best, best_state = v, {k: t.detach().clone() for k, t in head.state_dict().items()} head.load_state_dict(best_state) return head.cpu(), curve # {{/docs-fragment head}} def predict(head, x): import torch head = head.cuda().eval() with torch.no_grad(): return head(torch.tensor(x).cuda()).squeeze(-1).float().cpu().numpy() # {{docs-fragment agreement}} def agreement(reference, predicted, threshold: float = 3.0) -> dict: """How well ``predicted`` scores track ``reference`` scores (both 0-5, either may be float).""" import numpy as np ref = np.asarray(reference, dtype=np.float64) pred = np.asarray(predicted, dtype=np.float64) def ranks(v): order = np.argsort(v, kind="stable") r = np.empty(len(v)) r[order] = np.arange(len(v)) for val in np.unique(v): # average ranks over ties (scores are mostly integers) tie = v == val r[tie] = r[tie].mean() return r ri, pi = np.clip(np.rint(ref), 0, 5).astype(int), np.clip(np.rint(pred), 0, 5).astype(int) tp = int(((ref >= threshold) & (pred >= threshold)).sum()) fp = int(((ref < threshold) & (pred >= threshold)).sum()) fn = int(((ref >= threshold) & (pred < threshold)).sum()) precision = tp / (tp + fp) if tp + fp else 0.0 recall = tp / (tp + fn) if tp + fn else 0.0 confusion = np.zeros((6, 6), dtype=int) np.add.at(confusion, (ri, pi), 1) return { "n": int(len(ref)), "spearman": float(np.corrcoef(ranks(ref), ranks(pred))[0, 1]), "pearson": float(np.corrcoef(ref, pred)[0, 1]), "mae": float(np.abs(ref - pred).mean()), "exact": float((ri == pi).mean()), "within_one": float((np.abs(ri - pi) <= 1).mean()), "precision": precision, "recall": recall, "f1": 2 * precision * recall / (precision + recall) if precision + recall else 0.0, "confusion": confusion.tolist(), # rows: reference score, columns: predicted score } # {{/docs-fragment agreement}} CODE9 """The distilled quality classifier: a frozen text encoder and a small regression head. This is the FineWeb-Edu classifier's recipe at a smaller scale: Snowflake's arctic-embed-m encoder stays frozen, and only a head on its [CLS] vector (a dense layer, tanh, and one linear output, the same shape as BERT's pooler plus a regression layer) learns to predict the LLM's 0-5 score. Because the encoder is frozen, each document is encoded once and the head trains in seconds. """ from __future__ import annotations import time # Bump when the encoder, the head, or its training changes. Tasks that use this module salt # their cache with it, because cache="auto" hashes only a task's own source. VERSION = "arctic-embed-m/balanced-head/2" ENCODER = "Snowflake/snowflake-arctic-embed-m" PUBLIC_CLASSIFIER = "HuggingFaceFW/fineweb-edu-classifier" MAX_TOKENS = 512 _models: dict = {} def _load(name: str, head: bool = False): """Load a tokenizer and model onto the GPU once per container.""" if name not in _models: import torch from transformers import AutoModel, AutoModelForSequenceClassification, AutoTokenizer cls = AutoModelForSequenceClassification if head else AutoModel started = time.monotonic() tok = AutoTokenizer.from_pretrained(name) model = cls.from_pretrained(name, dtype=torch.float16).cuda().eval() _models[name] = (tok, model, time.monotonic() - started) return _models[name] # {{docs-fragment encode}} def _batches(tok, texts: list[str], batch_size: int): """Tokenize, then batch documents of similar length together so padding stays small.""" enc = tok(texts, truncation=True, max_length=MAX_TOKENS) order = sorted(range(len(texts)), key=lambda i: len(enc["input_ids"][i])) for s in range(0, len(order), batch_size): idx = order[s:s + batch_size] yield idx, tok.pad({"input_ids": [enc["input_ids"][i] for i in idx], "attention_mask": [enc["attention_mask"][i] for i in idx]}, return_tensors="pt") def embed(texts: list[str], batch_size: int = 128): """The encoder's last-layer [CLS] vector for every text, in input order (float32, N x 768).""" import numpy as np import torch tok, model, _ = _load(ENCODER) out = np.zeros((len(texts), model.config.hidden_size), dtype=np.float32) with torch.inference_mode(): for idx, batch in _batches(tok, texts, batch_size): hidden = model(**{k: v.cuda() for k, v in batch.items()}).last_hidden_state[:, 0] out[idx] = hidden.float().cpu().numpy() return out # {{/docs-fragment encode}} def public_scores(texts: list[str], batch_size: int = 128): """Scores from the public FineWeb-Edu classifier, distilled from Llama-3-70B labels.""" import numpy as np import torch tok, model, _ = _load(PUBLIC_CLASSIFIER, head=True) out = np.zeros(len(texts), dtype=np.float32) with torch.inference_mode(): for idx, batch in _batches(tok, texts, batch_size): out[idx] = model(**{k: v.cuda() for k, v in batch.items()}).logits.squeeze(-1).float().cpu().numpy() return out def warm_up(name: str = ENCODER) -> float: """Load a model if this container has not yet. Returns the seconds this call spent loading.""" if name in _models: return 0.0 return _load(name, head=name == PUBLIC_CLASSIFIER)[2] # {{docs-fragment head}} def make_head(dim: int = 768): from torch import nn return nn.Sequential(nn.Linear(dim, dim), nn.Tanh(), nn.Linear(dim, 1)) def train_head(x, y, epochs: int = 100, lr: float = 3e-4, batch_size: int = 256, seed: int = 0): """Fit the head to the LLM scores with a class-balanced MSE. Web text is mostly scores 0-2, so a plain MSE learns to predict "about 1" for everything and never reaches the threshold. Weighting each document by the inverse frequency of its score (capped at 20x) makes the rare high scores count. 10% of the rows pick the best epoch.""" import numpy as np import torch torch.manual_seed(seed) rng = np.random.default_rng(seed) counts = np.bincount(np.rint(y).astype(int), minlength=6).astype(float) weight = np.minimum(counts.max() / np.maximum(counts, 1), 20.0)[np.rint(y).astype(int)] perm = rng.permutation(len(x)) n_val = max(len(x) // 10, 1) val, tr = perm[:n_val], perm[n_val:] def t(a, idx): return torch.tensor(a[idx], dtype=torch.float32).cuda() xt, yt, wt = t(x, tr), t(y, tr), t(weight, tr) xv, yv, wv = t(x, val), t(y, val), t(weight, val) head = make_head(x.shape[1]).cuda() opt = torch.optim.AdamW(head.parameters(), lr=lr, weight_decay=0.05) best, best_state, curve = float("inf"), None, [] for epoch in range(epochs): head.train() for s in torch.randperm(len(xt)).split(batch_size): loss = (wt[s] * (head(xt[s]).squeeze(-1) - yt[s]) ** 2).sum() / wt[s].sum() opt.zero_grad() loss.backward() opt.step() head.eval() with torch.no_grad(): v = ((wv * (head(xv).squeeze(-1) - yv) ** 2).sum() / wv.sum()).item() curve.append(v) if v < best: best, best_state = v, {k: t.detach().clone() for k, t in head.state_dict().items()} head.load_state_dict(best_state) return head.cpu(), curve # {{/docs-fragment head}} def predict(head, x): import torch head = head.cuda().eval() with torch.no_grad(): return head(torch.tensor(x).cuda()).squeeze(-1).float().cpu().numpy() # {{docs-fragment agreement}} def agreement(reference, predicted, threshold: float = 3.0) -> dict: """How well ``predicted`` scores track ``reference`` scores (both 0-5, either may be float).""" import numpy as np ref = np.asarray(reference, dtype=np.float64) pred = np.asarray(predicted, dtype=np.float64) def ranks(v): order = np.argsort(v, kind="stable") r = np.empty(len(v)) r[order] = np.arange(len(v)) for val in np.unique(v): # average ranks over ties (scores are mostly integers) tie = v == val r[tie] = r[tie].mean() return r ri, pi = np.clip(np.rint(ref), 0, 5).astype(int), np.clip(np.rint(pred), 0, 5).astype(int) tp = int(((ref >= threshold) & (pred >= threshold)).sum()) fp = int(((ref < threshold) & (pred >= threshold)).sum()) fn = int(((ref >= threshold) & (pred < threshold)).sum()) precision = tp / (tp + fp) if tp + fp else 0.0 recall = tp / (tp + fn) if tp + fn else 0.0 confusion = np.zeros((6, 6), dtype=int) np.add.at(confusion, (ri, pi), 1) return { "n": int(len(ref)), "spearman": float(np.corrcoef(ranks(ref), ranks(pred))[0, 1]), "pearson": float(np.corrcoef(ref, pred)[0, 1]), "mae": float(np.abs(ref - pred).mean()), "exact": float((ri == pi).mean()), "within_one": float((np.abs(ri - pi) <= 1).mean()), "precision": precision, "recall": recall, "f1": 2 * precision * recall / (precision + recall) if precision + recall else 0.0, "confusion": confusion.tolist(), # rows: reference score, columns: predicted score } # {{/docs-fragment agreement}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/classifier.py* `train_classifier` holds out 20% of the labeled documents by a hash of their ID, trains the head on the rest, and scores the held-out documents with both the new classifier and the public FineWeb-Edu classifier, so the report can compare all three. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} CODE10 """The distilled quality classifier: a frozen text encoder and a small regression head. This is the FineWeb-Edu classifier's recipe at a smaller scale: Snowflake's arctic-embed-m encoder stays frozen, and only a head on its [CLS] vector (a dense layer, tanh, and one linear output, the same shape as BERT's pooler plus a regression layer) learns to predict the LLM's 0-5 score. Because the encoder is frozen, each document is encoded once and the head trains in seconds. """ from __future__ import annotations import time # Bump when the encoder, the head, or its training changes. Tasks that use this module salt # their cache with it, because cache="auto" hashes only a task's own source. VERSION = "arctic-embed-m/balanced-head/2" ENCODER = "Snowflake/snowflake-arctic-embed-m" PUBLIC_CLASSIFIER = "HuggingFaceFW/fineweb-edu-classifier" MAX_TOKENS = 512 _models: dict = {} def _load(name: str, head: bool = False): """Load a tokenizer and model onto the GPU once per container.""" if name not in _models: import torch from transformers import AutoModel, AutoModelForSequenceClassification, AutoTokenizer cls = AutoModelForSequenceClassification if head else AutoModel started = time.monotonic() tok = AutoTokenizer.from_pretrained(name) model = cls.from_pretrained(name, dtype=torch.float16).cuda().eval() _models[name] = (tok, model, time.monotonic() - started) return _models[name] # {{docs-fragment encode}} def _batches(tok, texts: list[str], batch_size: int): """Tokenize, then batch documents of similar length together so padding stays small.""" enc = tok(texts, truncation=True, max_length=MAX_TOKENS) order = sorted(range(len(texts)), key=lambda i: len(enc["input_ids"][i])) for s in range(0, len(order), batch_size): idx = order[s:s + batch_size] yield idx, tok.pad({"input_ids": [enc["input_ids"][i] for i in idx], "attention_mask": [enc["attention_mask"][i] for i in idx]}, return_tensors="pt") def embed(texts: list[str], batch_size: int = 128): """The encoder's last-layer [CLS] vector for every text, in input order (float32, N x 768).""" import numpy as np import torch tok, model, _ = _load(ENCODER) out = np.zeros((len(texts), model.config.hidden_size), dtype=np.float32) with torch.inference_mode(): for idx, batch in _batches(tok, texts, batch_size): hidden = model(**{k: v.cuda() for k, v in batch.items()}).last_hidden_state[:, 0] out[idx] = hidden.float().cpu().numpy() return out # {{/docs-fragment encode}} def public_scores(texts: list[str], batch_size: int = 128): """Scores from the public FineWeb-Edu classifier, distilled from Llama-3-70B labels.""" import numpy as np import torch tok, model, _ = _load(PUBLIC_CLASSIFIER, head=True) out = np.zeros(len(texts), dtype=np.float32) with torch.inference_mode(): for idx, batch in _batches(tok, texts, batch_size): out[idx] = model(**{k: v.cuda() for k, v in batch.items()}).logits.squeeze(-1).float().cpu().numpy() return out def warm_up(name: str = ENCODER) -> float: """Load a model if this container has not yet. Returns the seconds this call spent loading.""" if name in _models: return 0.0 return _load(name, head=name == PUBLIC_CLASSIFIER)[2] # {{docs-fragment head}} def make_head(dim: int = 768): from torch import nn return nn.Sequential(nn.Linear(dim, dim), nn.Tanh(), nn.Linear(dim, 1)) def train_head(x, y, epochs: int = 100, lr: float = 3e-4, batch_size: int = 256, seed: int = 0): """Fit the head to the LLM scores with a class-balanced MSE. Web text is mostly scores 0-2, so a plain MSE learns to predict "about 1" for everything and never reaches the threshold. Weighting each document by the inverse frequency of its score (capped at 20x) makes the rare high scores count. 10% of the rows pick the best epoch.""" import numpy as np import torch torch.manual_seed(seed) rng = np.random.default_rng(seed) counts = np.bincount(np.rint(y).astype(int), minlength=6).astype(float) weight = np.minimum(counts.max() / np.maximum(counts, 1), 20.0)[np.rint(y).astype(int)] perm = rng.permutation(len(x)) n_val = max(len(x) // 10, 1) val, tr = perm[:n_val], perm[n_val:] def t(a, idx): return torch.tensor(a[idx], dtype=torch.float32).cuda() xt, yt, wt = t(x, tr), t(y, tr), t(weight, tr) xv, yv, wv = t(x, val), t(y, val), t(weight, val) head = make_head(x.shape[1]).cuda() opt = torch.optim.AdamW(head.parameters(), lr=lr, weight_decay=0.05) best, best_state, curve = float("inf"), None, [] for epoch in range(epochs): head.train() for s in torch.randperm(len(xt)).split(batch_size): loss = (wt[s] * (head(xt[s]).squeeze(-1) - yt[s]) ** 2).sum() / wt[s].sum() opt.zero_grad() loss.backward() opt.step() head.eval() with torch.no_grad(): v = ((wv * (head(xv).squeeze(-1) - yv) ** 2).sum() / wv.sum()).item() curve.append(v) if v < best: best, best_state = v, {k: t.detach().clone() for k, t in head.state_dict().items()} head.load_state_dict(best_state) return head.cpu(), curve # {{/docs-fragment head}} def predict(head, x): import torch head = head.cuda().eval() with torch.no_grad(): return head(torch.tensor(x).cuda()).squeeze(-1).float().cpu().numpy() # {{docs-fragment agreement}} def agreement(reference, predicted, threshold: float = 3.0) -> dict: """How well ``predicted`` scores track ``reference`` scores (both 0-5, either may be float).""" import numpy as np ref = np.asarray(reference, dtype=np.float64) pred = np.asarray(predicted, dtype=np.float64) def ranks(v): order = np.argsort(v, kind="stable") r = np.empty(len(v)) r[order] = np.arange(len(v)) for val in np.unique(v): # average ranks over ties (scores are mostly integers) tie = v == val r[tie] = r[tie].mean() return r ri, pi = np.clip(np.rint(ref), 0, 5).astype(int), np.clip(np.rint(pred), 0, 5).astype(int) tp = int(((ref >= threshold) & (pred >= threshold)).sum()) fp = int(((ref < threshold) & (pred >= threshold)).sum()) fn = int(((ref >= threshold) & (pred < threshold)).sum()) precision = tp / (tp + fp) if tp + fp else 0.0 recall = tp / (tp + fn) if tp + fn else 0.0 confusion = np.zeros((6, 6), dtype=int) np.add.at(confusion, (ri, pi), 1) return { "n": int(len(ref)), "spearman": float(np.corrcoef(ranks(ref), ranks(pred))[0, 1]), "pearson": float(np.corrcoef(ref, pred)[0, 1]), "mae": float(np.abs(ref - pred).mean()), "exact": float((ri == pi).mean()), "within_one": float((np.abs(ri - pi) <= 1).mean()), "precision": precision, "recall": recall, "f1": 2 * precision * recall / (precision + recall) if precision + recall else 0.0, "confusion": confusion.tolist(), # rows: reference score, columns: predicted score } # {{/docs-fragment agreement}} CODE11 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/refinery.py* ## Curating and publishing `curate` joins the scores to the surviving documents and keeps those at or above the threshold. It is the only stage whose inputs include the threshold. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/refinery.py* The driver runs the stages, updates the report as each one finishes, and publishes the result as the `edu-web-corpus` artifact. The card records the funnel, every filter threshold, the labeler, and the classifier's agreement, so anyone who loads the dataset can see how it was made. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "refine" # params = "n_shards=2 docs_per_shard=2000 n_labels=300" # /// """Refine raw web text into pretraining data: filter, deduplicate, decontaminate, and score it. N x refine_shard (warm CPU pool, cached per shard) Gopher / C4 / FineWeb heuristics, exact hash, MinHash band keys, 13-gram eval overlap global_dedup exact and near duplicates across every shard, then decontamination sample_for_labeling a few thousand surviving documents K x label_chunk (warm L40S) Qwen2.5-14B-Instruct under vLLM scores them on the FineWeb-Edu rubric train_classifier (L4) frozen arctic-embed-m + a regression head, distilled from those labels N x score_shard (warm L4) the classifier scores every surviving document curate keep documents at or above the threshold; publish with a dataset card This is how FineWeb-Edu was built: Llama-3-70B labeled 450,000 pages for educational value, and a small classifier trained on those labels scored all 15 trillion tokens. Every stage before curate is cached, so rerunning with a new threshold reuses the shards, the labels, and the scores. python refinery.py # 15 shards of 20,000 FineWeb documents, 4,000 LLM labels python refinery.py --smoke # 2 shards of 2,000 documents, 300 labels python refinery.py --threshold 2.5 # same corpus, new threshold: everything but curate is cached """ import asyncio import os import zlib import sys import tempfile import time from dataclasses import dataclass, field import classifier import filters import flyte import flyte.artifacts as artifacts import flyte.report import labeler import reports from flyte.io import DataFrame, File DATASET = "HuggingFaceFW/fineweb" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] # about 1,000 documents per row group CODE = ["filters.py", "labeler.py", "classifier.py", "reports.py", "viz.py"] # {{docs-fragment images}} # CPU stages: Arrow for the shards, xxhash for stable token hashes, SciPy for connected components. cpu_image = flyte.Image.from_debian_base(name="refinery-cpu").with_pip_packages( "pyarrow==22.0.0", "pandas==2.3.3", "numpy==2.3.5", "scipy==1.16.3", "xxhash==3.6.0", "fsspec==2025.10.0", "aiohttp==3.13.2", "requests", "unionai-reuse==0.2.1", ) # GPU stages: vLLM for the labeler. It brings torch and transformers, which the classifier uses. gpu_image = flyte.Image.from_debian_base(name="refinery-gpu", python_version=(3, 12)).with_pip_packages( "vllm==0.33.0", "httpx>=0.27", "pandas", "pyarrow", "unionai-reuse==0.2.1", ) # {{/docs-fragment images}} # {{docs-fragment envs}} # A warm pool of CPU workers takes the shard fan-out and the small global steps. cpu_env = flyte.TaskEnvironment( name="refinery-cpu", image=cpu_image, resources=flyte.Resources(cpu=2, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=(2, 8), concurrency=1, idle_ttl=600, scaledown_ttl=120), include=CODE, ) # The labeler: one L40S that keeps the vLLM server and the model weights loaded between calls. label_env = flyte.TaskEnvironment( name="refinery-labeler", image=gpu_image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L40s:1", disk="60Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600, scaledown_ttl=300), # vLLM's FlashInfer sampler compiles CUDA code at startup, which needs nvcc; the image has # only the CUDA runtime, so use the PyTorch sampler. env_vars={"VLLM_USE_FLASHINFER_SAMPLER": "0"}, include=CODE, ) # The classifier is a 110M-parameter encoder, so a smaller GPU does. Two warm replicas split # the scoring fan-out, and each keeps the encoder in memory between shards. score_env = flyte.TaskEnvironment( name="refinery-scorer", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1", disk="40Gi"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=1, idle_ttl=600, scaledown_ttl=180), include=CODE, ) driver_env = flyte.TaskEnvironment( name="refinery-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, label_env, score_env], include=CODE, ) # {{/docs-fragment envs}} # {{docs-fragment dataclasses}} @dataclass class ShardSpec: index: int file: str row_groups: list[int] @dataclass class EvalNgrams: hashes: File # .npy of sorted uint64 13-gram hashes items: File # parquet: benchmark, text, one row per eval question; ``hashes`` index into it counts: dict[str, int] = field(default_factory=dict) @dataclass class ShardResult: index: int docs: File # parquet of the documents that passed the heuristics, with their signatures raw: int kept: int rejected: dict[str, int] = field(default_factory=dict) examples: list[dict] = field(default_factory=list) contaminated: int = 0 contam_examples: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class DedupResult: removed: File # parquet: id, stage, kept_id after_exact: int after_near: int after_decontam: int examples: list[dict] = field(default_factory=list) clusters: list[dict] = field(default_factory=list) seconds: float = 0.0 @dataclass class LabelChunk: labels: File # parquet: id, llm_score, justification, token counts n: int parsed: int seconds: float # time spent labeling, without the model load startup_s: float # vLLM start and model load, if this call paid for it prompt_tokens: int completion_tokens: int @dataclass class ClassifierResult: head: File held_out: dict # distilled classifier against held-out LLM labels public_vs_llm: dict # public FineWeb-Edu classifier against the same held-out LLM labels ours_vs_public: dict points: list[list[float]] = field(default_factory=list) # held out: [llm, ours, public] label_counts: list[int] = field(default_factory=list) examples: list[dict] = field(default_factory=list) n_train: int = 0 curve: list[float] = field(default_factory=list) @dataclass class ScoredShard: scores: File # parquet: id, edu_score n: int seconds: float # time spent scoring, without the model load load_s: float @dataclass class Curated: kept: int scored: int tokens_kept: int tokens_scored: int histogram: list[int] = field(default_factory=list) # 20 bins of 0.25 over [0, 5] examples: list[dict] = field(default_factory=list) # {{/docs-fragment dataclasses}} def _snippet(text: str, n: int = 600) -> str: text = " ".join(text.split()) return text if len(text) <= n else text[:n] + " โ€ฆ" # โ”€โ”€ CPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment evals}} EVAL_SETS = { "gsm8k": ("openai/gsm8k", "main/test-00000-of-00001.parquet"), "mmlu": ("cais/mmlu", "all/test-00000-of-00001.parquet"), "arc-challenge": ("allenai/ai2_arc", "ARC-Challenge/test-00000-of-00001.parquet"), "arc-easy": ("allenai/ai2_arc", "ARC-Easy/test-00000-of-00001.parquet"), } @cpu_env.task(cache="auto", retries=2) async def build_eval_ngrams(config: filters.FilterConfig) -> EvalNgrams: """Every 13-gram of every test question in GSM8K, MMLU and ARC, hashed like document text.""" import numpy as np import pandas as pd rows = [] for name, (repo, path) in EVAL_SETS.items(): df = pd.read_parquet(f"https://huggingface.co/datasets/{repo}/resolve/main/{path}") for q in df.to_dict("records"): question = q["question"] choices = q.get("choices") if isinstance(choices, dict): # ARC: {"text": [...], "label": [...]} choices = choices["text"] extra = " ".join(map(str, choices)) if choices is not None else "" rows.append((name, question, extra)) hashes, owners = [], [] for i, (_, question, extra) in enumerate(rows): # The question alone, and the question followed by its answer options. grams = np.unique(np.concatenate([ filters.ngram_hashes(filters.token_hashes(filters.tokens(t)), config.contam_ngram) for t in (question, f"{question} {extra}") ])) hashes.append(grams) owners.append(np.full(len(grams), i, dtype=np.int64)) h, o = np.concatenate(hashes), np.concatenate(owners) order = np.argsort(h, kind="stable") d = tempfile.mkdtemp() np.save(f"{d}/ngrams.npy", np.stack([h[order], o[order].astype(np.uint64)])) pd.DataFrame(rows, columns=["benchmark", "text", "choices"]).to_parquet(f"{d}/items.parquet") counts = pd.Series([r[0] for r in rows]).value_counts().to_dict() print(f"{len(rows)} eval questions, {len(h)} distinct 13-grams") return EvalNgrams(await File.from_local(f"{d}/ngrams.npy"), await File.from_local(f"{d}/items.parquet"), {k: int(v) for k, v in counts.items()}) # {{/docs-fragment evals}} # {{docs-fragment shard}} @cpu_env.task(cache="auto", retries=2) async def refine_shard(spec: ShardSpec, config: filters.FilterConfig, evals: EvalNgrams) -> ShardResult: """Read one shard of raw web text, drop documents that fail a heuristic, and compute what the global steps need: an exact-match hash, MinHash band keys, and any overlap with an eval set.""" import re import fsspec import numpy as np import pandas as pd import pyarrow.parquet as pq started = time.monotonic() url = f"https://huggingface.co/datasets/{DATASET}/resolve/main/{spec.file}" with fsspec.open(url, "rb", block_size=16 * 2**20) as f: table = pq.ParquetFile(f).read_row_groups(spec.row_groups, columns=["id", "url", "dump", "token_count", "text"]) eval_grams = np.load(await evals.hashes.download()) eval_items = pd.read_parquet(await evals.items.download()) rows, rejected, examples, contam_examples = [], {}, [], [] for doc in table.to_pylist(): text = doc["text"] words = filters.tokens(text) hashes = filters.token_hashes(words) reason = filters.heuristic_reject(text, config, words, hashes) if reason: rejected[reason] = rejected.get(reason, 0) + 1 if rejected[reason] <= 2: examples.append({"stage": "heuristics", "rule": reason, "url": doc["url"], "text": _snippet(text)}) continue keys = filters.band_keys(filters.minhash(hashes, config), config) # Decontamination: does any 13-gram of the document appear in an eval question? grams = filters.ngram_hashes(hashes, config.contam_ngram) pos = np.searchsorted(eval_grams[0], grams).clip(max=eval_grams.shape[1] - 1) hits = np.flatnonzero(eval_grams[0][pos] == grams) contam = "" if len(hits): item = eval_items.iloc[int(eval_grams[1][pos[hits[0]]])] contam = item["benchmark"] spans = [m.span() for m in re.finditer(r"\w+", text)] first = min(hits[0], len(spans) - config.contam_ngram) start, end = spans[first][0], spans[first + config.contam_ngram - 1][1] contam_examples.append({ "url": doc["url"], "benchmark": contam, "question": _snippet(item["text"], 400), "match": text[start:end], "matched_ngrams": int(len(np.unique(grams[hits]))), "context": _snippet(text[max(0, start - 250):end + 250], 700), }) rows.append({ "id": doc["id"], "url": doc["url"], "dump": doc["dump"], "token_count": doc["token_count"], "text": text, "exact": filters.exact_hash(text), "contam": contam, **{f"b{i}": k for i, k in enumerate(keys)}, }) out = os.path.join(tempfile.mkdtemp(), f"shard-{spec.index:03d}.parquet") pd.DataFrame(rows).to_parquet(out, index=False) seconds = time.monotonic() - started print(f"shard {spec.index}: {table.num_rows} read, {len(rows)} kept, {len(contam_examples)} contaminated, {seconds:.0f}s") return ShardResult(spec.index, await File.from_local(out), table.num_rows, len(rows), rejected, examples, len(contam_examples), contam_examples[:20], round(seconds, 1)) # {{/docs-fragment shard}} # {{docs-fragment dedup}} @cpu_env.task(cache="auto") async def global_dedup(shards: list[ShardResult], config: filters.FilterConfig) -> DedupResult: """Remove exact duplicates, then near duplicates, across every shard; then contaminated documents. Two documents are near-duplicate candidates when they share any MinHash band key. Candidates are joined into clusters (connected components), and each cluster keeps its first document.""" import numpy as np import pandas as pd import pyarrow.parquet as pq from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components started = time.monotonic() bands = [f"b{i}" for i in range(config.bands)] frames = [] for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "exact", "contam", *bands]).to_pandas() t["shard"] = s.index frames.append(t) df = pd.concat(frames, ignore_index=True) n = len(df) exact_dup = df.duplicated("exact", keep="first").to_numpy() first_of_hash = df.groupby("exact")["id"].transform("first").to_numpy() alive = np.flatnonzero(~exact_dup) src, dst = [], [] for b in bands: keys = df[b].to_numpy()[alive] order = np.argsort(keys, kind="stable") same = keys[order][1:] == keys[order][:-1] src.append(alive[order[:-1][same]]) dst.append(alive[order[1:][same]]) src, dst = np.concatenate(src), np.concatenate(dst) graph = coo_matrix((np.ones(len(src)), (src, dst)), shape=(n, n)) _, cluster = connected_components(graph, directed=False) rep = pd.Series(np.arange(n)[alive], index=alive).groupby(cluster[alive]).transform("min") near_dup = np.zeros(n, dtype=bool) near_dup[alive] = rep.to_numpy() != alive rep_of = np.arange(n) rep_of[alive] = rep.to_numpy() after_near = ~exact_dup & ~near_dup contaminated = after_near & (df["contam"].to_numpy() != "") stage = np.where(exact_dup, "exact duplicate", np.where(near_dup, "near duplicate", np.where(contaminated, "contaminated", ""))) removed = pd.DataFrame({"id": df["id"], "stage": stage, "kept_id": np.where(exact_dup, first_of_hash, df["id"].to_numpy()[rep_of])}) removed = removed[removed["stage"] != ""] out = os.path.join(tempfile.mkdtemp(), "removed.parquet") removed.to_parquet(out, index=False) # Examples for the report: a few duplicate pairs, with the text of both sides. pairs = pd.concat([removed[removed.stage == "exact duplicate"].head(3), removed[removed.stage == "near duplicate"].head(6)]) wanted = set(pairs["id"]) | set(pairs["kept_id"]) text = {} for s in shards: t = pq.read_table(await s.docs.download(), columns=["id", "url", "text"]).to_pandas() for r in t[t["id"].isin(wanted)].itertuples(): text[r.id] = (r.url, r.text) examples = [{"stage": p.stage, "url": text[p.id][0], "text": _snippet(text[p.id][1], 400), "kept_url": text[p.kept_id][0], "kept_text": _snippet(text[p.kept_id][1], 400)} for p in pairs.itertuples() if p.id in text and p.kept_id in text] sizes = pd.Series(cluster[alive]).value_counts() clusters = [{"size": int(c), "url": df["url"].iloc[int(alive[np.flatnonzero(cluster[alive] == k)[0]])]} for k, c in sizes[sizes > 1].head(5).items()] result = DedupResult(await File.from_local(out), int(n - exact_dup.sum()), int(after_near.sum()), int((after_near & ~contaminated).sum()), examples, clusters, round(time.monotonic() - started, 1)) print(f"{n} in, {result.after_exact} after exact, {result.after_near} after near, {result.after_decontam} after decontamination") return result # {{/docs-fragment dedup}} async def _survivors(docs: File, removed: File, columns: list[str]): import pandas as pd gone = set(pd.read_parquet(await removed.download(), columns=["id"])["id"]) df = pd.read_parquet(await docs.download(), columns=columns) return df[~df["id"].isin(gone)] @cpu_env.task(cache="auto") async def sample_for_labeling(shards: list[ShardResult], dedup: DedupResult, n: int, chunks: int, seed: int = 0) -> list[File]: """A uniform sample of the surviving documents, split into chunks for the labeler.""" import numpy as np import pandas as pd rng = np.random.default_rng(seed) total = dedup.after_decontam take = set(rng.choice(total, size=min(n, total), replace=False).tolist()) picked, offset = [], 0 for s in shards: df = await _survivors(s.docs, dedup.removed, ["id", "text"]) mine = [i - offset for i in range(offset, offset + len(df)) if i in take] picked.append(df.iloc[mine]) offset += len(df) sample = pd.concat(picked).sample(frac=1.0, random_state=seed) d, files = tempfile.mkdtemp(), [] for k, part in enumerate(np.array_split(np.arange(len(sample)), chunks)): path = f"{d}/chunk-{k}.parquet" sample.iloc[part].to_parquet(path, index=False) files.append(await File.from_local(path)) return files # โ”€โ”€ GPU stages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment label-task}} @label_env.task(cache=flyte.Cache("auto", salt=labeler.VERSION), retries=1) async def label_chunk(chunk: File, model: str) -> LabelChunk: """Score a chunk of documents on the FineWeb-Edu rubric with the LLM. The first call on a replica starts vLLM; the rest find it warm.""" import pandas as pd server, started_here = labeler.get_server(model) df = pd.read_parquet(await chunk.download()) t0 = time.monotonic() answers = await labeler.label_all(df["text"].tolist(), model) seconds = time.monotonic() - t0 out = pd.DataFrame(answers) out.insert(0, "id", df["id"].to_numpy()) path = os.path.join(tempfile.mkdtemp(), "labels.parquet") out.to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s, {out.llm_score.notna().sum()} with a score") return LabelChunk(await File.from_local(path), len(df), int(out.llm_score.notna().sum()), round(seconds, 2), round(server.startup_s, 1) if started_here else 0.0, int(out.prompt_tokens.sum()), int(out.completion_tokens.sum())) # {{/docs-fragment label-task}} # {{docs-fragment train-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def train_classifier(chunks: list[File], labels: list[LabelChunk], held_out_share: float = 0.2) -> ClassifierResult: """Distill the LLM's labels into the encoder + head classifier, and measure it on held-out labels next to the public FineWeb-Edu classifier.""" import pandas as pd import torch docs = pd.concat([pd.read_parquet(await c.download()) for c in chunks]) lab = pd.concat([pd.read_parquet(await l.labels.download()) for l in labels]) df = docs.merge(lab, on="id").dropna(subset=["llm_score"]).reset_index(drop=True) df["llm_score"] = df["llm_score"].astype(float) # A stable split by document id, so a rerun holds out the same documents. test = df["id"].map(lambda s: zlib.crc32(s.encode()) % 1000 < held_out_share * 1000).to_numpy() x = classifier.embed(df["text"].tolist()) head, curve = classifier.train_head(x[~test], df["llm_score"].to_numpy()[~test]) held = df[test].reset_index(drop=True) held["ours"] = classifier.predict(head, x[test]) held["public"] = classifier.public_scores(held["text"].tolist()) llm, ours, public = held["llm_score"].to_numpy(), held["ours"].to_numpy(), held["public"].to_numpy() path = os.path.join(tempfile.mkdtemp(), "head.pt") torch.save(head.state_dict(), path) examples = [{"llm": int(r.llm_score), "ours": float(r.ours), "public": float(r.public), "text": _snippet(r.text, 500), "justification": r.justification} for score in range(6) for r in held[held["llm_score"] == score].head(1).itertuples()] return ClassifierResult( head=await File.from_local(path), held_out=classifier.agreement(llm, ours), public_vs_llm=classifier.agreement(llm, public), ours_vs_public=classifier.agreement(public, ours), points=[[float(a), round(float(b), 3), round(float(c), 3)] for a, b, c in zip(llm, ours, public)], label_counts=[int((df["llm_score"] == s).sum()) for s in range(6)], examples=examples, n_train=int((~test).sum()), curve=[round(v, 4) for v in curve], ) # {{/docs-fragment train-task}} # {{docs-fragment score-task}} @score_env.task(cache=flyte.Cache("auto", salt=classifier.VERSION), retries=1) async def score_shard(docs: File, removed: File, head: File) -> ScoredShard: """Score every surviving document in one shard with the distilled classifier.""" import pandas as pd import torch df = await _survivors(docs, removed, ["id", "text"]) model = classifier.make_head() model.load_state_dict(torch.load(await head.download(), weights_only=True)) load_s = classifier.warm_up() # zero when this replica already holds the encoder t0 = time.monotonic() scores = classifier.predict(model, classifier.embed(df["text"].tolist())) seconds = time.monotonic() - t0 path = os.path.join(tempfile.mkdtemp(), "scores.parquet") pd.DataFrame({"id": df["id"].to_numpy(), "edu_score": scores.clip(0, 5)}).to_parquet(path, index=False) print(f"{len(df)} documents in {seconds:.0f}s") return ScoredShard(await File.from_local(path), len(df), round(seconds, 2), round(load_s, 1)) # {{/docs-fragment score-task}} # {{docs-fragment curate}} @cpu_env.task(cache="auto") async def curate(shards: list[ShardResult], dedup: DedupResult, scores: list[ScoredShard], threshold: float) -> tuple[DataFrame, Curated]: """Join the scores to the surviving documents and keep those at or above the threshold.""" import numpy as np import pandas as pd kept, hist, scored, tokens_scored = [], np.zeros(20, dtype=int), 0, 0 low = [] for s, sc in zip(shards, scores): df = await _survivors(s.docs, dedup.removed, ["id", "url", "dump", "token_count", "text"]) df = df.merge(pd.read_parquet(await sc.scores.download()), on="id") hist += np.histogram(df["edu_score"], bins=20, range=(0, 5))[0] scored += len(df) tokens_scored += int(df["token_count"].sum()) below = df[df["edu_score"] < threshold] low.append(below.sample(n=min(2, len(below)), random_state=s.index)) kept.append(df[df["edu_score"] >= threshold]) out = pd.concat(kept, ignore_index=True) out["edu_int_score"] = out["edu_score"].round().clip(0, 5).astype(int) examples = [{"stage": "classifier", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in pd.concat(low).head(4).itertuples()] examples += [{"stage": "kept", "rule": f"score {r.edu_score:.2f}", "url": r.url, "text": _snippet(r.text)} for r in out.nlargest(3, "edu_score").itertuples()] stats = Curated(len(out), scored, int(out["token_count"].sum()), tokens_scored, hist.tolist(), examples) return await DataFrame.from_local(out), stats # {{/docs-fragment curate}} # โ”€โ”€ driver โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def shard_specs(n_shards: int, docs_per_shard: int) -> list[ShardSpec]: """Spread shards over the sample's files. Each file mixes many Common Crawl snapshots.""" groups = max(docs_per_shard // 1000, 1) return [ShardSpec(i, FILES[i % len(FILES)], list(range((i // len(FILES)) * groups + 40, (i // len(FILES) + 1) * groups + 40))) for i in range(n_shards)] # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def refine( n_shards: int = 15, docs_per_shard: int = 20_000, n_labels: int = 4000, label_chunks: int = 4, threshold: float = 3.0, label_model: str = "Qwen/Qwen2.5-14B-Instruct", ) -> DataFrame: """Turn raw web text into a scored, filtered, deduplicated and decontaminated corpus.""" config = filters.FilterConfig() timing: dict[str, float] = {} t = time.monotonic() with flyte.group("filter-shards"): evals = await build_eval_ngrams(config) shards = list(await asyncio.gather(*[refine_shard(s, config, evals) for s in shard_specs(n_shards, docs_per_shard)])) timing["filter shards"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, None, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() dedup = await global_dedup(shards, config) timing["dedup + decontaminate"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, None, None, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("llm-labels"): chunks = await sample_for_labeling(shards, dedup, n_labels, label_chunks) labels = [] for c in chunks: # one warm replica: the first call loads the model, the rest reuse it labels.append(await label_chunk(c, label_model)) timing["LLM labels"] = time.monotonic() - t t = time.monotonic() clf = await train_classifier(chunks, labels) timing["train classifier"] = time.monotonic() - t await flyte.report.replace.aio(reports.live(config, shards, dedup, labels, clf, None, threshold, evals.counts), do_flush=True) t = time.monotonic() with flyte.group("score-shards"): scores = list(await asyncio.gather(*[score_shard(s.docs, dedup.removed, clf.head) for s in shards])) timing["score every document"] = time.monotonic() - t t = time.monotonic() dataset, curated = await curate(shards, dedup, scores, threshold) timing["curate"] = time.monotonic() - t summary = reports.summarize(config, shards, dedup, labels, clf, scores, curated, threshold, timing, label_model) await flyte.report.replace.aio(reports.final(summary, shards, dedup, clf, curated, evals.counts), do_flush=True) flyte.report.get_tab("Rejected documents").replace(reports.rejected_tab(shards, dedup, curated)) flyte.report.get_tab("LLM labels and the classifier").replace(reports.labels_tab(clf, labels)) await flyte.report.flush.aio() card = await artifacts.Card.create_from.aio(content=reports.card(summary), format="html", card_type="data") metadata = artifacts.Metadata( name="edu-web-corpus", description=f"{curated.kept:,} FineWeb documents with an educational score of at least {threshold}, " f"from {summary['funnel'][0][1]:,} raw documents", kind="data", attrs={"threshold": str(threshold), "filters": config.version, "labeler": label_model, "classifier": f"{classifier.ENCODER} + head", "documents": str(curated.kept), "tokens": str(curated.tokens_kept), "source": f"{DATASET} sample-10BT"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() args = {} if "--threshold" in sys.argv: args["threshold"] = float(sys.argv[sys.argv.index("--threshold") + 1]) if "--label-model" in sys.argv: args["label_model"] = sys.argv[sys.argv.index("--label-model") + 1] if "--smoke" in sys.argv: args.update(n_shards=2, docs_per_shard=2000, n_labels=300) run = flyte.run(refine, **args) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/pretraining_data_refinery/refinery.py* ## Results A run with the defaults read 299,906 FineWeb documents in 15 shards. The CPU stages took about 5 minutes for the shards and 20 seconds for the global step. Labeling 4,000 documents with Qwen2.5-14B-Instruct took 12 minutes on one L40S, plus 6 minutes to download and load the model on the first call. Training the head took 41 seconds and scoring every surviving document took 7 minutes on the L4 pool. A cold run takes about 30 minutes. | Stage | Documents kept | Share of raw | | --- | --- | --- | | Raw FineWeb documents | 299,906 | 100% | | Pass the heuristic filters | 290,179 | 96.8% | | No exact duplicate | 290,159 | 96.7% | | No near duplicate | 290,100 | 96.7% | | No eval overlap | 290,068 | 96.7% | | Educational score of at least 3 | 3,454 | 1.2% (3.8M tokens) | | Educational score of at least 2.5 | 17,967 | 6.0% (19.0M tokens) | ![The refinery report: documents kept at each stage, the distilled classifier's scores, its agreement with the LLM labels, GPU time per document, and the rules that rejected the most documents](../../../_static/images/tutorials/pretraining-data-refinery/refinery-report.png) The early stages remove little because FineWeb already ran the same kind of pipeline: Trafilatura extraction, language identification, Gopher and C4 filters, and MinHash deduplication within each Common Crawl snapshot. The rules that still fire most often are Gopher's repeated 5-grams (2,682 documents) and its minimum length (1,827). Many of the 79 duplicates are the same URL crawled in two snapshots, which FineWeb deduplicated within a snapshot but not across them; the rest are templated pages. On raw crawl, the heuristic and deduplication stages remove far more; on FineWeb, as in FineWeb-Edu, the quality classifier does most of the filtering. The 32 documents removed as eval overlap are worth reading. The ones in the report match MMLU questions that quote a famous public text, such as the Declaration of Independence, a Patrick Henry speech, or the boilerplate of a US statute. A 13-gram match finds exactly these documents, and whether to drop them is a policy decision: they contain the source passage, not the question or its answer. ### Why distill | | GPU time per document | GPU | | --- | --- | --- | | LLM labeler, Qwen2.5-14B-Instruct | 174 ms | L40S | | Distilled classifier | 2.6 ms | L4 | The classifier is 66 times cheaper per document, on a smaller GPU. Labeling all 290,068 surviving documents with the LLM would have taken about 14 L40S-hours; the classifier took 13 L4-minutes. At FineWeb's scale of billions of documents, only the classifier is affordable. What it costs in agreement, on 797 held-out documents that the LLM labeled. The decision that matters for curation is the binary one, keep or drop at a score of 3, so F1 at that threshold comes first: | Comparison | F1 at a score of 3 | Spearman | Within 1 point | | --- | --- | --- | --- | | Distilled classifier against the LLM labels | 0.20 | 0.61 | 98% | | Public FineWeb-Edu classifier against the LLM labels | 0.31 | 0.65 | 98% | | Distilled classifier against the public classifier | 0.21 | 0.74 | 99% | At the threshold, the distilled head is clearly worse than the public classifier, which was trained on 450,000 labels from a 70B model; on ranking, the gap is smaller. Read these numbers with two caveats. The held-out labels come from the distilled head's own teacher, so they measure how well it learned the 14B model, not how good the 14B model is. And both classifiers put a head on the same frozen `arctic-embed-m` encoder, which inflates their agreement with each other (0.74). Only 43 held-out documents have an LLM score of 3 or more, so the F1 values are noisy too. The distilled scores are also compressed toward the middle: the head rarely predicts above 3.5, so at FineWeb-Edu's threshold of 3 it keeps 1.2% of the corpus, while the LLM gave 4.8% of its sample a 3 or more. A threshold of 2.5 keeps 6.0%. ### Changing the threshold Rerunning with `--threshold 2.5` took 33 seconds. 38 of the 39 tasks were cache hits: every shard, the global step, the labels, the classifier, and every score. Only `curate` ran, and the artifact got a new version with 17,967 documents. ![The rerun with a new threshold: every shard, the labels, and the classifier come back from cache, and only curate runs](../../../_static/images/tutorials/pretraining-data-refinery/cached-rerun.png) ### Check the labeler before you distill A distilled classifier is only as good as its labels, and its agreement with its own teacher hides that. In the runs for this tutorial, Qwen2.5-3B-Instruct as the labeler was fast, 47 ms per document, but lenient: it gave 54% of the sample a 3 or more, against 5% for the 14B model. The public classifier agreed with its labels at an F1 of 0.08 at the threshold, and a classifier distilled from them kept 17% of the corpus. Check the teacher against an independent reference, here the public classifier, before you distill it. The loss matters too. In the same runs, a head trained on the 14B labels with a plain MSE ranked well, at a Spearman of 0.64, but almost every prediction fell between 0 and 2.5, and the threshold of 3 kept 30 documents. Weighting the loss by inverse score frequency spread the predictions out at a small cost in rank correlation. ## At real scale - **More data.** The shard task is the unit of work. Point `shard_specs` at more files and raise the pool's `replicas`; the global step reads only the hash columns, so it stays small. Past a few hundred million documents, run deduplication as a distributed join instead. - **More labels, a stronger labeler.** FineWeb-Edu used 450,000 labels from a 70B model. Raise `n_labels` and `label_chunks`, and give `label_env` more replicas or GPUs; every chunk is cached, so a long labeling job survives a failure. - **A raw crawl.** Replace the FineWeb reader with text extracted from Common Crawl WARC files and add a language identification stage. The heuristic and deduplication stages then do much more of the filtering. - **Other labels.** Swap the prompt for a taxonomy, as Essential-Web did, and train one head per category on the same frozen embeddings. ## Related - **Tasks > Configure tasks > Reusable containers** - **Tasks > Configure tasks > Caching** - **Tasks > Build tasks > Fanout** - **Tasks > Build tasks > Reports** - **Artifacts > Publish your own artifacts** === PAGE: https://www.union.ai/docs/v2/union/tutorials/frontier-ai/checkpoint-evals === Publish every checkpoint of a fine-tuning run as an artifact version, let an artifact trigger run a benchmark suite on each one while training continues, and promote the checkpoint that wins a ship rule. # Evaluate every checkpoint > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/checkpoint_evals). A training run saves checkpoints. Picking the one to ship takes evaluations. Post-training and evals teams at frontier labs run a benchmark suite on every checkpoint a job saves, while the job keeps training. The scores decide which checkpoint becomes the release candidate. They also catch a regression, such as a skill the new data is wearing away, while there is still time to stop the run. [OLMo](https://arxiv.org/abs/2402.00838) evaluates during training and again offline on saved checkpoints, with a standard suite ([OLMES](https://arxiv.org/abs/2406.08446)) so that scores from different runs are comparable. [DataDecide](https://arxiv.org/abs/2504.11393) shows why the early checkpoints are worth scoring too: rankings at intermediate checkpoints predict the final ranking well, so evals on small, early checkpoints can decide what to train at scale. At scale this is an infrastructure problem more than a benchmark problem: - **Training must not wait for evals.** An eval suite is hours of GPU time on a large model. If the trainer runs evals itself, it either stalls or runs a smaller suite than you want. - **Evals must not depend on the trainer.** The eval team changes benchmarks, prompts, and scorers on its own schedule. It should not have to edit, or even know about, the training job. - **Old checkpoints get new benchmarks.** When a benchmark is added, the team wants it on every checkpoint it already has, without paying again for the scores that have not changed. - **Scores must be reproducible.** The same checkpoint and the same benchmark version should give the same number. Greedy decoding with batched inference is less deterministic than it looks; see [Defeating nondeterminism in LLM inference](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/). This tutorial builds that system at small scale. A trainer fine-tunes [SmolLM2-360M](https://huggingface.co/HuggingFaceTB/SmolLM2-360M) on math word problems and publishes each checkpoint as a new version of an artifact. A separately deployed evaluator has an artifact trigger on that artifact, so every new checkpoint starts its own eval run, which fans out three benchmarks in parallel. A report on the trainer's side draws learning curves as the scores arrive and promotes the best checkpoint as a release candidate. ## How it fits together ```mermaid flowchart LR subgraph trainer["train.py (one run)"] D["train_and_watch
CPU driver, live leaderboard"] --> T["finetune
L40S, SFT"] end T -- "Artifact.create
step 0 ... step N" --> A[("math-sft-checkpoint
one version per checkpoint")] A -- "OnArtifact trigger" --> E["evaluate_checkpoint
one run per checkpoint"] subgraph evaluator["evals.py (deployed once)"] E --> G["run_generate
GSM8K, L4 + vLLM"] E --> C1["run_choice
ARC-Easy, L4"] E --> C2["run_choice
MMLU guard, L4"] end E -- "scores" --> R[("math-sft-checkpoint-evals")] R -. "polled" .-> D D -- "best checkpoint" --> P[("math-sft-release-candidate")] classDef gpu fill:#3b82f633,stroke:#3b82f6,stroke-width:1.5px classDef cpu fill:#94a3b826,stroke:#94a3b8,stroke-width:1px class T,G,C1,C2 gpu class D,E cpu ``` The trainer and the evaluator meet only in the artifact service. The trainer never calls the evaluator, and the evaluator never imports the trainer's code; `train.py` deploys the evaluator before it starts only so that a first run works with one command. | Need | Construct | | --- | --- | | Publish a checkpoint mid-training, without stopping | `flyte.remote.Artifact.create` from inside the training task, partitioned by run and step | | Start an eval run for every new checkpoint | `flyte.Trigger` with `flyte.OnArtifact`, deployed once with `flyte.deploy` | | Hand the checkpoint and its step to the eval run | `flyte.TriggeredArtifact` and `flyte.TriggeredPartition` in the trigger's inputs | | Score benchmarks in parallel | One task per benchmark, each on its own GPU, run with `asyncio.gather` | | Never score the same checkpoint and benchmark version twice | `flyte.Cache` with an explicit version; the benchmark version is a task input | | Learning curves while training runs | `report=True` on the driver, redrawn as score artifacts arrive | | Ship a checkpoint | A release-candidate artifact with a model card and lineage to the checkpoint | ## Getting started You need a cluster with one NVIDIA L40S for training and NVIDIA L4s for evals. Each eval run uses three L4s, and early checkpoints arrive faster than an eval run finishes, so up to about nine L4s are busy at once. Any GPU with 24 GB or more works; change `train_env` in `train.py` (shown below) and the environments in `evals.py`. ```bash git clone https://github.com/unionai/unionai-examples cd unionai-examples/v2/tutorials/checkpoint_evals python train.py ``` ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Fine-tune a small model on math and publish every checkpoint as an artifact version. train_and_watch (CPU driver, live leaderboard report) โ””โ”€ finetune (L40S): SFT SmolLM2-360M on MetaMathQA step 0, then 8 checkpoints โ”€โ”€> Artifact.create(math-sft-checkpoint, step=...) โ”‚ (the evaluator's trigger runs each one) <โ”€โ”€ polls math-sft-checkpoint-evals, redraws curves, picks and promotes the best The trainer never calls the evaluator. It publishes checkpoints and keeps training; the evaluator's artifact trigger (see evals.py) launches one eval run per checkpoint. The driver only reads the published scores to draw learning curves and promote a release candidate. python train.py # deploy the evaluator, then train (about 20 minutes) python train.py --smoke # 2 checkpoints, 40 problems per benchmark python train.py --leaderboard # redraw the leaderboard after a backfill """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from config import ( BASE_MODEL, CHECKPOINT_ARTIFACT, RELEASE_ARTIFACT, RESULTS_ARTIFACT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import leaderboard_html, pick_best, release_card, training_html # {{docs-fragment envs}} train_env = flyte.TaskEnvironment( name="ckpt-evals-train", image=gpu_image, resources=flyte.Resources(cpu=6, memory="48Gi", gpu="L40s:1", disk="80Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) driver_env = flyte.TaskEnvironment( name="ckpt-evals-driver", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[train_env], ) # {{/docs-fragment envs}} def checkpoint_steps(total: int, n: int) -> list[int]: """Step 0, then ``n`` checkpoints spaced closer early on, where the curves move fastest.""" fracs = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 3 / 8, 1 / 2, 3 / 4, 1][-n:] if n <= 8 else [k / n for k in range(1, n + 1)] return [0] + sorted({max(1, round(f * total)) for f in fracs}) def load_sft_data(tok, n: int, max_len: int, seed: int) -> list[tuple[list[int], int]]: """MetaMathQA's GSM8K-derived problems as (token ids, prompt length) in the eval prompt format.""" from benchmarks import SFT_PROMPT from datasets import load_dataset ds = load_dataset("meta-math/MetaMathQA", split="train") ds = ds.filter(lambda t: t.startswith("GSM"), input_columns="type").shuffle(seed=seed).select(range(n)) out = [] for q, a in zip(ds["query"], ds["response"]): prompt = tok.encode(SFT_PROMPT.format(question=q), add_special_tokens=False) answer = tok.encode(" " + a.strip(), add_special_tokens=False) + [tok.eos_token_id] out.append(((prompt + answer)[:max_len], len(prompt))) return out # {{docs-fragment publish}} async def publish_checkpoint(path: str, step: int, train_run: str, profile: str, loss: float | None) -> str: """Upload a saved checkpoint and register it as a new version of the checkpoint artifact. The evaluator's trigger fires on this call; training does not wait for it. """ from flyte.remote import Artifact ckpt = await Dir.from_local(path) art = await Artifact.create.aio( ckpt, name=CHECKPOINT_ARTIFACT, version=f"{train_run}-step{step:05d}", kind="model", description=f"{BASE_MODEL} math SFT, step {step} of {train_run}", partitions={"train_run": train_run, "step": str(step), "profile": profile}, attrs={"base_model": BASE_MODEL, "train_loss": f"{loss:.4f}" if loss is not None else "n/a"}, ) return art.version # {{/docs-fragment publish}} # {{docs-fragment finetune}} @train_env.task(report=True) async def finetune( train_run: str, profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, micro_batch: int = 8, grad_accum: int = 4, max_len: int = 512, seed: int = 0, ) -> str: """Full fine-tune on one GPU; save and publish checkpoints without pausing for uploads.""" import math import os import random import torch from safetensors.torch import save_file from transformers import AutoModelForCausalLM, AutoTokenizer torch.manual_seed(seed) tok = AutoTokenizer.from_pretrained(BASE_MODEL) model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.float32).cuda() data = load_sft_data(tok, train_examples, max_len, seed) total = len(data) // (micro_batch * grad_accum) save_at = checkpoint_steps(total, n_checkpoints) opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, betas=(0.9, 0.95), weight_decay=0.0) warmup = max(1, total // 30) def lr_at(s: int) -> float: # linear warmup, cosine decay to 10% if s < warmup: return learning_rate * (s + 1) / warmup return learning_rate * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total - warmup)))) loop = asyncio.get_running_loop() uploads: list = [] history: list[dict] = [] published: list[dict] = [] started = time.time() def save(step: int, loss: float | None) -> None: # Saving takes seconds and runs on the training thread. Uploading and publishing run on # the event loop, so the next optimizer step starts right away. path = f"/tmp/ckpt/step-{step:05d}" os.makedirs(path, exist_ok=True) sd = {k: v.detach().to(torch.bfloat16).cpu().contiguous() for k, v in model.state_dict().items() if not (model.config.tie_word_embeddings and k == "lm_head.weight")} save_file(sd, f"{path}/model.safetensors", metadata={"format": "pt"}) model.config.save_pretrained(path) model.generation_config.save_pretrained(path) tok.save_pretrained(path) published.append({"step": step, "loss": loss, "saved_s": round(time.time() - started, 1)}) uploads.append(asyncio.run_coroutine_threadsafe( publish_checkpoint(path, step, train_run, profile, loss), loop)) def train() -> None: model.train() order = list(range(len(data))) random.Random(seed).shuffle(order) save(0, None) for step in range(1, total + 1): for g in opt.param_groups: g["lr"] = lr_at(step - 1) step_loss = 0.0 for m in range(grad_accum): lo = ((step - 1) * grad_accum + m) * micro_batch batch = [data[i] for i in order[lo:lo + micro_batch]] width = max(len(ids) for ids, _ in batch) x = torch.full((len(batch), width), tok.pad_token_id or tok.eos_token_id) y = torch.full((len(batch), width), -100) mask = torch.zeros((len(batch), width), dtype=torch.long) for r, (ids, plen) in enumerate(batch): x[r, :len(ids)] = torch.tensor(ids) mask[r, :len(ids)] = 1 y[r, plen:len(ids)] = torch.tensor(ids[plen:]) # loss on the answer only with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=x.cuda(), attention_mask=mask.cuda(), labels=y.cuda()).loss / grad_accum loss.backward() step_loss += loss.item() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() opt.zero_grad(set_to_none=True) if step % 10 == 0 or step == total: history.append({"step": step, "loss": round(step_loss, 4), "lr": lr_at(step - 1), "elapsed_s": round(time.time() - started, 1)}) if step in save_at: save(step, step_loss) if step % 25 == 0 or step in save_at: flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() await asyncio.to_thread(train) versions = await asyncio.gather(*[asyncio.wrap_future(u) for u in uploads]) flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() return json.dumps({"steps": save_at, "versions": versions, "history": history, "published": published, "total_steps": total, "train_s": round(time.time() - started, 1)}) # {{/docs-fragment finetune}} # {{docs-fragment collect}} async def collect_results(train_run: str) -> dict[int, dict]: """The newest published scores for each checkpoint of one training run, keyed by step.""" from flyte.remote import Artifact rows: dict[int, dict] = {} async for art in Artifact.listall.aio(name=RESULTS_ARTIFACT, train_run=train_run): step = int(art.partitions["step"]) if step in rows: # listall is newest first; a backfill publishes a newer version continue f = await art.to_python.aio(File) async with f.open("rb") as fh: rows[step] = json.loads(bytes(await fh.read())) rows[step]["published_at"] = art.pb2.created_at.ToDatetime().timestamp() return rows async def checkpoint_times(train_run: str) -> dict[int, float]: from flyte.remote import Artifact return {int(a.partitions["step"]): a.pb2.created_at.ToDatetime().timestamp() async for a in Artifact.listall.aio(name=CHECKPOINT_ARTIFACT, train_run=train_run)} # {{/docs-fragment collect}} # {{docs-fragment promote}} async def promote(train_run: str, rows: dict[int, dict], best: int) -> str: """Publish the winning checkpoint again, as the release-candidate artifact with a model card.""" from flyte.remote import Artifact ckpt = await Artifact.get.aio(CHECKPOINT_ARTIFACT, train_run=train_run, step=str(best)) card = await artifacts.Card.create_from.aio(content=release_card(train_run, rows, best), format="html", card_type="model") scores = rows[best]["scores"] art = await Artifact.create.aio( await ckpt.to_python.aio(Dir), name=RELEASE_ARTIFACT, version=f"{train_run}-step{best:05d}", kind="model", description=f"step {best} of {train_run}: " + ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()), attrs={"train_run": train_run, "step": str(best), **{k: f"{v['accuracy']:.2f}" for k, v in scores.items()}}, card=card, parents=[ckpt.artifact_version_id], ) return art.version # {{/docs-fragment promote}} # {{docs-fragment driver}} @driver_env.task(report=True) async def train_and_watch( profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, wait_minutes: int = 40, ) -> str: """Train in the background, redraw the leaderboard as scores arrive, then promote the winner.""" train_run = flyte.ctx().action.run_name started = time.time() trainer = asyncio.create_task(finetune(train_run=train_run, profile=profile, train_examples=train_examples, n_checkpoints=n_checkpoints, learning_rate=learning_rate)) info, rows, deadline = None, {}, None while True: rows = await collect_results(train_run) times = await checkpoint_times(train_run) if trainer.done() and info is None: info = json.loads(trainer.result()) # re-raises if training failed deadline = time.time() + wait_minutes * 60 expected = len(info["steps"]) if info else n_checkpoints + 1 await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=False), do_flush=True) if info and (len(rows) >= expected or time.time() > deadline): break await asyncio.sleep(30) best = pick_best(rows) release = await promote(train_run, rows, best["step"]) if best else None await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=True, release=release), do_flush=True) return json.dumps({"best_step": best["step"] if best else None, "release_version": release, "evaluated": sorted(rows), "expected": info["steps"]}) # {{/docs-fragment driver}} @driver_env.task(report=True) async def refresh_leaderboard(train_run: str) -> str: """Redraw the leaderboard for a finished training run, for example after a backfill.""" rows = await collect_results(train_run) times = await checkpoint_times(train_run) await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, min(times.values()), None, len(times), final=True), do_flush=True) best = pick_best(rows) return json.dumps({"best_step": best["step"] if best else None, "evaluated": sorted(rows)}) # {{docs-fragment run}} if __name__ == "__main__": import evals flyte.init_from_config() if "--leaderboard" in sys.argv: run = flyte.run(refresh_leaderboard, train_run=sys.argv[sys.argv.index("--leaderboard") + 1]) else: # The evaluator must be deployed, with its trigger active, before the first checkpoint lands. flyte.deploy(evals.eval_env) if "--smoke" in sys.argv: run = flyte.run(train_and_watch, profile="smoke", train_examples=1_600, n_checkpoints=2, wait_minutes=20) else: run = flyte.run(train_and_watch) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/train.py* `train.py` deploys the evaluator first, because its trigger has to be active before the first checkpoint is published. You can also deploy it on its own with `python evals.py`, or with `flyte deploy evals.py eval_env`. The first run builds two images. The GPU image, with vLLM, transformers and datasets, takes a while to build; later runs reuse it. `--smoke` trains on 1,600 problems, publishes step 0 and two checkpoints, and scores 40 problems per benchmark, which takes about three minutes once the images exist. Forty problems are too few for the ship rule, so a smoke run usually ends without a release candidate. ## The shared contract The two sides agree on artifact names and a benchmark registry. Every benchmark has a version. Bumping one benchmark's version re-scores only that benchmark on every checkpoint, and the others stay cached. ``` """Names, models, benchmarks and images shared by the trainer and the evaluator. The trainer and the evaluator are deployed and run separately. They share only what is in this file: the artifact names that connect them and the container images. """ import flyte # {{docs-fragment names}} BASE_MODEL = "HuggingFaceTB/SmolLM2-360M" # The trainer publishes every checkpoint as a new version of this artifact, partitioned by # training run, step and profile ("full" or "smoke"). CHECKPOINT_ARTIFACT = "math-sft-checkpoint" # Every eval run publishes its scores as a new version of this artifact, same partitions. RESULTS_ARTIFACT = "math-sft-checkpoint-evals" # The checkpoint that wins the ship rule is promoted to this artifact. RELEASE_ARTIFACT = "math-sft-release-candidate" # {{/docs-fragment names}} # {{docs-fragment benchmarks}} # One entry per benchmark slice. Bump a benchmark's version to re-score only that benchmark on # every checkpoint; the other benchmarks stay cached. `limit` is the full-profile sample size. BENCHMARKS = { "gsm8k": {"kind": "generate", "version": "1", "limit": 0, "label": "GSM8K (exact match)", "role": "target"}, "arc_easy": {"kind": "choice", "version": "1", "limit": 0, "label": "ARC-Easy (MC)", "role": "reasoning"}, "mmlu": {"kind": "choice", "version": "1", "limit": 2000, "label": "MMLU (MC)", "role": "guard"}, } DEFAULT_SUITE = ["gsm8k", "arc_easy", "mmlu"] SMOKE_LIMIT = 40 # The ship rule: the best GSM8K checkpoint whose MMLU score is at most this many points below # the base model's. GUARD_BENCHMARK = "mmlu" GUARD_MAX_DROP = 2.0 # {{/docs-fragment benchmarks}} # {{docs-fragment images}} # One GPU image trains the model, generates with vLLM, and scores multiple choice with transformers. gpu_image = ( flyte.Image.from_debian_base(name="ckpt-evals-gpu", python_version=(3, 12)) .with_pip_packages("vllm==0.33.0", "transformers==5.19.0", "datasets>=4.0.0", "accelerate") ) # Drivers, reports and artifact bookkeeping need nothing but flyte. driver_image = flyte.Image.from_debian_base(name="ckpt-evals-driver", python_version=(3, 12)) # {{/docs-fragment images}} CODE2 """Names, models, benchmarks and images shared by the trainer and the evaluator. The trainer and the evaluator are deployed and run separately. They share only what is in this file: the artifact names that connect them and the container images. """ import flyte # {{docs-fragment names}} BASE_MODEL = "HuggingFaceTB/SmolLM2-360M" # The trainer publishes every checkpoint as a new version of this artifact, partitioned by # training run, step and profile ("full" or "smoke"). CHECKPOINT_ARTIFACT = "math-sft-checkpoint" # Every eval run publishes its scores as a new version of this artifact, same partitions. RESULTS_ARTIFACT = "math-sft-checkpoint-evals" # The checkpoint that wins the ship rule is promoted to this artifact. RELEASE_ARTIFACT = "math-sft-release-candidate" # {{/docs-fragment names}} # {{docs-fragment benchmarks}} # One entry per benchmark slice. Bump a benchmark's version to re-score only that benchmark on # every checkpoint; the other benchmarks stay cached. `limit` is the full-profile sample size. BENCHMARKS = { "gsm8k": {"kind": "generate", "version": "1", "limit": 0, "label": "GSM8K (exact match)", "role": "target"}, "arc_easy": {"kind": "choice", "version": "1", "limit": 0, "label": "ARC-Easy (MC)", "role": "reasoning"}, "mmlu": {"kind": "choice", "version": "1", "limit": 2000, "label": "MMLU (MC)", "role": "guard"}, } DEFAULT_SUITE = ["gsm8k", "arc_easy", "mmlu"] SMOKE_LIMIT = 40 # The ship rule: the best GSM8K checkpoint whose MMLU score is at most this many points below # the base model's. GUARD_BENCHMARK = "mmlu" GUARD_MAX_DROP = 2.0 # {{/docs-fragment benchmarks}} # {{docs-fragment images}} # One GPU image trains the model, generates with vLLM, and scores multiple choice with transformers. gpu_image = ( flyte.Image.from_debian_base(name="ckpt-evals-gpu", python_version=(3, 12)) .with_pip_packages("vllm==0.33.0", "transformers==5.19.0", "datasets>=4.0.0", "accelerate") ) # Drivers, reports and artifact bookkeeping need nothing but flyte. driver_image = flyte.Image.from_debian_base(name="ckpt-evals-driver", python_version=(3, 12)) # {{/docs-fragment images}} CODE3 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Fine-tune a small model on math and publish every checkpoint as an artifact version. train_and_watch (CPU driver, live leaderboard report) โ””โ”€ finetune (L40S): SFT SmolLM2-360M on MetaMathQA step 0, then 8 checkpoints โ”€โ”€> Artifact.create(math-sft-checkpoint, step=...) โ”‚ (the evaluator's trigger runs each one) <โ”€โ”€ polls math-sft-checkpoint-evals, redraws curves, picks and promotes the best The trainer never calls the evaluator. It publishes checkpoints and keeps training; the evaluator's artifact trigger (see evals.py) launches one eval run per checkpoint. The driver only reads the published scores to draw learning curves and promote a release candidate. python train.py # deploy the evaluator, then train (about 20 minutes) python train.py --smoke # 2 checkpoints, 40 problems per benchmark python train.py --leaderboard # redraw the leaderboard after a backfill """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from config import ( BASE_MODEL, CHECKPOINT_ARTIFACT, RELEASE_ARTIFACT, RESULTS_ARTIFACT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import leaderboard_html, pick_best, release_card, training_html # {{docs-fragment envs}} train_env = flyte.TaskEnvironment( name="ckpt-evals-train", image=gpu_image, resources=flyte.Resources(cpu=6, memory="48Gi", gpu="L40s:1", disk="80Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) driver_env = flyte.TaskEnvironment( name="ckpt-evals-driver", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[train_env], ) # {{/docs-fragment envs}} def checkpoint_steps(total: int, n: int) -> list[int]: """Step 0, then ``n`` checkpoints spaced closer early on, where the curves move fastest.""" fracs = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 3 / 8, 1 / 2, 3 / 4, 1][-n:] if n <= 8 else [k / n for k in range(1, n + 1)] return [0] + sorted({max(1, round(f * total)) for f in fracs}) def load_sft_data(tok, n: int, max_len: int, seed: int) -> list[tuple[list[int], int]]: """MetaMathQA's GSM8K-derived problems as (token ids, prompt length) in the eval prompt format.""" from benchmarks import SFT_PROMPT from datasets import load_dataset ds = load_dataset("meta-math/MetaMathQA", split="train") ds = ds.filter(lambda t: t.startswith("GSM"), input_columns="type").shuffle(seed=seed).select(range(n)) out = [] for q, a in zip(ds["query"], ds["response"]): prompt = tok.encode(SFT_PROMPT.format(question=q), add_special_tokens=False) answer = tok.encode(" " + a.strip(), add_special_tokens=False) + [tok.eos_token_id] out.append(((prompt + answer)[:max_len], len(prompt))) return out # {{docs-fragment publish}} async def publish_checkpoint(path: str, step: int, train_run: str, profile: str, loss: float | None) -> str: """Upload a saved checkpoint and register it as a new version of the checkpoint artifact. The evaluator's trigger fires on this call; training does not wait for it. """ from flyte.remote import Artifact ckpt = await Dir.from_local(path) art = await Artifact.create.aio( ckpt, name=CHECKPOINT_ARTIFACT, version=f"{train_run}-step{step:05d}", kind="model", description=f"{BASE_MODEL} math SFT, step {step} of {train_run}", partitions={"train_run": train_run, "step": str(step), "profile": profile}, attrs={"base_model": BASE_MODEL, "train_loss": f"{loss:.4f}" if loss is not None else "n/a"}, ) return art.version # {{/docs-fragment publish}} # {{docs-fragment finetune}} @train_env.task(report=True) async def finetune( train_run: str, profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, micro_batch: int = 8, grad_accum: int = 4, max_len: int = 512, seed: int = 0, ) -> str: """Full fine-tune on one GPU; save and publish checkpoints without pausing for uploads.""" import math import os import random import torch from safetensors.torch import save_file from transformers import AutoModelForCausalLM, AutoTokenizer torch.manual_seed(seed) tok = AutoTokenizer.from_pretrained(BASE_MODEL) model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.float32).cuda() data = load_sft_data(tok, train_examples, max_len, seed) total = len(data) // (micro_batch * grad_accum) save_at = checkpoint_steps(total, n_checkpoints) opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, betas=(0.9, 0.95), weight_decay=0.0) warmup = max(1, total // 30) def lr_at(s: int) -> float: # linear warmup, cosine decay to 10% if s < warmup: return learning_rate * (s + 1) / warmup return learning_rate * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total - warmup)))) loop = asyncio.get_running_loop() uploads: list = [] history: list[dict] = [] published: list[dict] = [] started = time.time() def save(step: int, loss: float | None) -> None: # Saving takes seconds and runs on the training thread. Uploading and publishing run on # the event loop, so the next optimizer step starts right away. path = f"/tmp/ckpt/step-{step:05d}" os.makedirs(path, exist_ok=True) sd = {k: v.detach().to(torch.bfloat16).cpu().contiguous() for k, v in model.state_dict().items() if not (model.config.tie_word_embeddings and k == "lm_head.weight")} save_file(sd, f"{path}/model.safetensors", metadata={"format": "pt"}) model.config.save_pretrained(path) model.generation_config.save_pretrained(path) tok.save_pretrained(path) published.append({"step": step, "loss": loss, "saved_s": round(time.time() - started, 1)}) uploads.append(asyncio.run_coroutine_threadsafe( publish_checkpoint(path, step, train_run, profile, loss), loop)) def train() -> None: model.train() order = list(range(len(data))) random.Random(seed).shuffle(order) save(0, None) for step in range(1, total + 1): for g in opt.param_groups: g["lr"] = lr_at(step - 1) step_loss = 0.0 for m in range(grad_accum): lo = ((step - 1) * grad_accum + m) * micro_batch batch = [data[i] for i in order[lo:lo + micro_batch]] width = max(len(ids) for ids, _ in batch) x = torch.full((len(batch), width), tok.pad_token_id or tok.eos_token_id) y = torch.full((len(batch), width), -100) mask = torch.zeros((len(batch), width), dtype=torch.long) for r, (ids, plen) in enumerate(batch): x[r, :len(ids)] = torch.tensor(ids) mask[r, :len(ids)] = 1 y[r, plen:len(ids)] = torch.tensor(ids[plen:]) # loss on the answer only with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=x.cuda(), attention_mask=mask.cuda(), labels=y.cuda()).loss / grad_accum loss.backward() step_loss += loss.item() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() opt.zero_grad(set_to_none=True) if step % 10 == 0 or step == total: history.append({"step": step, "loss": round(step_loss, 4), "lr": lr_at(step - 1), "elapsed_s": round(time.time() - started, 1)}) if step in save_at: save(step, step_loss) if step % 25 == 0 or step in save_at: flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() await asyncio.to_thread(train) versions = await asyncio.gather(*[asyncio.wrap_future(u) for u in uploads]) flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() return json.dumps({"steps": save_at, "versions": versions, "history": history, "published": published, "total_steps": total, "train_s": round(time.time() - started, 1)}) # {{/docs-fragment finetune}} # {{docs-fragment collect}} async def collect_results(train_run: str) -> dict[int, dict]: """The newest published scores for each checkpoint of one training run, keyed by step.""" from flyte.remote import Artifact rows: dict[int, dict] = {} async for art in Artifact.listall.aio(name=RESULTS_ARTIFACT, train_run=train_run): step = int(art.partitions["step"]) if step in rows: # listall is newest first; a backfill publishes a newer version continue f = await art.to_python.aio(File) async with f.open("rb") as fh: rows[step] = json.loads(bytes(await fh.read())) rows[step]["published_at"] = art.pb2.created_at.ToDatetime().timestamp() return rows async def checkpoint_times(train_run: str) -> dict[int, float]: from flyte.remote import Artifact return {int(a.partitions["step"]): a.pb2.created_at.ToDatetime().timestamp() async for a in Artifact.listall.aio(name=CHECKPOINT_ARTIFACT, train_run=train_run)} # {{/docs-fragment collect}} # {{docs-fragment promote}} async def promote(train_run: str, rows: dict[int, dict], best: int) -> str: """Publish the winning checkpoint again, as the release-candidate artifact with a model card.""" from flyte.remote import Artifact ckpt = await Artifact.get.aio(CHECKPOINT_ARTIFACT, train_run=train_run, step=str(best)) card = await artifacts.Card.create_from.aio(content=release_card(train_run, rows, best), format="html", card_type="model") scores = rows[best]["scores"] art = await Artifact.create.aio( await ckpt.to_python.aio(Dir), name=RELEASE_ARTIFACT, version=f"{train_run}-step{best:05d}", kind="model", description=f"step {best} of {train_run}: " + ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()), attrs={"train_run": train_run, "step": str(best), **{k: f"{v['accuracy']:.2f}" for k, v in scores.items()}}, card=card, parents=[ckpt.artifact_version_id], ) return art.version # {{/docs-fragment promote}} # {{docs-fragment driver}} @driver_env.task(report=True) async def train_and_watch( profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, wait_minutes: int = 40, ) -> str: """Train in the background, redraw the leaderboard as scores arrive, then promote the winner.""" train_run = flyte.ctx().action.run_name started = time.time() trainer = asyncio.create_task(finetune(train_run=train_run, profile=profile, train_examples=train_examples, n_checkpoints=n_checkpoints, learning_rate=learning_rate)) info, rows, deadline = None, {}, None while True: rows = await collect_results(train_run) times = await checkpoint_times(train_run) if trainer.done() and info is None: info = json.loads(trainer.result()) # re-raises if training failed deadline = time.time() + wait_minutes * 60 expected = len(info["steps"]) if info else n_checkpoints + 1 await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=False), do_flush=True) if info and (len(rows) >= expected or time.time() > deadline): break await asyncio.sleep(30) best = pick_best(rows) release = await promote(train_run, rows, best["step"]) if best else None await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=True, release=release), do_flush=True) return json.dumps({"best_step": best["step"] if best else None, "release_version": release, "evaluated": sorted(rows), "expected": info["steps"]}) # {{/docs-fragment driver}} @driver_env.task(report=True) async def refresh_leaderboard(train_run: str) -> str: """Redraw the leaderboard for a finished training run, for example after a backfill.""" rows = await collect_results(train_run) times = await checkpoint_times(train_run) await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, min(times.values()), None, len(times), final=True), do_flush=True) best = pick_best(rows) return json.dumps({"best_step": best["step"] if best else None, "evaluated": sorted(rows)}) # {{docs-fragment run}} if __name__ == "__main__": import evals flyte.init_from_config() if "--leaderboard" in sys.argv: run = flyte.run(refresh_leaderboard, train_run=sys.argv[sys.argv.index("--leaderboard") + 1]) else: # The evaluator must be deployed, with its trigger active, before the first checkpoint lands. flyte.deploy(evals.eval_env) if "--smoke" in sys.argv: run = flyte.run(train_and_watch, profile="smoke", train_examples=1_600, n_checkpoints=2, wait_minutes=20) else: run = flyte.run(train_and_watch) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/train.py* `finetune` is a plain PyTorch loop: full fine-tuning in bf16 autocast, AdamW, a short warmup and a cosine decay, and the loss on the answer tokens only. The training data is the GSM8K-derived part of [MetaMathQA](https://huggingface.co/datasets/meta-math/MetaMathQA), in the same `Question: ... Answer:` format the evals use. SmolLM2-360M is small enough to fine-tune in minutes, and weak enough at math that the learning curve has room to move. Checkpoints are spaced closer early on, where the curves move fastest, and step 0 is the base model, so the base model goes through exactly the same eval path as every checkpoint. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Fine-tune a small model on math and publish every checkpoint as an artifact version. train_and_watch (CPU driver, live leaderboard report) โ””โ”€ finetune (L40S): SFT SmolLM2-360M on MetaMathQA step 0, then 8 checkpoints โ”€โ”€> Artifact.create(math-sft-checkpoint, step=...) โ”‚ (the evaluator's trigger runs each one) <โ”€โ”€ polls math-sft-checkpoint-evals, redraws curves, picks and promotes the best The trainer never calls the evaluator. It publishes checkpoints and keeps training; the evaluator's artifact trigger (see evals.py) launches one eval run per checkpoint. The driver only reads the published scores to draw learning curves and promote a release candidate. python train.py # deploy the evaluator, then train (about 20 minutes) python train.py --smoke # 2 checkpoints, 40 problems per benchmark python train.py --leaderboard # redraw the leaderboard after a backfill """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from config import ( BASE_MODEL, CHECKPOINT_ARTIFACT, RELEASE_ARTIFACT, RESULTS_ARTIFACT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import leaderboard_html, pick_best, release_card, training_html # {{docs-fragment envs}} train_env = flyte.TaskEnvironment( name="ckpt-evals-train", image=gpu_image, resources=flyte.Resources(cpu=6, memory="48Gi", gpu="L40s:1", disk="80Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) driver_env = flyte.TaskEnvironment( name="ckpt-evals-driver", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[train_env], ) # {{/docs-fragment envs}} def checkpoint_steps(total: int, n: int) -> list[int]: """Step 0, then ``n`` checkpoints spaced closer early on, where the curves move fastest.""" fracs = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 3 / 8, 1 / 2, 3 / 4, 1][-n:] if n <= 8 else [k / n for k in range(1, n + 1)] return [0] + sorted({max(1, round(f * total)) for f in fracs}) def load_sft_data(tok, n: int, max_len: int, seed: int) -> list[tuple[list[int], int]]: """MetaMathQA's GSM8K-derived problems as (token ids, prompt length) in the eval prompt format.""" from benchmarks import SFT_PROMPT from datasets import load_dataset ds = load_dataset("meta-math/MetaMathQA", split="train") ds = ds.filter(lambda t: t.startswith("GSM"), input_columns="type").shuffle(seed=seed).select(range(n)) out = [] for q, a in zip(ds["query"], ds["response"]): prompt = tok.encode(SFT_PROMPT.format(question=q), add_special_tokens=False) answer = tok.encode(" " + a.strip(), add_special_tokens=False) + [tok.eos_token_id] out.append(((prompt + answer)[:max_len], len(prompt))) return out # {{docs-fragment publish}} async def publish_checkpoint(path: str, step: int, train_run: str, profile: str, loss: float | None) -> str: """Upload a saved checkpoint and register it as a new version of the checkpoint artifact. The evaluator's trigger fires on this call; training does not wait for it. """ from flyte.remote import Artifact ckpt = await Dir.from_local(path) art = await Artifact.create.aio( ckpt, name=CHECKPOINT_ARTIFACT, version=f"{train_run}-step{step:05d}", kind="model", description=f"{BASE_MODEL} math SFT, step {step} of {train_run}", partitions={"train_run": train_run, "step": str(step), "profile": profile}, attrs={"base_model": BASE_MODEL, "train_loss": f"{loss:.4f}" if loss is not None else "n/a"}, ) return art.version # {{/docs-fragment publish}} # {{docs-fragment finetune}} @train_env.task(report=True) async def finetune( train_run: str, profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, micro_batch: int = 8, grad_accum: int = 4, max_len: int = 512, seed: int = 0, ) -> str: """Full fine-tune on one GPU; save and publish checkpoints without pausing for uploads.""" import math import os import random import torch from safetensors.torch import save_file from transformers import AutoModelForCausalLM, AutoTokenizer torch.manual_seed(seed) tok = AutoTokenizer.from_pretrained(BASE_MODEL) model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.float32).cuda() data = load_sft_data(tok, train_examples, max_len, seed) total = len(data) // (micro_batch * grad_accum) save_at = checkpoint_steps(total, n_checkpoints) opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, betas=(0.9, 0.95), weight_decay=0.0) warmup = max(1, total // 30) def lr_at(s: int) -> float: # linear warmup, cosine decay to 10% if s < warmup: return learning_rate * (s + 1) / warmup return learning_rate * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total - warmup)))) loop = asyncio.get_running_loop() uploads: list = [] history: list[dict] = [] published: list[dict] = [] started = time.time() def save(step: int, loss: float | None) -> None: # Saving takes seconds and runs on the training thread. Uploading and publishing run on # the event loop, so the next optimizer step starts right away. path = f"/tmp/ckpt/step-{step:05d}" os.makedirs(path, exist_ok=True) sd = {k: v.detach().to(torch.bfloat16).cpu().contiguous() for k, v in model.state_dict().items() if not (model.config.tie_word_embeddings and k == "lm_head.weight")} save_file(sd, f"{path}/model.safetensors", metadata={"format": "pt"}) model.config.save_pretrained(path) model.generation_config.save_pretrained(path) tok.save_pretrained(path) published.append({"step": step, "loss": loss, "saved_s": round(time.time() - started, 1)}) uploads.append(asyncio.run_coroutine_threadsafe( publish_checkpoint(path, step, train_run, profile, loss), loop)) def train() -> None: model.train() order = list(range(len(data))) random.Random(seed).shuffle(order) save(0, None) for step in range(1, total + 1): for g in opt.param_groups: g["lr"] = lr_at(step - 1) step_loss = 0.0 for m in range(grad_accum): lo = ((step - 1) * grad_accum + m) * micro_batch batch = [data[i] for i in order[lo:lo + micro_batch]] width = max(len(ids) for ids, _ in batch) x = torch.full((len(batch), width), tok.pad_token_id or tok.eos_token_id) y = torch.full((len(batch), width), -100) mask = torch.zeros((len(batch), width), dtype=torch.long) for r, (ids, plen) in enumerate(batch): x[r, :len(ids)] = torch.tensor(ids) mask[r, :len(ids)] = 1 y[r, plen:len(ids)] = torch.tensor(ids[plen:]) # loss on the answer only with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=x.cuda(), attention_mask=mask.cuda(), labels=y.cuda()).loss / grad_accum loss.backward() step_loss += loss.item() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() opt.zero_grad(set_to_none=True) if step % 10 == 0 or step == total: history.append({"step": step, "loss": round(step_loss, 4), "lr": lr_at(step - 1), "elapsed_s": round(time.time() - started, 1)}) if step in save_at: save(step, step_loss) if step % 25 == 0 or step in save_at: flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() await asyncio.to_thread(train) versions = await asyncio.gather(*[asyncio.wrap_future(u) for u in uploads]) flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() return json.dumps({"steps": save_at, "versions": versions, "history": history, "published": published, "total_steps": total, "train_s": round(time.time() - started, 1)}) # {{/docs-fragment finetune}} # {{docs-fragment collect}} async def collect_results(train_run: str) -> dict[int, dict]: """The newest published scores for each checkpoint of one training run, keyed by step.""" from flyte.remote import Artifact rows: dict[int, dict] = {} async for art in Artifact.listall.aio(name=RESULTS_ARTIFACT, train_run=train_run): step = int(art.partitions["step"]) if step in rows: # listall is newest first; a backfill publishes a newer version continue f = await art.to_python.aio(File) async with f.open("rb") as fh: rows[step] = json.loads(bytes(await fh.read())) rows[step]["published_at"] = art.pb2.created_at.ToDatetime().timestamp() return rows async def checkpoint_times(train_run: str) -> dict[int, float]: from flyte.remote import Artifact return {int(a.partitions["step"]): a.pb2.created_at.ToDatetime().timestamp() async for a in Artifact.listall.aio(name=CHECKPOINT_ARTIFACT, train_run=train_run)} # {{/docs-fragment collect}} # {{docs-fragment promote}} async def promote(train_run: str, rows: dict[int, dict], best: int) -> str: """Publish the winning checkpoint again, as the release-candidate artifact with a model card.""" from flyte.remote import Artifact ckpt = await Artifact.get.aio(CHECKPOINT_ARTIFACT, train_run=train_run, step=str(best)) card = await artifacts.Card.create_from.aio(content=release_card(train_run, rows, best), format="html", card_type="model") scores = rows[best]["scores"] art = await Artifact.create.aio( await ckpt.to_python.aio(Dir), name=RELEASE_ARTIFACT, version=f"{train_run}-step{best:05d}", kind="model", description=f"step {best} of {train_run}: " + ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()), attrs={"train_run": train_run, "step": str(best), **{k: f"{v['accuracy']:.2f}" for k, v in scores.items()}}, card=card, parents=[ckpt.artifact_version_id], ) return art.version # {{/docs-fragment promote}} # {{docs-fragment driver}} @driver_env.task(report=True) async def train_and_watch( profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, wait_minutes: int = 40, ) -> str: """Train in the background, redraw the leaderboard as scores arrive, then promote the winner.""" train_run = flyte.ctx().action.run_name started = time.time() trainer = asyncio.create_task(finetune(train_run=train_run, profile=profile, train_examples=train_examples, n_checkpoints=n_checkpoints, learning_rate=learning_rate)) info, rows, deadline = None, {}, None while True: rows = await collect_results(train_run) times = await checkpoint_times(train_run) if trainer.done() and info is None: info = json.loads(trainer.result()) # re-raises if training failed deadline = time.time() + wait_minutes * 60 expected = len(info["steps"]) if info else n_checkpoints + 1 await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=False), do_flush=True) if info and (len(rows) >= expected or time.time() > deadline): break await asyncio.sleep(30) best = pick_best(rows) release = await promote(train_run, rows, best["step"]) if best else None await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=True, release=release), do_flush=True) return json.dumps({"best_step": best["step"] if best else None, "release_version": release, "evaluated": sorted(rows), "expected": info["steps"]}) # {{/docs-fragment driver}} @driver_env.task(report=True) async def refresh_leaderboard(train_run: str) -> str: """Redraw the leaderboard for a finished training run, for example after a backfill.""" rows = await collect_results(train_run) times = await checkpoint_times(train_run) await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, min(times.values()), None, len(times), final=True), do_flush=True) best = pick_best(rows) return json.dumps({"best_step": best["step"] if best else None, "evaluated": sorted(rows)}) # {{docs-fragment run}} if __name__ == "__main__": import evals flyte.init_from_config() if "--leaderboard" in sys.argv: run = flyte.run(refresh_leaderboard, train_run=sys.argv[sys.argv.index("--leaderboard") + 1]) else: # The evaluator must be deployed, with its trigger active, before the first checkpoint lands. flyte.deploy(evals.eval_env) if "--smoke" in sys.argv: run = flyte.run(train_and_watch, profile="smoke", train_examples=1_600, n_checkpoints=2, wait_minutes=20) else: run = flyte.run(train_and_watch) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/train.py* The training loop runs in a thread (`asyncio.to_thread`). When it saves a checkpoint, it hands the upload to the task's event loop with `asyncio.run_coroutine_threadsafe` and goes straight on to the next step. `publish_checkpoint` uploads the directory and creates a new version of the checkpoint artifact. The partitions carry the training run, the step, and the profile. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Fine-tune a small model on math and publish every checkpoint as an artifact version. train_and_watch (CPU driver, live leaderboard report) โ””โ”€ finetune (L40S): SFT SmolLM2-360M on MetaMathQA step 0, then 8 checkpoints โ”€โ”€> Artifact.create(math-sft-checkpoint, step=...) โ”‚ (the evaluator's trigger runs each one) <โ”€โ”€ polls math-sft-checkpoint-evals, redraws curves, picks and promotes the best The trainer never calls the evaluator. It publishes checkpoints and keeps training; the evaluator's artifact trigger (see evals.py) launches one eval run per checkpoint. The driver only reads the published scores to draw learning curves and promote a release candidate. python train.py # deploy the evaluator, then train (about 20 minutes) python train.py --smoke # 2 checkpoints, 40 problems per benchmark python train.py --leaderboard # redraw the leaderboard after a backfill """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from config import ( BASE_MODEL, CHECKPOINT_ARTIFACT, RELEASE_ARTIFACT, RESULTS_ARTIFACT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import leaderboard_html, pick_best, release_card, training_html # {{docs-fragment envs}} train_env = flyte.TaskEnvironment( name="ckpt-evals-train", image=gpu_image, resources=flyte.Resources(cpu=6, memory="48Gi", gpu="L40s:1", disk="80Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) driver_env = flyte.TaskEnvironment( name="ckpt-evals-driver", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[train_env], ) # {{/docs-fragment envs}} def checkpoint_steps(total: int, n: int) -> list[int]: """Step 0, then ``n`` checkpoints spaced closer early on, where the curves move fastest.""" fracs = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 3 / 8, 1 / 2, 3 / 4, 1][-n:] if n <= 8 else [k / n for k in range(1, n + 1)] return [0] + sorted({max(1, round(f * total)) for f in fracs}) def load_sft_data(tok, n: int, max_len: int, seed: int) -> list[tuple[list[int], int]]: """MetaMathQA's GSM8K-derived problems as (token ids, prompt length) in the eval prompt format.""" from benchmarks import SFT_PROMPT from datasets import load_dataset ds = load_dataset("meta-math/MetaMathQA", split="train") ds = ds.filter(lambda t: t.startswith("GSM"), input_columns="type").shuffle(seed=seed).select(range(n)) out = [] for q, a in zip(ds["query"], ds["response"]): prompt = tok.encode(SFT_PROMPT.format(question=q), add_special_tokens=False) answer = tok.encode(" " + a.strip(), add_special_tokens=False) + [tok.eos_token_id] out.append(((prompt + answer)[:max_len], len(prompt))) return out # {{docs-fragment publish}} async def publish_checkpoint(path: str, step: int, train_run: str, profile: str, loss: float | None) -> str: """Upload a saved checkpoint and register it as a new version of the checkpoint artifact. The evaluator's trigger fires on this call; training does not wait for it. """ from flyte.remote import Artifact ckpt = await Dir.from_local(path) art = await Artifact.create.aio( ckpt, name=CHECKPOINT_ARTIFACT, version=f"{train_run}-step{step:05d}", kind="model", description=f"{BASE_MODEL} math SFT, step {step} of {train_run}", partitions={"train_run": train_run, "step": str(step), "profile": profile}, attrs={"base_model": BASE_MODEL, "train_loss": f"{loss:.4f}" if loss is not None else "n/a"}, ) return art.version # {{/docs-fragment publish}} # {{docs-fragment finetune}} @train_env.task(report=True) async def finetune( train_run: str, profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, micro_batch: int = 8, grad_accum: int = 4, max_len: int = 512, seed: int = 0, ) -> str: """Full fine-tune on one GPU; save and publish checkpoints without pausing for uploads.""" import math import os import random import torch from safetensors.torch import save_file from transformers import AutoModelForCausalLM, AutoTokenizer torch.manual_seed(seed) tok = AutoTokenizer.from_pretrained(BASE_MODEL) model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.float32).cuda() data = load_sft_data(tok, train_examples, max_len, seed) total = len(data) // (micro_batch * grad_accum) save_at = checkpoint_steps(total, n_checkpoints) opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, betas=(0.9, 0.95), weight_decay=0.0) warmup = max(1, total // 30) def lr_at(s: int) -> float: # linear warmup, cosine decay to 10% if s < warmup: return learning_rate * (s + 1) / warmup return learning_rate * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total - warmup)))) loop = asyncio.get_running_loop() uploads: list = [] history: list[dict] = [] published: list[dict] = [] started = time.time() def save(step: int, loss: float | None) -> None: # Saving takes seconds and runs on the training thread. Uploading and publishing run on # the event loop, so the next optimizer step starts right away. path = f"/tmp/ckpt/step-{step:05d}" os.makedirs(path, exist_ok=True) sd = {k: v.detach().to(torch.bfloat16).cpu().contiguous() for k, v in model.state_dict().items() if not (model.config.tie_word_embeddings and k == "lm_head.weight")} save_file(sd, f"{path}/model.safetensors", metadata={"format": "pt"}) model.config.save_pretrained(path) model.generation_config.save_pretrained(path) tok.save_pretrained(path) published.append({"step": step, "loss": loss, "saved_s": round(time.time() - started, 1)}) uploads.append(asyncio.run_coroutine_threadsafe( publish_checkpoint(path, step, train_run, profile, loss), loop)) def train() -> None: model.train() order = list(range(len(data))) random.Random(seed).shuffle(order) save(0, None) for step in range(1, total + 1): for g in opt.param_groups: g["lr"] = lr_at(step - 1) step_loss = 0.0 for m in range(grad_accum): lo = ((step - 1) * grad_accum + m) * micro_batch batch = [data[i] for i in order[lo:lo + micro_batch]] width = max(len(ids) for ids, _ in batch) x = torch.full((len(batch), width), tok.pad_token_id or tok.eos_token_id) y = torch.full((len(batch), width), -100) mask = torch.zeros((len(batch), width), dtype=torch.long) for r, (ids, plen) in enumerate(batch): x[r, :len(ids)] = torch.tensor(ids) mask[r, :len(ids)] = 1 y[r, plen:len(ids)] = torch.tensor(ids[plen:]) # loss on the answer only with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=x.cuda(), attention_mask=mask.cuda(), labels=y.cuda()).loss / grad_accum loss.backward() step_loss += loss.item() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() opt.zero_grad(set_to_none=True) if step % 10 == 0 or step == total: history.append({"step": step, "loss": round(step_loss, 4), "lr": lr_at(step - 1), "elapsed_s": round(time.time() - started, 1)}) if step in save_at: save(step, step_loss) if step % 25 == 0 or step in save_at: flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() await asyncio.to_thread(train) versions = await asyncio.gather(*[asyncio.wrap_future(u) for u in uploads]) flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() return json.dumps({"steps": save_at, "versions": versions, "history": history, "published": published, "total_steps": total, "train_s": round(time.time() - started, 1)}) # {{/docs-fragment finetune}} # {{docs-fragment collect}} async def collect_results(train_run: str) -> dict[int, dict]: """The newest published scores for each checkpoint of one training run, keyed by step.""" from flyte.remote import Artifact rows: dict[int, dict] = {} async for art in Artifact.listall.aio(name=RESULTS_ARTIFACT, train_run=train_run): step = int(art.partitions["step"]) if step in rows: # listall is newest first; a backfill publishes a newer version continue f = await art.to_python.aio(File) async with f.open("rb") as fh: rows[step] = json.loads(bytes(await fh.read())) rows[step]["published_at"] = art.pb2.created_at.ToDatetime().timestamp() return rows async def checkpoint_times(train_run: str) -> dict[int, float]: from flyte.remote import Artifact return {int(a.partitions["step"]): a.pb2.created_at.ToDatetime().timestamp() async for a in Artifact.listall.aio(name=CHECKPOINT_ARTIFACT, train_run=train_run)} # {{/docs-fragment collect}} # {{docs-fragment promote}} async def promote(train_run: str, rows: dict[int, dict], best: int) -> str: """Publish the winning checkpoint again, as the release-candidate artifact with a model card.""" from flyte.remote import Artifact ckpt = await Artifact.get.aio(CHECKPOINT_ARTIFACT, train_run=train_run, step=str(best)) card = await artifacts.Card.create_from.aio(content=release_card(train_run, rows, best), format="html", card_type="model") scores = rows[best]["scores"] art = await Artifact.create.aio( await ckpt.to_python.aio(Dir), name=RELEASE_ARTIFACT, version=f"{train_run}-step{best:05d}", kind="model", description=f"step {best} of {train_run}: " + ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()), attrs={"train_run": train_run, "step": str(best), **{k: f"{v['accuracy']:.2f}" for k, v in scores.items()}}, card=card, parents=[ckpt.artifact_version_id], ) return art.version # {{/docs-fragment promote}} # {{docs-fragment driver}} @driver_env.task(report=True) async def train_and_watch( profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, wait_minutes: int = 40, ) -> str: """Train in the background, redraw the leaderboard as scores arrive, then promote the winner.""" train_run = flyte.ctx().action.run_name started = time.time() trainer = asyncio.create_task(finetune(train_run=train_run, profile=profile, train_examples=train_examples, n_checkpoints=n_checkpoints, learning_rate=learning_rate)) info, rows, deadline = None, {}, None while True: rows = await collect_results(train_run) times = await checkpoint_times(train_run) if trainer.done() and info is None: info = json.loads(trainer.result()) # re-raises if training failed deadline = time.time() + wait_minutes * 60 expected = len(info["steps"]) if info else n_checkpoints + 1 await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=False), do_flush=True) if info and (len(rows) >= expected or time.time() > deadline): break await asyncio.sleep(30) best = pick_best(rows) release = await promote(train_run, rows, best["step"]) if best else None await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=True, release=release), do_flush=True) return json.dumps({"best_step": best["step"] if best else None, "release_version": release, "evaluated": sorted(rows), "expected": info["steps"]}) # {{/docs-fragment driver}} @driver_env.task(report=True) async def refresh_leaderboard(train_run: str) -> str: """Redraw the leaderboard for a finished training run, for example after a backfill.""" rows = await collect_results(train_run) times = await checkpoint_times(train_run) await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, min(times.values()), None, len(times), final=True), do_flush=True) best = pick_best(rows) return json.dumps({"best_step": best["step"] if best else None, "evaluated": sorted(rows)}) # {{docs-fragment run}} if __name__ == "__main__": import evals flyte.init_from_config() if "--leaderboard" in sys.argv: run = flyte.run(refresh_leaderboard, train_run=sys.argv[sys.argv.index("--leaderboard") + 1]) else: # The evaluator must be deployed, with its trigger active, before the first checkpoint lands. flyte.deploy(evals.eval_env) if "--smoke" in sys.argv: run = flyte.run(train_and_watch, profile="smoke", train_examples=1_600, n_checkpoints=2, wait_minutes=20) else: run = flyte.run(train_and_watch) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/train.py* `Artifact.create` publishes from anywhere: a task, a notebook, or another system's job. The more common way to publish an artifact is to return `flyte.artifacts.new(...)` from a task, which the evaluator does with its scores. A checkpoint is not a task output, though. It appears in the middle of a task, and the eval for it should start right away. ## The evaluator runs on every new version The evaluator has three environments: a small CPU driver, an L4 for generative evals with vLLM, and an L4 for multiple-choice evals with transformers. The two L4 environments use the same image as the trainer. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Evaluate every checkpoint: an eval suite that runs itself whenever a checkpoint is published. new version of math-sft-checkpoint โ”€โ”€(OnArtifact trigger)โ”€โ”€> evaluate_checkpoint โ”œโ”€ run_generate gsm8k (L4 GPU, vLLM) โ”œโ”€ run_choice arc_easy (L4 GPU, log-likelihood) โ””โ”€ run_choice mmlu (L4 GPU, log-likelihood, the regression guard) -> publish scores as a new version of math-sft-checkpoint-evals The evaluator knows nothing about the trainer. It is deployed once, and its trigger launches one eval run per new checkpoint version, while training keeps going. Each benchmark result is cached per (checkpoint, benchmark, benchmark version), so re-evaluating old checkpoints with a new benchmark only runs the new one. python evals.py # deploy the evaluator and its trigger python evals.py --backfill arc_challenge # add a benchmark to every checkpoint # (register it in config.BENCHMARKS first) """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from benchmarks import load_items, score_choice, score_generate from config import ( BENCHMARKS, CHECKPOINT_ARTIFACT, DEFAULT_SUITE, RESULTS_ARTIFACT, SMOKE_LIMIT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import scorecard_html # {{docs-fragment envs}} # Generative evals: one L4 per (checkpoint, benchmark). vLLM runs in the task's process, and # uses PyTorch's sampler instead of FlashInfer's, which would JIT-compile with nvcc at startup. generate_env = flyte.TaskEnvironment( name="ckpt-evals-generate", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"VLLM_ENABLE_V1_MULTIPROCESSING": "0", "VLLM_USE_FLASHINFER_SAMPLER": "0", "TOKENIZERS_PARALLELISM": "false"}, ) # Multiple-choice evals score every answer option's log-likelihood, one L4 per benchmark. choice_env = flyte.TaskEnvironment( name="ckpt-evals-choice", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) eval_env = flyte.TaskEnvironment( name="ckpt-evals", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[generate_env, choice_env], ) # The cache key is the task inputs (checkpoint, benchmark, benchmark version, limit) under one # explicit cache version, so editing a report does not throw away finished evals. EVAL_CACHE = flyte.Cache("override", version_override="checkpoint-evals-1") # {{/docs-fragment envs}} # {{docs-fragment benchmark_tasks}} @generate_env.task(cache=EVAL_CACHE, retries=1) def run_generate(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one generative benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_generate(model_dir, load_items(benchmark, limit, version), version)) @choice_env.task(cache=EVAL_CACHE, retries=1) def run_choice(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one multiple-choice benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_choice(model_dir, load_items(benchmark, limit, version), benchmark, version)) # {{/docs-fragment benchmark_tasks}} # {{docs-fragment trigger}} on_checkpoint = flyte.Trigger( name="eval_new_checkpoint", description="Run the eval suite on every new version of the math SFT checkpoint", automation=flyte.OnArtifact(name=CHECKPOINT_ARTIFACT), inputs={ "checkpoint": flyte.TriggeredArtifact, "step": flyte.TriggeredPartition("step"), "train_run": flyte.TriggeredPartition("train_run"), "profile": flyte.TriggeredPartition("profile"), }, ) # {{/docs-fragment trigger}} # {{docs-fragment evaluate}} @eval_env.task(triggers=[on_checkpoint], report=True, produces_artifacts=True) async def evaluate_checkpoint( checkpoint: Dir, step: str, train_run: str, profile: str = "full", suite: list[str] = DEFAULT_SUITE ) -> File: """Fan the suite out over one checkpoint and publish the scores as an artifact version.""" started = time.time() calls = [] for name in suite: spec = BENCHMARKS[name] limit = SMOKE_LIMIT if profile == "smoke" else spec["limit"] task = run_generate if spec["kind"] == "generate" else run_choice calls.append(task.aio(checkpoint=checkpoint, benchmark=name, version=spec["version"], limit=limit)) scores = {s["benchmark"]: s for s in map(json.loads, await asyncio.gather(*calls))} result = {"train_run": train_run, "step": int(step), "profile": profile, "checkpoint": checkpoint.path, "eval_run": flyte.ctx().action.run_name, "started_at": started, "finished_at": time.time(), "scores": scores} await flyte.report.replace.aio(scorecard_html(result), do_flush=True) path = "/tmp/scores.json" with open(path, "w") as f: json.dump(result, f) summary = ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()) return artifacts.new(await File.from_local(path), artifacts.Metadata( name=RESULTS_ARTIFACT, description=f"step {int(step)} of {train_run}: {summary}", partitions={"train_run": train_run, "step": step, "profile": profile}, attrs={k: f"{v['accuracy']:.2f}" for k, v in scores.items()}, )) # {{/docs-fragment evaluate}} # {{docs-fragment backfill}} def backfill(train_run: str, extra: list[str]) -> list[str]: """Re-run the suite plus ``extra`` benchmarks on every checkpoint of one training run. Benchmarks that already ran on a checkpoint come back from the cache; only ``extra`` runs. """ from flyte.remote import Artifact unknown = [b for b in extra if b not in BENCHMARKS] if unknown: raise ValueError(f"add {unknown} to BENCHMARKS in config.py before backfilling") suite = DEFAULT_SUITE + [b for b in extra if b not in DEFAULT_SUITE] urls = [] for art in Artifact.listall(name=CHECKPOINT_ARTIFACT, train_run=train_run, latest_per_partition=True): p = art.partitions run = flyte.run(evaluate_checkpoint, checkpoint=art, step=p["step"], train_run=train_run, profile=p["profile"], suite=suite) urls.append(run.url) return urls # {{/docs-fragment backfill}} if __name__ == "__main__": flyte.init_from_config() if "--backfill" in sys.argv: i = sys.argv.index("--backfill") for url in backfill(sys.argv[i + 1], sys.argv[i + 2:]): print(url) else: # Deploying registers the tasks and activates the trigger. flyte.deploy(eval_env) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/evals.py* The trigger watches the checkpoint artifact. `flyte.TriggeredArtifact` binds the new version's value, a `flyte.io.Dir`, to the `checkpoint` input. `flyte.TriggeredPartition` binds partition values to the other inputs. `flyte.OnArtifact` can also filter on partition values, for example `flyte.OnArtifact(CHECKPOINT_ARTIFACT, profile="full")` to skip smoke runs. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Evaluate every checkpoint: an eval suite that runs itself whenever a checkpoint is published. new version of math-sft-checkpoint โ”€โ”€(OnArtifact trigger)โ”€โ”€> evaluate_checkpoint โ”œโ”€ run_generate gsm8k (L4 GPU, vLLM) โ”œโ”€ run_choice arc_easy (L4 GPU, log-likelihood) โ””โ”€ run_choice mmlu (L4 GPU, log-likelihood, the regression guard) -> publish scores as a new version of math-sft-checkpoint-evals The evaluator knows nothing about the trainer. It is deployed once, and its trigger launches one eval run per new checkpoint version, while training keeps going. Each benchmark result is cached per (checkpoint, benchmark, benchmark version), so re-evaluating old checkpoints with a new benchmark only runs the new one. python evals.py # deploy the evaluator and its trigger python evals.py --backfill arc_challenge # add a benchmark to every checkpoint # (register it in config.BENCHMARKS first) """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from benchmarks import load_items, score_choice, score_generate from config import ( BENCHMARKS, CHECKPOINT_ARTIFACT, DEFAULT_SUITE, RESULTS_ARTIFACT, SMOKE_LIMIT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import scorecard_html # {{docs-fragment envs}} # Generative evals: one L4 per (checkpoint, benchmark). vLLM runs in the task's process, and # uses PyTorch's sampler instead of FlashInfer's, which would JIT-compile with nvcc at startup. generate_env = flyte.TaskEnvironment( name="ckpt-evals-generate", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"VLLM_ENABLE_V1_MULTIPROCESSING": "0", "VLLM_USE_FLASHINFER_SAMPLER": "0", "TOKENIZERS_PARALLELISM": "false"}, ) # Multiple-choice evals score every answer option's log-likelihood, one L4 per benchmark. choice_env = flyte.TaskEnvironment( name="ckpt-evals-choice", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) eval_env = flyte.TaskEnvironment( name="ckpt-evals", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[generate_env, choice_env], ) # The cache key is the task inputs (checkpoint, benchmark, benchmark version, limit) under one # explicit cache version, so editing a report does not throw away finished evals. EVAL_CACHE = flyte.Cache("override", version_override="checkpoint-evals-1") # {{/docs-fragment envs}} # {{docs-fragment benchmark_tasks}} @generate_env.task(cache=EVAL_CACHE, retries=1) def run_generate(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one generative benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_generate(model_dir, load_items(benchmark, limit, version), version)) @choice_env.task(cache=EVAL_CACHE, retries=1) def run_choice(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one multiple-choice benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_choice(model_dir, load_items(benchmark, limit, version), benchmark, version)) # {{/docs-fragment benchmark_tasks}} # {{docs-fragment trigger}} on_checkpoint = flyte.Trigger( name="eval_new_checkpoint", description="Run the eval suite on every new version of the math SFT checkpoint", automation=flyte.OnArtifact(name=CHECKPOINT_ARTIFACT), inputs={ "checkpoint": flyte.TriggeredArtifact, "step": flyte.TriggeredPartition("step"), "train_run": flyte.TriggeredPartition("train_run"), "profile": flyte.TriggeredPartition("profile"), }, ) # {{/docs-fragment trigger}} # {{docs-fragment evaluate}} @eval_env.task(triggers=[on_checkpoint], report=True, produces_artifacts=True) async def evaluate_checkpoint( checkpoint: Dir, step: str, train_run: str, profile: str = "full", suite: list[str] = DEFAULT_SUITE ) -> File: """Fan the suite out over one checkpoint and publish the scores as an artifact version.""" started = time.time() calls = [] for name in suite: spec = BENCHMARKS[name] limit = SMOKE_LIMIT if profile == "smoke" else spec["limit"] task = run_generate if spec["kind"] == "generate" else run_choice calls.append(task.aio(checkpoint=checkpoint, benchmark=name, version=spec["version"], limit=limit)) scores = {s["benchmark"]: s for s in map(json.loads, await asyncio.gather(*calls))} result = {"train_run": train_run, "step": int(step), "profile": profile, "checkpoint": checkpoint.path, "eval_run": flyte.ctx().action.run_name, "started_at": started, "finished_at": time.time(), "scores": scores} await flyte.report.replace.aio(scorecard_html(result), do_flush=True) path = "/tmp/scores.json" with open(path, "w") as f: json.dump(result, f) summary = ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()) return artifacts.new(await File.from_local(path), artifacts.Metadata( name=RESULTS_ARTIFACT, description=f"step {int(step)} of {train_run}: {summary}", partitions={"train_run": train_run, "step": step, "profile": profile}, attrs={k: f"{v['accuracy']:.2f}" for k, v in scores.items()}, )) # {{/docs-fragment evaluate}} # {{docs-fragment backfill}} def backfill(train_run: str, extra: list[str]) -> list[str]: """Re-run the suite plus ``extra`` benchmarks on every checkpoint of one training run. Benchmarks that already ran on a checkpoint come back from the cache; only ``extra`` runs. """ from flyte.remote import Artifact unknown = [b for b in extra if b not in BENCHMARKS] if unknown: raise ValueError(f"add {unknown} to BENCHMARKS in config.py before backfilling") suite = DEFAULT_SUITE + [b for b in extra if b not in DEFAULT_SUITE] urls = [] for art in Artifact.listall(name=CHECKPOINT_ARTIFACT, train_run=train_run, latest_per_partition=True): p = art.partitions run = flyte.run(evaluate_checkpoint, checkpoint=art, step=p["step"], train_run=train_run, profile=p["profile"], suite=suite) urls.append(run.url) return urls # {{/docs-fragment backfill}} if __name__ == "__main__": flyte.init_from_config() if "--backfill" in sys.argv: i = sys.argv.index("--backfill") for url in backfill(sys.argv[i + 1], sys.argv[i + 2:]): print(url) else: # Deploying registers the tasks and activates the trigger. flyte.deploy(eval_env) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/evals.py* `evaluate_checkpoint` fans the suite out, one task per benchmark, and publishes the merged scores as a version of the results artifact, with the same partitions as the checkpoint. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Evaluate every checkpoint: an eval suite that runs itself whenever a checkpoint is published. new version of math-sft-checkpoint โ”€โ”€(OnArtifact trigger)โ”€โ”€> evaluate_checkpoint โ”œโ”€ run_generate gsm8k (L4 GPU, vLLM) โ”œโ”€ run_choice arc_easy (L4 GPU, log-likelihood) โ””โ”€ run_choice mmlu (L4 GPU, log-likelihood, the regression guard) -> publish scores as a new version of math-sft-checkpoint-evals The evaluator knows nothing about the trainer. It is deployed once, and its trigger launches one eval run per new checkpoint version, while training keeps going. Each benchmark result is cached per (checkpoint, benchmark, benchmark version), so re-evaluating old checkpoints with a new benchmark only runs the new one. python evals.py # deploy the evaluator and its trigger python evals.py --backfill arc_challenge # add a benchmark to every checkpoint # (register it in config.BENCHMARKS first) """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from benchmarks import load_items, score_choice, score_generate from config import ( BENCHMARKS, CHECKPOINT_ARTIFACT, DEFAULT_SUITE, RESULTS_ARTIFACT, SMOKE_LIMIT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import scorecard_html # {{docs-fragment envs}} # Generative evals: one L4 per (checkpoint, benchmark). vLLM runs in the task's process, and # uses PyTorch's sampler instead of FlashInfer's, which would JIT-compile with nvcc at startup. generate_env = flyte.TaskEnvironment( name="ckpt-evals-generate", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"VLLM_ENABLE_V1_MULTIPROCESSING": "0", "VLLM_USE_FLASHINFER_SAMPLER": "0", "TOKENIZERS_PARALLELISM": "false"}, ) # Multiple-choice evals score every answer option's log-likelihood, one L4 per benchmark. choice_env = flyte.TaskEnvironment( name="ckpt-evals-choice", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) eval_env = flyte.TaskEnvironment( name="ckpt-evals", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[generate_env, choice_env], ) # The cache key is the task inputs (checkpoint, benchmark, benchmark version, limit) under one # explicit cache version, so editing a report does not throw away finished evals. EVAL_CACHE = flyte.Cache("override", version_override="checkpoint-evals-1") # {{/docs-fragment envs}} # {{docs-fragment benchmark_tasks}} @generate_env.task(cache=EVAL_CACHE, retries=1) def run_generate(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one generative benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_generate(model_dir, load_items(benchmark, limit, version), version)) @choice_env.task(cache=EVAL_CACHE, retries=1) def run_choice(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one multiple-choice benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_choice(model_dir, load_items(benchmark, limit, version), benchmark, version)) # {{/docs-fragment benchmark_tasks}} # {{docs-fragment trigger}} on_checkpoint = flyte.Trigger( name="eval_new_checkpoint", description="Run the eval suite on every new version of the math SFT checkpoint", automation=flyte.OnArtifact(name=CHECKPOINT_ARTIFACT), inputs={ "checkpoint": flyte.TriggeredArtifact, "step": flyte.TriggeredPartition("step"), "train_run": flyte.TriggeredPartition("train_run"), "profile": flyte.TriggeredPartition("profile"), }, ) # {{/docs-fragment trigger}} # {{docs-fragment evaluate}} @eval_env.task(triggers=[on_checkpoint], report=True, produces_artifacts=True) async def evaluate_checkpoint( checkpoint: Dir, step: str, train_run: str, profile: str = "full", suite: list[str] = DEFAULT_SUITE ) -> File: """Fan the suite out over one checkpoint and publish the scores as an artifact version.""" started = time.time() calls = [] for name in suite: spec = BENCHMARKS[name] limit = SMOKE_LIMIT if profile == "smoke" else spec["limit"] task = run_generate if spec["kind"] == "generate" else run_choice calls.append(task.aio(checkpoint=checkpoint, benchmark=name, version=spec["version"], limit=limit)) scores = {s["benchmark"]: s for s in map(json.loads, await asyncio.gather(*calls))} result = {"train_run": train_run, "step": int(step), "profile": profile, "checkpoint": checkpoint.path, "eval_run": flyte.ctx().action.run_name, "started_at": started, "finished_at": time.time(), "scores": scores} await flyte.report.replace.aio(scorecard_html(result), do_flush=True) path = "/tmp/scores.json" with open(path, "w") as f: json.dump(result, f) summary = ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()) return artifacts.new(await File.from_local(path), artifacts.Metadata( name=RESULTS_ARTIFACT, description=f"step {int(step)} of {train_run}: {summary}", partitions={"train_run": train_run, "step": step, "profile": profile}, attrs={k: f"{v['accuracy']:.2f}" for k, v in scores.items()}, )) # {{/docs-fragment evaluate}} # {{docs-fragment backfill}} def backfill(train_run: str, extra: list[str]) -> list[str]: """Re-run the suite plus ``extra`` benchmarks on every checkpoint of one training run. Benchmarks that already ran on a checkpoint come back from the cache; only ``extra`` runs. """ from flyte.remote import Artifact unknown = [b for b in extra if b not in BENCHMARKS] if unknown: raise ValueError(f"add {unknown} to BENCHMARKS in config.py before backfilling") suite = DEFAULT_SUITE + [b for b in extra if b not in DEFAULT_SUITE] urls = [] for art in Artifact.listall(name=CHECKPOINT_ARTIFACT, train_run=train_run, latest_per_partition=True): p = art.partitions run = flyte.run(evaluate_checkpoint, checkpoint=art, step=p["step"], train_run=train_run, profile=p["profile"], suite=suite) urls.append(run.url) return urls # {{/docs-fragment backfill}} if __name__ == "__main__": flyte.init_from_config() if "--backfill" in sys.argv: i = sys.argv.index("--backfill") for url in backfill(sys.argv[i + 1], sys.argv[i + 2:]): print(url) else: # Deploying registers the tasks and activates the trigger. flyte.deploy(eval_env) CODE4 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Evaluate every checkpoint: an eval suite that runs itself whenever a checkpoint is published. new version of math-sft-checkpoint โ”€โ”€(OnArtifact trigger)โ”€โ”€> evaluate_checkpoint โ”œโ”€ run_generate gsm8k (L4 GPU, vLLM) โ”œโ”€ run_choice arc_easy (L4 GPU, log-likelihood) โ””โ”€ run_choice mmlu (L4 GPU, log-likelihood, the regression guard) -> publish scores as a new version of math-sft-checkpoint-evals The evaluator knows nothing about the trainer. It is deployed once, and its trigger launches one eval run per new checkpoint version, while training keeps going. Each benchmark result is cached per (checkpoint, benchmark, benchmark version), so re-evaluating old checkpoints with a new benchmark only runs the new one. python evals.py # deploy the evaluator and its trigger python evals.py --backfill arc_challenge # add a benchmark to every checkpoint # (register it in config.BENCHMARKS first) """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from benchmarks import load_items, score_choice, score_generate from config import ( BENCHMARKS, CHECKPOINT_ARTIFACT, DEFAULT_SUITE, RESULTS_ARTIFACT, SMOKE_LIMIT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import scorecard_html # {{docs-fragment envs}} # Generative evals: one L4 per (checkpoint, benchmark). vLLM runs in the task's process, and # uses PyTorch's sampler instead of FlashInfer's, which would JIT-compile with nvcc at startup. generate_env = flyte.TaskEnvironment( name="ckpt-evals-generate", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"VLLM_ENABLE_V1_MULTIPROCESSING": "0", "VLLM_USE_FLASHINFER_SAMPLER": "0", "TOKENIZERS_PARALLELISM": "false"}, ) # Multiple-choice evals score every answer option's log-likelihood, one L4 per benchmark. choice_env = flyte.TaskEnvironment( name="ckpt-evals-choice", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) eval_env = flyte.TaskEnvironment( name="ckpt-evals", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[generate_env, choice_env], ) # The cache key is the task inputs (checkpoint, benchmark, benchmark version, limit) under one # explicit cache version, so editing a report does not throw away finished evals. EVAL_CACHE = flyte.Cache("override", version_override="checkpoint-evals-1") # {{/docs-fragment envs}} # {{docs-fragment benchmark_tasks}} @generate_env.task(cache=EVAL_CACHE, retries=1) def run_generate(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one generative benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_generate(model_dir, load_items(benchmark, limit, version), version)) @choice_env.task(cache=EVAL_CACHE, retries=1) def run_choice(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one multiple-choice benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_choice(model_dir, load_items(benchmark, limit, version), benchmark, version)) # {{/docs-fragment benchmark_tasks}} # {{docs-fragment trigger}} on_checkpoint = flyte.Trigger( name="eval_new_checkpoint", description="Run the eval suite on every new version of the math SFT checkpoint", automation=flyte.OnArtifact(name=CHECKPOINT_ARTIFACT), inputs={ "checkpoint": flyte.TriggeredArtifact, "step": flyte.TriggeredPartition("step"), "train_run": flyte.TriggeredPartition("train_run"), "profile": flyte.TriggeredPartition("profile"), }, ) # {{/docs-fragment trigger}} # {{docs-fragment evaluate}} @eval_env.task(triggers=[on_checkpoint], report=True, produces_artifacts=True) async def evaluate_checkpoint( checkpoint: Dir, step: str, train_run: str, profile: str = "full", suite: list[str] = DEFAULT_SUITE ) -> File: """Fan the suite out over one checkpoint and publish the scores as an artifact version.""" started = time.time() calls = [] for name in suite: spec = BENCHMARKS[name] limit = SMOKE_LIMIT if profile == "smoke" else spec["limit"] task = run_generate if spec["kind"] == "generate" else run_choice calls.append(task.aio(checkpoint=checkpoint, benchmark=name, version=spec["version"], limit=limit)) scores = {s["benchmark"]: s for s in map(json.loads, await asyncio.gather(*calls))} result = {"train_run": train_run, "step": int(step), "profile": profile, "checkpoint": checkpoint.path, "eval_run": flyte.ctx().action.run_name, "started_at": started, "finished_at": time.time(), "scores": scores} await flyte.report.replace.aio(scorecard_html(result), do_flush=True) path = "/tmp/scores.json" with open(path, "w") as f: json.dump(result, f) summary = ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()) return artifacts.new(await File.from_local(path), artifacts.Metadata( name=RESULTS_ARTIFACT, description=f"step {int(step)} of {train_run}: {summary}", partitions={"train_run": train_run, "step": step, "profile": profile}, attrs={k: f"{v['accuracy']:.2f}" for k, v in scores.items()}, )) # {{/docs-fragment evaluate}} # {{docs-fragment backfill}} def backfill(train_run: str, extra: list[str]) -> list[str]: """Re-run the suite plus ``extra`` benchmarks on every checkpoint of one training run. Benchmarks that already ran on a checkpoint come back from the cache; only ``extra`` runs. """ from flyte.remote import Artifact unknown = [b for b in extra if b not in BENCHMARKS] if unknown: raise ValueError(f"add {unknown} to BENCHMARKS in config.py before backfilling") suite = DEFAULT_SUITE + [b for b in extra if b not in DEFAULT_SUITE] urls = [] for art in Artifact.listall(name=CHECKPOINT_ARTIFACT, train_run=train_run, latest_per_partition=True): p = art.partitions run = flyte.run(evaluate_checkpoint, checkpoint=art, step=p["step"], train_run=train_run, profile=p["profile"], suite=suite) urls.append(run.url) return urls # {{/docs-fragment backfill}} if __name__ == "__main__": flyte.init_from_config() if "--backfill" in sys.argv: i = sys.argv.index("--backfill") for url in backfill(sys.argv[i + 1], sys.argv[i + 2:]): print(url) else: # Deploying registers the tasks and activates the trigger. flyte.deploy(eval_env) CODE5 """Benchmark slices: loading, prompts, answer extraction and scoring. Every function imports its heavy dependencies inside, so this module imports cleanly in the driver image too. The prompt format matches the one the trainer uses for SFT, so the base model (step 0) and every checkpoint see exactly the same prompts. """ import math import random import re import time SFT_PROMPT = "Question: {question}\nAnswer:" # MMLU as a regression guard measures general knowledge, so it leaves out the math subjects the # SFT data trains on. MATH_SUBJECTS = ("math", "algebra", "statistics") # ARC prompt versions, selected by the benchmark version in config.BENCHMARKS. v1 is the usual # cloze prompt, which is also exactly the SFT prompt. v2 ends with the phrase that precedes the # final answer in the training data instead; the tutorial bumps ARC-Easy to it in a backfill. ARC_PROMPTS = {"1": "Question: {question}\nAnswer:", "2": "Question: {question}\nThe answer is:"} def _sample(n: int, limit: int, seed: int = 0) -> list[int]: idx = list(range(n)) if limit and limit < n: idx = sorted(random.Random(seed).sample(idx, limit)) return idx # {{docs-fragment load}} def load_items(benchmark: str, limit: int, version: str = "1") -> list[dict]: """A fixed, seeded slice of one benchmark's test split as plain dicts.""" from datasets import load_dataset if benchmark == "gsm8k": ds = load_dataset("openai/gsm8k", "main", split="test") rows = [ds[i] for i in _sample(len(ds), limit)] return [{"question": r["question"], "gold": r["answer"].split("####")[-1].strip().replace(",", "")} for r in rows] if benchmark in ("arc_easy", "arc_challenge"): name = "ARC-Easy" if benchmark == "arc_easy" else "ARC-Challenge" ds = load_dataset("allenai/ai2_arc", name, split="test") rows = [ds[i] for i in _sample(len(ds), limit)] prompt = ARC_PROMPTS[version] return [{"context": prompt.format(question=r["question"].strip()), "choices": list(r["choices"]["text"]), "gold": list(r["choices"]["label"]).index(r["answerKey"])} for r in rows] if benchmark == "mmlu": ds = load_dataset("cais/mmlu", "all", split="test") keep = [i for i, s in enumerate(ds["subject"]) if not any(m in s for m in MATH_SUBJECTS)] rows = [ds[keep[j]] for j in _sample(len(keep), limit)] return [{"context": f"The following is a question about {r['subject'].replace('_', ' ')}.\n\n" f"Question: {r['question'].strip()}\nAnswer:", "choices": list(r["choices"]), "gold": int(r["answer"])} for r in rows] raise ValueError(f"unknown benchmark {benchmark!r}") # {{/docs-fragment load}} # {{docs-fragment extract}} _NUM = r"-?\d[\d,]*(?:\.\d+)?" def extract_answer(text: str) -> str | None: """The final number: after "The answer is" if the model says it, else the last number.""" # This takes the first "answer is", not the last. Fine-tuned outputs say it once, at the end. # The published GSM8K v1 scores were computed this way; switching to the last match changes # results, so do it together with a GSM8K version bump. m = re.search(rf"answer is:?\s*\$?\s*({_NUM})", text, flags=re.IGNORECASE) if m is None: nums = re.findall(_NUM, text) if not nums: return None found = nums[-1] else: found = m.group(1) found = found.replace(",", "").rstrip(".") try: v = float(found) except ValueError: return None return str(int(v)) if v.is_integer() else str(v) # {{/docs-fragment extract}} def _summary(benchmark: str, version: str, correct: list[bool], seconds: float, examples: list[dict]) -> dict: n = len(correct) acc = sum(correct) / max(n, 1) return {"benchmark": benchmark, "version": version, "n": n, "correct": int(sum(correct)), "accuracy": round(100 * acc, 2), "stderr": round(100 * math.sqrt(acc * (1 - acc) / max(n, 1)), 2), "seconds": round(seconds, 1), "examples": examples} # {{docs-fragment generate}} def score_generate(model_dir: str, items: list[dict], version: str, n_examples: int = 24) -> dict: """GSM8K: greedy generation with vLLM, exact match on the final number.""" from vllm import LLM, SamplingParams started = time.time() llm = LLM(model=model_dir, dtype="bfloat16", max_model_len=2048, gpu_memory_utilization=0.85, enforce_eager=True, seed=0) params = SamplingParams(temperature=0.0, max_tokens=400, stop=["\nQuestion:", "\n\n\n"]) outs = llm.generate([SFT_PROMPT.format(question=it["question"]) for it in items], params) texts = [o.outputs[0].text.strip() for o in outs] preds = [extract_answer(t) for t in texts] correct = [p is not None and float(p) == float(it["gold"]) for p, it in zip(preds, items)] examples = [{"question": it["question"], "gold": it["gold"], "pred": p, "ok": ok, "output": t[:900]} for it, p, ok, t in list(zip(items, preds, correct, texts))[:n_examples]] return _summary("gsm8k", version, correct, time.time() - started, examples) # {{/docs-fragment generate}} # {{docs-fragment choice}} def score_choice(model_dir: str, items: list[dict], benchmark: str, version: str, batch_tokens: int = 24_576) -> dict: """Multiple choice in the cloze form: pick the answer text with the highest log-likelihood. Small models score near chance when they have to answer with a letter, so this scores each option's own text after the question, normalized by its length in characters (as OLMES does for small models). """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer started = time.time() tok = AutoTokenizer.from_pretrained(model_dir) model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16).cuda().eval() pairs = [] # (item index, token ids, number of answer tokens, answer length in characters) for i, it in enumerate(items): ctx = tok.encode(it["context"], add_special_tokens=False) for choice in it["choices"]: ans = tok.encode(" " + choice.strip(), add_special_tokens=False) pairs.append((i, (ctx + ans)[-1024:], len(ans), max(1, len(choice.strip())))) score = [0.0] * len(pairs) pad = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id order = sorted(range(len(pairs)), key=lambda k: len(pairs[k][1])) # batch similar lengths with torch.inference_mode(): b = 0 while b < len(order): # Sorted by length, so the last row is the widest: fill the batch up to a token budget. n = max(1, batch_tokens // len(pairs[order[min(b + 255, len(order) - 1)]][1])) ks = order[b:b + min(n, 256)] b += len(ks) ids = [pairs[k][1] for k in ks] width = max(len(t) for t in ids) # Right padding keeps position ids exact for every row. x = torch.tensor([t + [pad] * (width - len(t)) for t in ids]).cuda() mask = torch.tensor([[1] * len(t) + [0] * (width - len(t)) for t in ids]).cuda() logp = torch.log_softmax(model(input_ids=x, attention_mask=mask).logits.float(), dim=-1) for r, k in enumerate(ks): _, t, n_ans, n_chars = pairs[k] pos = torch.arange(len(t) - n_ans, len(t), device=x.device) score[k] = logp[r, pos - 1, x[r, pos]].sum().item() / n_chars # token t is predicted at t-1 by_item: list[list[float]] = [[] for _ in items] for k, (i, _, _, _) in enumerate(pairs): # pairs are in item, then option, order by_item[i].append(score[k]) correct = [max(range(len(sc)), key=sc.__getitem__) == it["gold"] for sc, it in zip(by_item, items)] return _summary(benchmark, version, correct, time.time() - started, []) # {{/docs-fragment choice}} CODE6 """Benchmark slices: loading, prompts, answer extraction and scoring. Every function imports its heavy dependencies inside, so this module imports cleanly in the driver image too. The prompt format matches the one the trainer uses for SFT, so the base model (step 0) and every checkpoint see exactly the same prompts. """ import math import random import re import time SFT_PROMPT = "Question: {question}\nAnswer:" # MMLU as a regression guard measures general knowledge, so it leaves out the math subjects the # SFT data trains on. MATH_SUBJECTS = ("math", "algebra", "statistics") # ARC prompt versions, selected by the benchmark version in config.BENCHMARKS. v1 is the usual # cloze prompt, which is also exactly the SFT prompt. v2 ends with the phrase that precedes the # final answer in the training data instead; the tutorial bumps ARC-Easy to it in a backfill. ARC_PROMPTS = {"1": "Question: {question}\nAnswer:", "2": "Question: {question}\nThe answer is:"} def _sample(n: int, limit: int, seed: int = 0) -> list[int]: idx = list(range(n)) if limit and limit < n: idx = sorted(random.Random(seed).sample(idx, limit)) return idx # {{docs-fragment load}} def load_items(benchmark: str, limit: int, version: str = "1") -> list[dict]: """A fixed, seeded slice of one benchmark's test split as plain dicts.""" from datasets import load_dataset if benchmark == "gsm8k": ds = load_dataset("openai/gsm8k", "main", split="test") rows = [ds[i] for i in _sample(len(ds), limit)] return [{"question": r["question"], "gold": r["answer"].split("####")[-1].strip().replace(",", "")} for r in rows] if benchmark in ("arc_easy", "arc_challenge"): name = "ARC-Easy" if benchmark == "arc_easy" else "ARC-Challenge" ds = load_dataset("allenai/ai2_arc", name, split="test") rows = [ds[i] for i in _sample(len(ds), limit)] prompt = ARC_PROMPTS[version] return [{"context": prompt.format(question=r["question"].strip()), "choices": list(r["choices"]["text"]), "gold": list(r["choices"]["label"]).index(r["answerKey"])} for r in rows] if benchmark == "mmlu": ds = load_dataset("cais/mmlu", "all", split="test") keep = [i for i, s in enumerate(ds["subject"]) if not any(m in s for m in MATH_SUBJECTS)] rows = [ds[keep[j]] for j in _sample(len(keep), limit)] return [{"context": f"The following is a question about {r['subject'].replace('_', ' ')}.\n\n" f"Question: {r['question'].strip()}\nAnswer:", "choices": list(r["choices"]), "gold": int(r["answer"])} for r in rows] raise ValueError(f"unknown benchmark {benchmark!r}") # {{/docs-fragment load}} # {{docs-fragment extract}} _NUM = r"-?\d[\d,]*(?:\.\d+)?" def extract_answer(text: str) -> str | None: """The final number: after "The answer is" if the model says it, else the last number.""" # This takes the first "answer is", not the last. Fine-tuned outputs say it once, at the end. # The published GSM8K v1 scores were computed this way; switching to the last match changes # results, so do it together with a GSM8K version bump. m = re.search(rf"answer is:?\s*\$?\s*({_NUM})", text, flags=re.IGNORECASE) if m is None: nums = re.findall(_NUM, text) if not nums: return None found = nums[-1] else: found = m.group(1) found = found.replace(",", "").rstrip(".") try: v = float(found) except ValueError: return None return str(int(v)) if v.is_integer() else str(v) # {{/docs-fragment extract}} def _summary(benchmark: str, version: str, correct: list[bool], seconds: float, examples: list[dict]) -> dict: n = len(correct) acc = sum(correct) / max(n, 1) return {"benchmark": benchmark, "version": version, "n": n, "correct": int(sum(correct)), "accuracy": round(100 * acc, 2), "stderr": round(100 * math.sqrt(acc * (1 - acc) / max(n, 1)), 2), "seconds": round(seconds, 1), "examples": examples} # {{docs-fragment generate}} def score_generate(model_dir: str, items: list[dict], version: str, n_examples: int = 24) -> dict: """GSM8K: greedy generation with vLLM, exact match on the final number.""" from vllm import LLM, SamplingParams started = time.time() llm = LLM(model=model_dir, dtype="bfloat16", max_model_len=2048, gpu_memory_utilization=0.85, enforce_eager=True, seed=0) params = SamplingParams(temperature=0.0, max_tokens=400, stop=["\nQuestion:", "\n\n\n"]) outs = llm.generate([SFT_PROMPT.format(question=it["question"]) for it in items], params) texts = [o.outputs[0].text.strip() for o in outs] preds = [extract_answer(t) for t in texts] correct = [p is not None and float(p) == float(it["gold"]) for p, it in zip(preds, items)] examples = [{"question": it["question"], "gold": it["gold"], "pred": p, "ok": ok, "output": t[:900]} for it, p, ok, t in list(zip(items, preds, correct, texts))[:n_examples]] return _summary("gsm8k", version, correct, time.time() - started, examples) # {{/docs-fragment generate}} # {{docs-fragment choice}} def score_choice(model_dir: str, items: list[dict], benchmark: str, version: str, batch_tokens: int = 24_576) -> dict: """Multiple choice in the cloze form: pick the answer text with the highest log-likelihood. Small models score near chance when they have to answer with a letter, so this scores each option's own text after the question, normalized by its length in characters (as OLMES does for small models). """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer started = time.time() tok = AutoTokenizer.from_pretrained(model_dir) model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16).cuda().eval() pairs = [] # (item index, token ids, number of answer tokens, answer length in characters) for i, it in enumerate(items): ctx = tok.encode(it["context"], add_special_tokens=False) for choice in it["choices"]: ans = tok.encode(" " + choice.strip(), add_special_tokens=False) pairs.append((i, (ctx + ans)[-1024:], len(ans), max(1, len(choice.strip())))) score = [0.0] * len(pairs) pad = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id order = sorted(range(len(pairs)), key=lambda k: len(pairs[k][1])) # batch similar lengths with torch.inference_mode(): b = 0 while b < len(order): # Sorted by length, so the last row is the widest: fill the batch up to a token budget. n = max(1, batch_tokens // len(pairs[order[min(b + 255, len(order) - 1)]][1])) ks = order[b:b + min(n, 256)] b += len(ks) ids = [pairs[k][1] for k in ks] width = max(len(t) for t in ids) # Right padding keeps position ids exact for every row. x = torch.tensor([t + [pad] * (width - len(t)) for t in ids]).cuda() mask = torch.tensor([[1] * len(t) + [0] * (width - len(t)) for t in ids]).cuda() logp = torch.log_softmax(model(input_ids=x, attention_mask=mask).logits.float(), dim=-1) for r, k in enumerate(ks): _, t, n_ans, n_chars = pairs[k] pos = torch.arange(len(t) - n_ans, len(t), device=x.device) score[k] = logp[r, pos - 1, x[r, pos]].sum().item() / n_chars # token t is predicted at t-1 by_item: list[list[float]] = [[] for _ in items] for k, (i, _, _, _) in enumerate(pairs): # pairs are in item, then option, order by_item[i].append(score[k]) correct = [max(range(len(sc)), key=sc.__getitem__) == it["gold"] for sc, it in zip(by_item, items)] return _summary(benchmark, version, correct, time.time() - started, []) # {{/docs-fragment choice}} CODE7 """Benchmark slices: loading, prompts, answer extraction and scoring. Every function imports its heavy dependencies inside, so this module imports cleanly in the driver image too. The prompt format matches the one the trainer uses for SFT, so the base model (step 0) and every checkpoint see exactly the same prompts. """ import math import random import re import time SFT_PROMPT = "Question: {question}\nAnswer:" # MMLU as a regression guard measures general knowledge, so it leaves out the math subjects the # SFT data trains on. MATH_SUBJECTS = ("math", "algebra", "statistics") # ARC prompt versions, selected by the benchmark version in config.BENCHMARKS. v1 is the usual # cloze prompt, which is also exactly the SFT prompt. v2 ends with the phrase that precedes the # final answer in the training data instead; the tutorial bumps ARC-Easy to it in a backfill. ARC_PROMPTS = {"1": "Question: {question}\nAnswer:", "2": "Question: {question}\nThe answer is:"} def _sample(n: int, limit: int, seed: int = 0) -> list[int]: idx = list(range(n)) if limit and limit < n: idx = sorted(random.Random(seed).sample(idx, limit)) return idx # {{docs-fragment load}} def load_items(benchmark: str, limit: int, version: str = "1") -> list[dict]: """A fixed, seeded slice of one benchmark's test split as plain dicts.""" from datasets import load_dataset if benchmark == "gsm8k": ds = load_dataset("openai/gsm8k", "main", split="test") rows = [ds[i] for i in _sample(len(ds), limit)] return [{"question": r["question"], "gold": r["answer"].split("####")[-1].strip().replace(",", "")} for r in rows] if benchmark in ("arc_easy", "arc_challenge"): name = "ARC-Easy" if benchmark == "arc_easy" else "ARC-Challenge" ds = load_dataset("allenai/ai2_arc", name, split="test") rows = [ds[i] for i in _sample(len(ds), limit)] prompt = ARC_PROMPTS[version] return [{"context": prompt.format(question=r["question"].strip()), "choices": list(r["choices"]["text"]), "gold": list(r["choices"]["label"]).index(r["answerKey"])} for r in rows] if benchmark == "mmlu": ds = load_dataset("cais/mmlu", "all", split="test") keep = [i for i, s in enumerate(ds["subject"]) if not any(m in s for m in MATH_SUBJECTS)] rows = [ds[keep[j]] for j in _sample(len(keep), limit)] return [{"context": f"The following is a question about {r['subject'].replace('_', ' ')}.\n\n" f"Question: {r['question'].strip()}\nAnswer:", "choices": list(r["choices"]), "gold": int(r["answer"])} for r in rows] raise ValueError(f"unknown benchmark {benchmark!r}") # {{/docs-fragment load}} # {{docs-fragment extract}} _NUM = r"-?\d[\d,]*(?:\.\d+)?" def extract_answer(text: str) -> str | None: """The final number: after "The answer is" if the model says it, else the last number.""" # This takes the first "answer is", not the last. Fine-tuned outputs say it once, at the end. # The published GSM8K v1 scores were computed this way; switching to the last match changes # results, so do it together with a GSM8K version bump. m = re.search(rf"answer is:?\s*\$?\s*({_NUM})", text, flags=re.IGNORECASE) if m is None: nums = re.findall(_NUM, text) if not nums: return None found = nums[-1] else: found = m.group(1) found = found.replace(",", "").rstrip(".") try: v = float(found) except ValueError: return None return str(int(v)) if v.is_integer() else str(v) # {{/docs-fragment extract}} def _summary(benchmark: str, version: str, correct: list[bool], seconds: float, examples: list[dict]) -> dict: n = len(correct) acc = sum(correct) / max(n, 1) return {"benchmark": benchmark, "version": version, "n": n, "correct": int(sum(correct)), "accuracy": round(100 * acc, 2), "stderr": round(100 * math.sqrt(acc * (1 - acc) / max(n, 1)), 2), "seconds": round(seconds, 1), "examples": examples} # {{docs-fragment generate}} def score_generate(model_dir: str, items: list[dict], version: str, n_examples: int = 24) -> dict: """GSM8K: greedy generation with vLLM, exact match on the final number.""" from vllm import LLM, SamplingParams started = time.time() llm = LLM(model=model_dir, dtype="bfloat16", max_model_len=2048, gpu_memory_utilization=0.85, enforce_eager=True, seed=0) params = SamplingParams(temperature=0.0, max_tokens=400, stop=["\nQuestion:", "\n\n\n"]) outs = llm.generate([SFT_PROMPT.format(question=it["question"]) for it in items], params) texts = [o.outputs[0].text.strip() for o in outs] preds = [extract_answer(t) for t in texts] correct = [p is not None and float(p) == float(it["gold"]) for p, it in zip(preds, items)] examples = [{"question": it["question"], "gold": it["gold"], "pred": p, "ok": ok, "output": t[:900]} for it, p, ok, t in list(zip(items, preds, correct, texts))[:n_examples]] return _summary("gsm8k", version, correct, time.time() - started, examples) # {{/docs-fragment generate}} # {{docs-fragment choice}} def score_choice(model_dir: str, items: list[dict], benchmark: str, version: str, batch_tokens: int = 24_576) -> dict: """Multiple choice in the cloze form: pick the answer text with the highest log-likelihood. Small models score near chance when they have to answer with a letter, so this scores each option's own text after the question, normalized by its length in characters (as OLMES does for small models). """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer started = time.time() tok = AutoTokenizer.from_pretrained(model_dir) model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16).cuda().eval() pairs = [] # (item index, token ids, number of answer tokens, answer length in characters) for i, it in enumerate(items): ctx = tok.encode(it["context"], add_special_tokens=False) for choice in it["choices"]: ans = tok.encode(" " + choice.strip(), add_special_tokens=False) pairs.append((i, (ctx + ans)[-1024:], len(ans), max(1, len(choice.strip())))) score = [0.0] * len(pairs) pad = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id order = sorted(range(len(pairs)), key=lambda k: len(pairs[k][1])) # batch similar lengths with torch.inference_mode(): b = 0 while b < len(order): # Sorted by length, so the last row is the widest: fill the batch up to a token budget. n = max(1, batch_tokens // len(pairs[order[min(b + 255, len(order) - 1)]][1])) ks = order[b:b + min(n, 256)] b += len(ks) ids = [pairs[k][1] for k in ks] width = max(len(t) for t in ids) # Right padding keeps position ids exact for every row. x = torch.tensor([t + [pad] * (width - len(t)) for t in ids]).cuda() mask = torch.tensor([[1] * len(t) + [0] * (width - len(t)) for t in ids]).cuda() logp = torch.log_softmax(model(input_ids=x, attention_mask=mask).logits.float(), dim=-1) for r, k in enumerate(ks): _, t, n_ans, n_chars = pairs[k] pos = torch.arange(len(t) - n_ans, len(t), device=x.device) score[k] = logp[r, pos - 1, x[r, pos]].sum().item() / n_chars # token t is predicted at t-1 by_item: list[list[float]] = [[] for _ in items] for k, (i, _, _, _) in enumerate(pairs): # pairs are in item, then option, order by_item[i].append(score[k]) correct = [max(range(len(sc)), key=sc.__getitem__) == it["gold"] for sc, it in zip(by_item, items)] return _summary(benchmark, version, correct, time.time() - started, []) # {{/docs-fragment choice}} CODE8 """Benchmark slices: loading, prompts, answer extraction and scoring. Every function imports its heavy dependencies inside, so this module imports cleanly in the driver image too. The prompt format matches the one the trainer uses for SFT, so the base model (step 0) and every checkpoint see exactly the same prompts. """ import math import random import re import time SFT_PROMPT = "Question: {question}\nAnswer:" # MMLU as a regression guard measures general knowledge, so it leaves out the math subjects the # SFT data trains on. MATH_SUBJECTS = ("math", "algebra", "statistics") # ARC prompt versions, selected by the benchmark version in config.BENCHMARKS. v1 is the usual # cloze prompt, which is also exactly the SFT prompt. v2 ends with the phrase that precedes the # final answer in the training data instead; the tutorial bumps ARC-Easy to it in a backfill. ARC_PROMPTS = {"1": "Question: {question}\nAnswer:", "2": "Question: {question}\nThe answer is:"} def _sample(n: int, limit: int, seed: int = 0) -> list[int]: idx = list(range(n)) if limit and limit < n: idx = sorted(random.Random(seed).sample(idx, limit)) return idx # {{docs-fragment load}} def load_items(benchmark: str, limit: int, version: str = "1") -> list[dict]: """A fixed, seeded slice of one benchmark's test split as plain dicts.""" from datasets import load_dataset if benchmark == "gsm8k": ds = load_dataset("openai/gsm8k", "main", split="test") rows = [ds[i] for i in _sample(len(ds), limit)] return [{"question": r["question"], "gold": r["answer"].split("####")[-1].strip().replace(",", "")} for r in rows] if benchmark in ("arc_easy", "arc_challenge"): name = "ARC-Easy" if benchmark == "arc_easy" else "ARC-Challenge" ds = load_dataset("allenai/ai2_arc", name, split="test") rows = [ds[i] for i in _sample(len(ds), limit)] prompt = ARC_PROMPTS[version] return [{"context": prompt.format(question=r["question"].strip()), "choices": list(r["choices"]["text"]), "gold": list(r["choices"]["label"]).index(r["answerKey"])} for r in rows] if benchmark == "mmlu": ds = load_dataset("cais/mmlu", "all", split="test") keep = [i for i, s in enumerate(ds["subject"]) if not any(m in s for m in MATH_SUBJECTS)] rows = [ds[keep[j]] for j in _sample(len(keep), limit)] return [{"context": f"The following is a question about {r['subject'].replace('_', ' ')}.\n\n" f"Question: {r['question'].strip()}\nAnswer:", "choices": list(r["choices"]), "gold": int(r["answer"])} for r in rows] raise ValueError(f"unknown benchmark {benchmark!r}") # {{/docs-fragment load}} # {{docs-fragment extract}} _NUM = r"-?\d[\d,]*(?:\.\d+)?" def extract_answer(text: str) -> str | None: """The final number: after "The answer is" if the model says it, else the last number.""" # This takes the first "answer is", not the last. Fine-tuned outputs say it once, at the end. # The published GSM8K v1 scores were computed this way; switching to the last match changes # results, so do it together with a GSM8K version bump. m = re.search(rf"answer is:?\s*\$?\s*({_NUM})", text, flags=re.IGNORECASE) if m is None: nums = re.findall(_NUM, text) if not nums: return None found = nums[-1] else: found = m.group(1) found = found.replace(",", "").rstrip(".") try: v = float(found) except ValueError: return None return str(int(v)) if v.is_integer() else str(v) # {{/docs-fragment extract}} def _summary(benchmark: str, version: str, correct: list[bool], seconds: float, examples: list[dict]) -> dict: n = len(correct) acc = sum(correct) / max(n, 1) return {"benchmark": benchmark, "version": version, "n": n, "correct": int(sum(correct)), "accuracy": round(100 * acc, 2), "stderr": round(100 * math.sqrt(acc * (1 - acc) / max(n, 1)), 2), "seconds": round(seconds, 1), "examples": examples} # {{docs-fragment generate}} def score_generate(model_dir: str, items: list[dict], version: str, n_examples: int = 24) -> dict: """GSM8K: greedy generation with vLLM, exact match on the final number.""" from vllm import LLM, SamplingParams started = time.time() llm = LLM(model=model_dir, dtype="bfloat16", max_model_len=2048, gpu_memory_utilization=0.85, enforce_eager=True, seed=0) params = SamplingParams(temperature=0.0, max_tokens=400, stop=["\nQuestion:", "\n\n\n"]) outs = llm.generate([SFT_PROMPT.format(question=it["question"]) for it in items], params) texts = [o.outputs[0].text.strip() for o in outs] preds = [extract_answer(t) for t in texts] correct = [p is not None and float(p) == float(it["gold"]) for p, it in zip(preds, items)] examples = [{"question": it["question"], "gold": it["gold"], "pred": p, "ok": ok, "output": t[:900]} for it, p, ok, t in list(zip(items, preds, correct, texts))[:n_examples]] return _summary("gsm8k", version, correct, time.time() - started, examples) # {{/docs-fragment generate}} # {{docs-fragment choice}} def score_choice(model_dir: str, items: list[dict], benchmark: str, version: str, batch_tokens: int = 24_576) -> dict: """Multiple choice in the cloze form: pick the answer text with the highest log-likelihood. Small models score near chance when they have to answer with a letter, so this scores each option's own text after the question, normalized by its length in characters (as OLMES does for small models). """ import torch from transformers import AutoModelForCausalLM, AutoTokenizer started = time.time() tok = AutoTokenizer.from_pretrained(model_dir) model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16).cuda().eval() pairs = [] # (item index, token ids, number of answer tokens, answer length in characters) for i, it in enumerate(items): ctx = tok.encode(it["context"], add_special_tokens=False) for choice in it["choices"]: ans = tok.encode(" " + choice.strip(), add_special_tokens=False) pairs.append((i, (ctx + ans)[-1024:], len(ans), max(1, len(choice.strip())))) score = [0.0] * len(pairs) pad = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id order = sorted(range(len(pairs)), key=lambda k: len(pairs[k][1])) # batch similar lengths with torch.inference_mode(): b = 0 while b < len(order): # Sorted by length, so the last row is the widest: fill the batch up to a token budget. n = max(1, batch_tokens // len(pairs[order[min(b + 255, len(order) - 1)]][1])) ks = order[b:b + min(n, 256)] b += len(ks) ids = [pairs[k][1] for k in ks] width = max(len(t) for t in ids) # Right padding keeps position ids exact for every row. x = torch.tensor([t + [pad] * (width - len(t)) for t in ids]).cuda() mask = torch.tensor([[1] * len(t) + [0] * (width - len(t)) for t in ids]).cuda() logp = torch.log_softmax(model(input_ids=x, attention_mask=mask).logits.float(), dim=-1) for r, k in enumerate(ks): _, t, n_ans, n_chars = pairs[k] pos = torch.arange(len(t) - n_ans, len(t), device=x.device) score[k] = logp[r, pos - 1, x[r, pos]].sum().item() / n_chars # token t is predicted at t-1 by_item: list[list[float]] = [[] for _ in items] for k, (i, _, _, _) in enumerate(pairs): # pairs are in item, then option, order by_item[i].append(score[k]) correct = [max(range(len(sc)), key=sc.__getitem__) == it["gold"] for sc, it in zip(by_item, items)] return _summary(benchmark, version, correct, time.time() - started, []) # {{/docs-fragment choice}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/benchmarks.py* ## The trainer's leaderboard The driver starts `finetune` as a background asyncio task. Every 30 seconds it lists the results artifact for its own training run, redraws the report, and stops once every published checkpoint has scores. Then it applies the ship rule and promotes the winner. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Fine-tune a small model on math and publish every checkpoint as an artifact version. train_and_watch (CPU driver, live leaderboard report) โ””โ”€ finetune (L40S): SFT SmolLM2-360M on MetaMathQA step 0, then 8 checkpoints โ”€โ”€> Artifact.create(math-sft-checkpoint, step=...) โ”‚ (the evaluator's trigger runs each one) <โ”€โ”€ polls math-sft-checkpoint-evals, redraws curves, picks and promotes the best The trainer never calls the evaluator. It publishes checkpoints and keeps training; the evaluator's artifact trigger (see evals.py) launches one eval run per checkpoint. The driver only reads the published scores to draw learning curves and promote a release candidate. python train.py # deploy the evaluator, then train (about 20 minutes) python train.py --smoke # 2 checkpoints, 40 problems per benchmark python train.py --leaderboard # redraw the leaderboard after a backfill """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from config import ( BASE_MODEL, CHECKPOINT_ARTIFACT, RELEASE_ARTIFACT, RESULTS_ARTIFACT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import leaderboard_html, pick_best, release_card, training_html # {{docs-fragment envs}} train_env = flyte.TaskEnvironment( name="ckpt-evals-train", image=gpu_image, resources=flyte.Resources(cpu=6, memory="48Gi", gpu="L40s:1", disk="80Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) driver_env = flyte.TaskEnvironment( name="ckpt-evals-driver", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[train_env], ) # {{/docs-fragment envs}} def checkpoint_steps(total: int, n: int) -> list[int]: """Step 0, then ``n`` checkpoints spaced closer early on, where the curves move fastest.""" fracs = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 3 / 8, 1 / 2, 3 / 4, 1][-n:] if n <= 8 else [k / n for k in range(1, n + 1)] return [0] + sorted({max(1, round(f * total)) for f in fracs}) def load_sft_data(tok, n: int, max_len: int, seed: int) -> list[tuple[list[int], int]]: """MetaMathQA's GSM8K-derived problems as (token ids, prompt length) in the eval prompt format.""" from benchmarks import SFT_PROMPT from datasets import load_dataset ds = load_dataset("meta-math/MetaMathQA", split="train") ds = ds.filter(lambda t: t.startswith("GSM"), input_columns="type").shuffle(seed=seed).select(range(n)) out = [] for q, a in zip(ds["query"], ds["response"]): prompt = tok.encode(SFT_PROMPT.format(question=q), add_special_tokens=False) answer = tok.encode(" " + a.strip(), add_special_tokens=False) + [tok.eos_token_id] out.append(((prompt + answer)[:max_len], len(prompt))) return out # {{docs-fragment publish}} async def publish_checkpoint(path: str, step: int, train_run: str, profile: str, loss: float | None) -> str: """Upload a saved checkpoint and register it as a new version of the checkpoint artifact. The evaluator's trigger fires on this call; training does not wait for it. """ from flyte.remote import Artifact ckpt = await Dir.from_local(path) art = await Artifact.create.aio( ckpt, name=CHECKPOINT_ARTIFACT, version=f"{train_run}-step{step:05d}", kind="model", description=f"{BASE_MODEL} math SFT, step {step} of {train_run}", partitions={"train_run": train_run, "step": str(step), "profile": profile}, attrs={"base_model": BASE_MODEL, "train_loss": f"{loss:.4f}" if loss is not None else "n/a"}, ) return art.version # {{/docs-fragment publish}} # {{docs-fragment finetune}} @train_env.task(report=True) async def finetune( train_run: str, profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, micro_batch: int = 8, grad_accum: int = 4, max_len: int = 512, seed: int = 0, ) -> str: """Full fine-tune on one GPU; save and publish checkpoints without pausing for uploads.""" import math import os import random import torch from safetensors.torch import save_file from transformers import AutoModelForCausalLM, AutoTokenizer torch.manual_seed(seed) tok = AutoTokenizer.from_pretrained(BASE_MODEL) model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.float32).cuda() data = load_sft_data(tok, train_examples, max_len, seed) total = len(data) // (micro_batch * grad_accum) save_at = checkpoint_steps(total, n_checkpoints) opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, betas=(0.9, 0.95), weight_decay=0.0) warmup = max(1, total // 30) def lr_at(s: int) -> float: # linear warmup, cosine decay to 10% if s < warmup: return learning_rate * (s + 1) / warmup return learning_rate * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total - warmup)))) loop = asyncio.get_running_loop() uploads: list = [] history: list[dict] = [] published: list[dict] = [] started = time.time() def save(step: int, loss: float | None) -> None: # Saving takes seconds and runs on the training thread. Uploading and publishing run on # the event loop, so the next optimizer step starts right away. path = f"/tmp/ckpt/step-{step:05d}" os.makedirs(path, exist_ok=True) sd = {k: v.detach().to(torch.bfloat16).cpu().contiguous() for k, v in model.state_dict().items() if not (model.config.tie_word_embeddings and k == "lm_head.weight")} save_file(sd, f"{path}/model.safetensors", metadata={"format": "pt"}) model.config.save_pretrained(path) model.generation_config.save_pretrained(path) tok.save_pretrained(path) published.append({"step": step, "loss": loss, "saved_s": round(time.time() - started, 1)}) uploads.append(asyncio.run_coroutine_threadsafe( publish_checkpoint(path, step, train_run, profile, loss), loop)) def train() -> None: model.train() order = list(range(len(data))) random.Random(seed).shuffle(order) save(0, None) for step in range(1, total + 1): for g in opt.param_groups: g["lr"] = lr_at(step - 1) step_loss = 0.0 for m in range(grad_accum): lo = ((step - 1) * grad_accum + m) * micro_batch batch = [data[i] for i in order[lo:lo + micro_batch]] width = max(len(ids) for ids, _ in batch) x = torch.full((len(batch), width), tok.pad_token_id or tok.eos_token_id) y = torch.full((len(batch), width), -100) mask = torch.zeros((len(batch), width), dtype=torch.long) for r, (ids, plen) in enumerate(batch): x[r, :len(ids)] = torch.tensor(ids) mask[r, :len(ids)] = 1 y[r, plen:len(ids)] = torch.tensor(ids[plen:]) # loss on the answer only with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=x.cuda(), attention_mask=mask.cuda(), labels=y.cuda()).loss / grad_accum loss.backward() step_loss += loss.item() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() opt.zero_grad(set_to_none=True) if step % 10 == 0 or step == total: history.append({"step": step, "loss": round(step_loss, 4), "lr": lr_at(step - 1), "elapsed_s": round(time.time() - started, 1)}) if step in save_at: save(step, step_loss) if step % 25 == 0 or step in save_at: flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() await asyncio.to_thread(train) versions = await asyncio.gather(*[asyncio.wrap_future(u) for u in uploads]) flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() return json.dumps({"steps": save_at, "versions": versions, "history": history, "published": published, "total_steps": total, "train_s": round(time.time() - started, 1)}) # {{/docs-fragment finetune}} # {{docs-fragment collect}} async def collect_results(train_run: str) -> dict[int, dict]: """The newest published scores for each checkpoint of one training run, keyed by step.""" from flyte.remote import Artifact rows: dict[int, dict] = {} async for art in Artifact.listall.aio(name=RESULTS_ARTIFACT, train_run=train_run): step = int(art.partitions["step"]) if step in rows: # listall is newest first; a backfill publishes a newer version continue f = await art.to_python.aio(File) async with f.open("rb") as fh: rows[step] = json.loads(bytes(await fh.read())) rows[step]["published_at"] = art.pb2.created_at.ToDatetime().timestamp() return rows async def checkpoint_times(train_run: str) -> dict[int, float]: from flyte.remote import Artifact return {int(a.partitions["step"]): a.pb2.created_at.ToDatetime().timestamp() async for a in Artifact.listall.aio(name=CHECKPOINT_ARTIFACT, train_run=train_run)} # {{/docs-fragment collect}} # {{docs-fragment promote}} async def promote(train_run: str, rows: dict[int, dict], best: int) -> str: """Publish the winning checkpoint again, as the release-candidate artifact with a model card.""" from flyte.remote import Artifact ckpt = await Artifact.get.aio(CHECKPOINT_ARTIFACT, train_run=train_run, step=str(best)) card = await artifacts.Card.create_from.aio(content=release_card(train_run, rows, best), format="html", card_type="model") scores = rows[best]["scores"] art = await Artifact.create.aio( await ckpt.to_python.aio(Dir), name=RELEASE_ARTIFACT, version=f"{train_run}-step{best:05d}", kind="model", description=f"step {best} of {train_run}: " + ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()), attrs={"train_run": train_run, "step": str(best), **{k: f"{v['accuracy']:.2f}" for k, v in scores.items()}}, card=card, parents=[ckpt.artifact_version_id], ) return art.version # {{/docs-fragment promote}} # {{docs-fragment driver}} @driver_env.task(report=True) async def train_and_watch( profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, wait_minutes: int = 40, ) -> str: """Train in the background, redraw the leaderboard as scores arrive, then promote the winner.""" train_run = flyte.ctx().action.run_name started = time.time() trainer = asyncio.create_task(finetune(train_run=train_run, profile=profile, train_examples=train_examples, n_checkpoints=n_checkpoints, learning_rate=learning_rate)) info, rows, deadline = None, {}, None while True: rows = await collect_results(train_run) times = await checkpoint_times(train_run) if trainer.done() and info is None: info = json.loads(trainer.result()) # re-raises if training failed deadline = time.time() + wait_minutes * 60 expected = len(info["steps"]) if info else n_checkpoints + 1 await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=False), do_flush=True) if info and (len(rows) >= expected or time.time() > deadline): break await asyncio.sleep(30) best = pick_best(rows) release = await promote(train_run, rows, best["step"]) if best else None await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=True, release=release), do_flush=True) return json.dumps({"best_step": best["step"] if best else None, "release_version": release, "evaluated": sorted(rows), "expected": info["steps"]}) # {{/docs-fragment driver}} @driver_env.task(report=True) async def refresh_leaderboard(train_run: str) -> str: """Redraw the leaderboard for a finished training run, for example after a backfill.""" rows = await collect_results(train_run) times = await checkpoint_times(train_run) await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, min(times.values()), None, len(times), final=True), do_flush=True) best = pick_best(rows) return json.dumps({"best_step": best["step"] if best else None, "evaluated": sorted(rows)}) # {{docs-fragment run}} if __name__ == "__main__": import evals flyte.init_from_config() if "--leaderboard" in sys.argv: run = flyte.run(refresh_leaderboard, train_run=sys.argv[sys.argv.index("--leaderboard") + 1]) else: # The evaluator must be deployed, with its trigger active, before the first checkpoint lands. flyte.deploy(evals.eval_env) if "--smoke" in sys.argv: run = flyte.run(train_and_watch, profile="smoke", train_examples=1_600, n_checkpoints=2, wait_minutes=20) else: run = flyte.run(train_and_watch) print(run.url) # {{/docs-fragment run}} CODE9 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Fine-tune a small model on math and publish every checkpoint as an artifact version. train_and_watch (CPU driver, live leaderboard report) โ””โ”€ finetune (L40S): SFT SmolLM2-360M on MetaMathQA step 0, then 8 checkpoints โ”€โ”€> Artifact.create(math-sft-checkpoint, step=...) โ”‚ (the evaluator's trigger runs each one) <โ”€โ”€ polls math-sft-checkpoint-evals, redraws curves, picks and promotes the best The trainer never calls the evaluator. It publishes checkpoints and keeps training; the evaluator's artifact trigger (see evals.py) launches one eval run per checkpoint. The driver only reads the published scores to draw learning curves and promote a release candidate. python train.py # deploy the evaluator, then train (about 20 minutes) python train.py --smoke # 2 checkpoints, 40 problems per benchmark python train.py --leaderboard # redraw the leaderboard after a backfill """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from config import ( BASE_MODEL, CHECKPOINT_ARTIFACT, RELEASE_ARTIFACT, RESULTS_ARTIFACT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import leaderboard_html, pick_best, release_card, training_html # {{docs-fragment envs}} train_env = flyte.TaskEnvironment( name="ckpt-evals-train", image=gpu_image, resources=flyte.Resources(cpu=6, memory="48Gi", gpu="L40s:1", disk="80Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) driver_env = flyte.TaskEnvironment( name="ckpt-evals-driver", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[train_env], ) # {{/docs-fragment envs}} def checkpoint_steps(total: int, n: int) -> list[int]: """Step 0, then ``n`` checkpoints spaced closer early on, where the curves move fastest.""" fracs = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 3 / 8, 1 / 2, 3 / 4, 1][-n:] if n <= 8 else [k / n for k in range(1, n + 1)] return [0] + sorted({max(1, round(f * total)) for f in fracs}) def load_sft_data(tok, n: int, max_len: int, seed: int) -> list[tuple[list[int], int]]: """MetaMathQA's GSM8K-derived problems as (token ids, prompt length) in the eval prompt format.""" from benchmarks import SFT_PROMPT from datasets import load_dataset ds = load_dataset("meta-math/MetaMathQA", split="train") ds = ds.filter(lambda t: t.startswith("GSM"), input_columns="type").shuffle(seed=seed).select(range(n)) out = [] for q, a in zip(ds["query"], ds["response"]): prompt = tok.encode(SFT_PROMPT.format(question=q), add_special_tokens=False) answer = tok.encode(" " + a.strip(), add_special_tokens=False) + [tok.eos_token_id] out.append(((prompt + answer)[:max_len], len(prompt))) return out # {{docs-fragment publish}} async def publish_checkpoint(path: str, step: int, train_run: str, profile: str, loss: float | None) -> str: """Upload a saved checkpoint and register it as a new version of the checkpoint artifact. The evaluator's trigger fires on this call; training does not wait for it. """ from flyte.remote import Artifact ckpt = await Dir.from_local(path) art = await Artifact.create.aio( ckpt, name=CHECKPOINT_ARTIFACT, version=f"{train_run}-step{step:05d}", kind="model", description=f"{BASE_MODEL} math SFT, step {step} of {train_run}", partitions={"train_run": train_run, "step": str(step), "profile": profile}, attrs={"base_model": BASE_MODEL, "train_loss": f"{loss:.4f}" if loss is not None else "n/a"}, ) return art.version # {{/docs-fragment publish}} # {{docs-fragment finetune}} @train_env.task(report=True) async def finetune( train_run: str, profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, micro_batch: int = 8, grad_accum: int = 4, max_len: int = 512, seed: int = 0, ) -> str: """Full fine-tune on one GPU; save and publish checkpoints without pausing for uploads.""" import math import os import random import torch from safetensors.torch import save_file from transformers import AutoModelForCausalLM, AutoTokenizer torch.manual_seed(seed) tok = AutoTokenizer.from_pretrained(BASE_MODEL) model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.float32).cuda() data = load_sft_data(tok, train_examples, max_len, seed) total = len(data) // (micro_batch * grad_accum) save_at = checkpoint_steps(total, n_checkpoints) opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, betas=(0.9, 0.95), weight_decay=0.0) warmup = max(1, total // 30) def lr_at(s: int) -> float: # linear warmup, cosine decay to 10% if s < warmup: return learning_rate * (s + 1) / warmup return learning_rate * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total - warmup)))) loop = asyncio.get_running_loop() uploads: list = [] history: list[dict] = [] published: list[dict] = [] started = time.time() def save(step: int, loss: float | None) -> None: # Saving takes seconds and runs on the training thread. Uploading and publishing run on # the event loop, so the next optimizer step starts right away. path = f"/tmp/ckpt/step-{step:05d}" os.makedirs(path, exist_ok=True) sd = {k: v.detach().to(torch.bfloat16).cpu().contiguous() for k, v in model.state_dict().items() if not (model.config.tie_word_embeddings and k == "lm_head.weight")} save_file(sd, f"{path}/model.safetensors", metadata={"format": "pt"}) model.config.save_pretrained(path) model.generation_config.save_pretrained(path) tok.save_pretrained(path) published.append({"step": step, "loss": loss, "saved_s": round(time.time() - started, 1)}) uploads.append(asyncio.run_coroutine_threadsafe( publish_checkpoint(path, step, train_run, profile, loss), loop)) def train() -> None: model.train() order = list(range(len(data))) random.Random(seed).shuffle(order) save(0, None) for step in range(1, total + 1): for g in opt.param_groups: g["lr"] = lr_at(step - 1) step_loss = 0.0 for m in range(grad_accum): lo = ((step - 1) * grad_accum + m) * micro_batch batch = [data[i] for i in order[lo:lo + micro_batch]] width = max(len(ids) for ids, _ in batch) x = torch.full((len(batch), width), tok.pad_token_id or tok.eos_token_id) y = torch.full((len(batch), width), -100) mask = torch.zeros((len(batch), width), dtype=torch.long) for r, (ids, plen) in enumerate(batch): x[r, :len(ids)] = torch.tensor(ids) mask[r, :len(ids)] = 1 y[r, plen:len(ids)] = torch.tensor(ids[plen:]) # loss on the answer only with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=x.cuda(), attention_mask=mask.cuda(), labels=y.cuda()).loss / grad_accum loss.backward() step_loss += loss.item() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() opt.zero_grad(set_to_none=True) if step % 10 == 0 or step == total: history.append({"step": step, "loss": round(step_loss, 4), "lr": lr_at(step - 1), "elapsed_s": round(time.time() - started, 1)}) if step in save_at: save(step, step_loss) if step % 25 == 0 or step in save_at: flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() await asyncio.to_thread(train) versions = await asyncio.gather(*[asyncio.wrap_future(u) for u in uploads]) flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() return json.dumps({"steps": save_at, "versions": versions, "history": history, "published": published, "total_steps": total, "train_s": round(time.time() - started, 1)}) # {{/docs-fragment finetune}} # {{docs-fragment collect}} async def collect_results(train_run: str) -> dict[int, dict]: """The newest published scores for each checkpoint of one training run, keyed by step.""" from flyte.remote import Artifact rows: dict[int, dict] = {} async for art in Artifact.listall.aio(name=RESULTS_ARTIFACT, train_run=train_run): step = int(art.partitions["step"]) if step in rows: # listall is newest first; a backfill publishes a newer version continue f = await art.to_python.aio(File) async with f.open("rb") as fh: rows[step] = json.loads(bytes(await fh.read())) rows[step]["published_at"] = art.pb2.created_at.ToDatetime().timestamp() return rows async def checkpoint_times(train_run: str) -> dict[int, float]: from flyte.remote import Artifact return {int(a.partitions["step"]): a.pb2.created_at.ToDatetime().timestamp() async for a in Artifact.listall.aio(name=CHECKPOINT_ARTIFACT, train_run=train_run)} # {{/docs-fragment collect}} # {{docs-fragment promote}} async def promote(train_run: str, rows: dict[int, dict], best: int) -> str: """Publish the winning checkpoint again, as the release-candidate artifact with a model card.""" from flyte.remote import Artifact ckpt = await Artifact.get.aio(CHECKPOINT_ARTIFACT, train_run=train_run, step=str(best)) card = await artifacts.Card.create_from.aio(content=release_card(train_run, rows, best), format="html", card_type="model") scores = rows[best]["scores"] art = await Artifact.create.aio( await ckpt.to_python.aio(Dir), name=RELEASE_ARTIFACT, version=f"{train_run}-step{best:05d}", kind="model", description=f"step {best} of {train_run}: " + ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()), attrs={"train_run": train_run, "step": str(best), **{k: f"{v['accuracy']:.2f}" for k, v in scores.items()}}, card=card, parents=[ckpt.artifact_version_id], ) return art.version # {{/docs-fragment promote}} # {{docs-fragment driver}} @driver_env.task(report=True) async def train_and_watch( profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, wait_minutes: int = 40, ) -> str: """Train in the background, redraw the leaderboard as scores arrive, then promote the winner.""" train_run = flyte.ctx().action.run_name started = time.time() trainer = asyncio.create_task(finetune(train_run=train_run, profile=profile, train_examples=train_examples, n_checkpoints=n_checkpoints, learning_rate=learning_rate)) info, rows, deadline = None, {}, None while True: rows = await collect_results(train_run) times = await checkpoint_times(train_run) if trainer.done() and info is None: info = json.loads(trainer.result()) # re-raises if training failed deadline = time.time() + wait_minutes * 60 expected = len(info["steps"]) if info else n_checkpoints + 1 await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=False), do_flush=True) if info and (len(rows) >= expected or time.time() > deadline): break await asyncio.sleep(30) best = pick_best(rows) release = await promote(train_run, rows, best["step"]) if best else None await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=True, release=release), do_flush=True) return json.dumps({"best_step": best["step"] if best else None, "release_version": release, "evaluated": sorted(rows), "expected": info["steps"]}) # {{/docs-fragment driver}} @driver_env.task(report=True) async def refresh_leaderboard(train_run: str) -> str: """Redraw the leaderboard for a finished training run, for example after a backfill.""" rows = await collect_results(train_run) times = await checkpoint_times(train_run) await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, min(times.values()), None, len(times), final=True), do_flush=True) best = pick_best(rows) return json.dumps({"best_step": best["step"] if best else None, "evaluated": sorted(rows)}) # {{docs-fragment run}} if __name__ == "__main__": import evals flyte.init_from_config() if "--leaderboard" in sys.argv: run = flyte.run(refresh_leaderboard, train_run=sys.argv[sys.argv.index("--leaderboard") + 1]) else: # The evaluator must be deployed, with its trigger active, before the first checkpoint lands. flyte.deploy(evals.eval_env) if "--smoke" in sys.argv: run = flyte.run(train_and_watch, profile="smoke", train_examples=1_600, n_checkpoints=2, wait_minutes=20) else: run = flyte.run(train_and_watch) print(run.url) # {{/docs-fragment run}} CODE10 """Reports: the per-checkpoint scorecard, the training report, the leaderboard and the release card.""" import time import viz from config import BASE_MODEL, BENCHMARKS, GUARD_BENCHMARK, GUARD_MAX_DROP def _benchmarks(rows: dict[int, dict]) -> list[str]: seen = {b for r in rows.values() for b in r["scores"]} return [b for b in BENCHMARKS if b in seen] def _acc(row: dict, b: str) -> float | None: s = row["scores"].get(b) return s["accuracy"] if s else None # {{docs-fragment ship_rule}} def pick_best(rows: dict[int, dict]) -> dict | None: """The ship rule: highest GSM8K among checkpoints that keep MMLU within GUARD_MAX_DROP of step 0.""" if 0 not in rows: return None floor = (_acc(rows[0], GUARD_BENCHMARK) or 0.0) - GUARD_MAX_DROP ok = [r for s, r in rows.items() if s > 0 and (_acc(r, GUARD_BENCHMARK) or 0.0) >= floor] return max(ok, key=lambda r: (_acc(r, "gsm8k") or 0.0, -r["step"])) if ok else None # {{/docs-fragment ship_rule}} def _example(e: dict) -> str: verdict = viz.status("good", f"predicted {e['pred']}") if e["ok"] else viz.status("critical", f"predicted {e['pred']}") return (f"

Gold {viz.esc(e['gold'])} ยท {verdict}

" f"
{viz.esc(e['output'])}
") def scorecard_html(result: dict) -> str: """One eval run: the suite's scores for one checkpoint, and a few GSM8K generations.""" scores = result["scores"] tiles = [(BENCHMARKS[b]["label"], f"{s['accuracy']:.1f}%", f"ยฑ{s['stderr']:.1f} ยท n={s['n']} ยท v{s['version']} ยท {s['seconds']:.0f} s") for b, s in scores.items()] blocks = [viz.tiles(tiles, hero=True)] gsm = scores.get("gsm8k") if gsm and gsm["examples"]: blocks.append(viz.panel("GSM8K generations", "".join( f"

Q: {viz.esc(e['question'])}

{_example(e)}" for e in gsm["examples"][:3]))) return viz.page(f"Checkpoint step {result['step']}", f"Training run {viz.esc(result['train_run'])} ยท profile {result['profile']} ยท " f"suite took {result['finished_at'] - result['started_at']:.0f} s end to end", *blocks) def training_html(history: list[dict], published: list[dict], total: int, n_examples: int, model: str) -> str: last = history[-1] if history else {"step": 0, "loss": None, "elapsed_s": 0} xs = [h["step"] for h in history] loss = viz.line_chart([viz.Series("train loss", [h["loss"] for h in history], 1, xs=xs)], height=200, markers={p["step"]: f"ckpt {p['step']}" for p in published if p["step"] > 0}, x_label="step") rows = [(p["step"], f"{p['saved_s'] / 60:.1f} min", f"{p['loss']:.3f}" if p["loss"] is not None else "base model") for p in published] return viz.page( f"Fine-tuning {model} on MetaMathQA", f"{n_examples:,} GSM8K-style problems ยท {total} optimizer steps ยท checkpoints publish as artifact versions " "and the evaluator picks them up on its own", viz.tiles([("Step", f"{last['step']}/{total}"), ("Train loss", f"{last['loss']:.3f}" if last["loss"] is not None else "โ€“"), ("Checkpoints published", str(len(published))), ("Elapsed", f"{last['elapsed_s'] / 60:.1f} min")]), viz.panel("Training loss", loss, "Vertical lines mark saved checkpoints."), viz.panel("Published checkpoints", viz.table(["step", "saved at", "train loss"], rows)), ) # {{docs-fragment leaderboard}} def leaderboard_html(train_run: str, rows: dict[int, dict], times: dict[int, float], started: float, info: dict | None, expected: int, final: bool, release: str | None = None) -> str: """Learning curves per benchmark, the checkpoints x benchmarks table, a timeline, and generations.""" benches = _benchmarks(rows) steps = sorted(rows) best = pick_best(rows) if final else None base = rows.get(0) state = "final" if final else ("training finished, waiting for evals" if info else "training") blocks = [] if best and base: g0, g1 = _acc(base, "gsm8k"), _acc(best, "gsm8k") m0, m1 = _acc(base, GUARD_BENCHMARK), _acc(best, GUARD_BENCHMARK) blocks.append(viz.tiles([ ("Release candidate: step", str(best["step"]), f"published as {release}" if release else "ship rule winner"), ("GSM8K", f"{g1:.1f}%", f"{g1 - g0:+.1f} pts vs base ({g0:.1f}%)"), ("MMLU guard", f"{m1:.1f}%", f"{m1 - m0:+.1f} pts vs base, limit -{GUARD_MAX_DROP:.0f}"), ("Checkpoints evaluated", f"{len(rows)}/{expected}", f"{sum(len(r['scores']) for r in rows.values())} benchmark runs"), ], hero=True)) elif final and base: top = max((r for s, r in rows.items() if s > 0), key=lambda r: _acc(r, "gsm8k") or 0.0, default=None) blocks.append(viz.tiles([ ("Release candidate", "none", f"no checkpoint keeps MMLU within {GUARD_MAX_DROP:.0f} pts of the base model"), ("Best GSM8K", f"{_acc(top, 'gsm8k'):.1f}%" if top else "โ€“", f"step {top['step']}" if top else ""), ("Checkpoints evaluated", f"{len(rows)}/{expected}"), ], hero=True)) else: blocks.append(viz.tiles([("Status", state), ("Checkpoints evaluated", f"{len(rows)}/{expected}"), ("Elapsed", f"{(time.time() - started) / 60:.0f} min")])) # One small chart per benchmark: the curve, the base model as a reference line, the winner marked. charts = [] for i, b in enumerate(benches): pts = [(s, _acc(rows[s], b)) for s in steps if _acc(rows[s], b) is not None] refs = [(_acc(base, b), "base")] if base and _acc(base, b) is not None else [] marks = {best["step"]: "release"} if best else None chart = viz.line_chart([viz.Series(BENCHMARKS[b]["label"], [v for _, v in pts], i + 1, xs=[s for s, _ in pts])], height=200, width=360, refs=refs, markers=marks, x_label="step", y_fmt=lambda v: f"{v:.0f}%") note = {"target": "What the SFT is for.", "guard": "Regression guard: the ship rule rejects drops over " f"{GUARD_MAX_DROP:.0f} pts.", "reasoning": "General reasoning, multiple choice."}[BENCHMARKS[b]["role"]] charts.append(viz.panel(BENCHMARKS[b]["label"], chart, note)) if charts: blocks.append("
" + "".join(c.replace("class='panel'", "class='panel' style='margin:0'", 1) for c in charts) + "
") # The checkpoints x benchmarks table. floor = (_acc(base, GUARD_BENCHMARK) or 0) - GUARD_MAX_DROP if base else None table_rows = [] for s in steps: r = rows[s] cells = [f"{_acc(r, b):.1f} ยฑ{r['scores'][b]['stderr']:.1f}" if b in r["scores"] else "โ€“" for b in benches] if s == 0: verdict = viz.status("neutral", "base model") elif best and s == best["step"]: verdict = viz.status("good", "release candidate") elif floor is not None and (_acc(r, GUARD_BENCHMARK) or 0) < floor: verdict = viz.status("critical", "fails guard") else: verdict = viz.status("neutral", "passes guard") table_rows.append([f"{s}", *cells, verdict, f"{viz.esc(r['eval_run'])}"]) blocks.append(viz.panel("Checkpoints ร— benchmarks (accuracy %, ยฑ one standard error)", viz.table(["step", *[BENCHMARKS[b]["label"] for b in benches], "ship rule", "eval run"], table_rows))) # Timeline: evals overlap training because the trigger, not the trainer, launches them. spans = [] if times: # Training runs from the step-0 checkpoint to the last one (or to now, while it runs). t_end = max(times.values()) if info or final else time.time() spans.append(viz.Span("training", "step 0 to last checkpoint", times.get(0, min(times.values())), t_end, 1)) for s in steps: spans.append(viz.Span("evals", f"step {s}", rows[s]["started_at"], rows[s]["finished_at"], 3)) blocks.append(viz.panel("Timeline", viz.gantt(spans, unit="s", packed=False), "Each green bar is the newest eval run for one checkpoint, from start to finish.")) # Generations: the same GSM8K problems, base model vs the release candidate. Problems the # fine-tuning fixed come first. if base and best and "gsm8k" in base["scores"] and "gsm8k" in best["scores"]: pairs = list(zip(base["scores"]["gsm8k"]["examples"], best["scores"]["gsm8k"]["examples"])) pairs.sort(key=lambda p: (p[0]["ok"] or not p[1]["ok"], p[0]["ok"] == p[1]["ok"])) cells = "".join( f"

Q: {viz.esc(a['question'])}

" f"

Base model

{_example(a)}
" f"

Step {best['step']}

{_example(c)}
" for a, c in pairs[:3]) blocks.append(viz.panel("GSM8K generations, base vs release candidate", cells)) return viz.page(f"Evaluate every checkpoint ยท {train_run}", f"{state} ยท scores arrive from independent, trigger-launched eval runs", *blocks) # {{/docs-fragment leaderboard}} def release_card(train_run: str, rows: dict[int, dict], best: int) -> str: benches = _benchmarks(rows) base, win = rows[0], rows[best] table = viz.table(["benchmark", "base", f"step {best}", "change"], [(BENCHMARKS[b]["label"], f"{_acc(base, b):.1f}", f"{_acc(win, b):.1f}", f"{_acc(win, b) - _acc(base, b):+.1f}") for b in benches if _acc(base, b) is not None and _acc(win, b) is not None]) return viz.card(f"Math SFT release candidate ยท step {best}", f"Picked by the ship rule from {len(rows)} evaluated checkpoints of {viz.esc(train_run)}: highest " f"GSM8K with MMLU no more than {GUARD_MAX_DROP:.0f} points below the base model.", [BASE_MODEL.split("/")[-1], "MetaMathQA SFT", f"step {best}"], viz.panel("Scores", table)) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/reports.py* Promotion publishes the winning checkpoint's directory again, under the release-candidate name, with a model card and the checkpoint version as its parent. Anything downstream, such as a serving app or a longer eval suite, can load `flyte.remote.Artifact.get("math-sft-release-candidate")` without knowing which run or step produced it. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Fine-tune a small model on math and publish every checkpoint as an artifact version. train_and_watch (CPU driver, live leaderboard report) โ””โ”€ finetune (L40S): SFT SmolLM2-360M on MetaMathQA step 0, then 8 checkpoints โ”€โ”€> Artifact.create(math-sft-checkpoint, step=...) โ”‚ (the evaluator's trigger runs each one) <โ”€โ”€ polls math-sft-checkpoint-evals, redraws curves, picks and promotes the best The trainer never calls the evaluator. It publishes checkpoints and keeps training; the evaluator's artifact trigger (see evals.py) launches one eval run per checkpoint. The driver only reads the published scores to draw learning curves and promote a release candidate. python train.py # deploy the evaluator, then train (about 20 minutes) python train.py --smoke # 2 checkpoints, 40 problems per benchmark python train.py --leaderboard # redraw the leaderboard after a backfill """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from config import ( BASE_MODEL, CHECKPOINT_ARTIFACT, RELEASE_ARTIFACT, RESULTS_ARTIFACT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import leaderboard_html, pick_best, release_card, training_html # {{docs-fragment envs}} train_env = flyte.TaskEnvironment( name="ckpt-evals-train", image=gpu_image, resources=flyte.Resources(cpu=6, memory="48Gi", gpu="L40s:1", disk="80Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) driver_env = flyte.TaskEnvironment( name="ckpt-evals-driver", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[train_env], ) # {{/docs-fragment envs}} def checkpoint_steps(total: int, n: int) -> list[int]: """Step 0, then ``n`` checkpoints spaced closer early on, where the curves move fastest.""" fracs = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 3 / 8, 1 / 2, 3 / 4, 1][-n:] if n <= 8 else [k / n for k in range(1, n + 1)] return [0] + sorted({max(1, round(f * total)) for f in fracs}) def load_sft_data(tok, n: int, max_len: int, seed: int) -> list[tuple[list[int], int]]: """MetaMathQA's GSM8K-derived problems as (token ids, prompt length) in the eval prompt format.""" from benchmarks import SFT_PROMPT from datasets import load_dataset ds = load_dataset("meta-math/MetaMathQA", split="train") ds = ds.filter(lambda t: t.startswith("GSM"), input_columns="type").shuffle(seed=seed).select(range(n)) out = [] for q, a in zip(ds["query"], ds["response"]): prompt = tok.encode(SFT_PROMPT.format(question=q), add_special_tokens=False) answer = tok.encode(" " + a.strip(), add_special_tokens=False) + [tok.eos_token_id] out.append(((prompt + answer)[:max_len], len(prompt))) return out # {{docs-fragment publish}} async def publish_checkpoint(path: str, step: int, train_run: str, profile: str, loss: float | None) -> str: """Upload a saved checkpoint and register it as a new version of the checkpoint artifact. The evaluator's trigger fires on this call; training does not wait for it. """ from flyte.remote import Artifact ckpt = await Dir.from_local(path) art = await Artifact.create.aio( ckpt, name=CHECKPOINT_ARTIFACT, version=f"{train_run}-step{step:05d}", kind="model", description=f"{BASE_MODEL} math SFT, step {step} of {train_run}", partitions={"train_run": train_run, "step": str(step), "profile": profile}, attrs={"base_model": BASE_MODEL, "train_loss": f"{loss:.4f}" if loss is not None else "n/a"}, ) return art.version # {{/docs-fragment publish}} # {{docs-fragment finetune}} @train_env.task(report=True) async def finetune( train_run: str, profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, micro_batch: int = 8, grad_accum: int = 4, max_len: int = 512, seed: int = 0, ) -> str: """Full fine-tune on one GPU; save and publish checkpoints without pausing for uploads.""" import math import os import random import torch from safetensors.torch import save_file from transformers import AutoModelForCausalLM, AutoTokenizer torch.manual_seed(seed) tok = AutoTokenizer.from_pretrained(BASE_MODEL) model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.float32).cuda() data = load_sft_data(tok, train_examples, max_len, seed) total = len(data) // (micro_batch * grad_accum) save_at = checkpoint_steps(total, n_checkpoints) opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, betas=(0.9, 0.95), weight_decay=0.0) warmup = max(1, total // 30) def lr_at(s: int) -> float: # linear warmup, cosine decay to 10% if s < warmup: return learning_rate * (s + 1) / warmup return learning_rate * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total - warmup)))) loop = asyncio.get_running_loop() uploads: list = [] history: list[dict] = [] published: list[dict] = [] started = time.time() def save(step: int, loss: float | None) -> None: # Saving takes seconds and runs on the training thread. Uploading and publishing run on # the event loop, so the next optimizer step starts right away. path = f"/tmp/ckpt/step-{step:05d}" os.makedirs(path, exist_ok=True) sd = {k: v.detach().to(torch.bfloat16).cpu().contiguous() for k, v in model.state_dict().items() if not (model.config.tie_word_embeddings and k == "lm_head.weight")} save_file(sd, f"{path}/model.safetensors", metadata={"format": "pt"}) model.config.save_pretrained(path) model.generation_config.save_pretrained(path) tok.save_pretrained(path) published.append({"step": step, "loss": loss, "saved_s": round(time.time() - started, 1)}) uploads.append(asyncio.run_coroutine_threadsafe( publish_checkpoint(path, step, train_run, profile, loss), loop)) def train() -> None: model.train() order = list(range(len(data))) random.Random(seed).shuffle(order) save(0, None) for step in range(1, total + 1): for g in opt.param_groups: g["lr"] = lr_at(step - 1) step_loss = 0.0 for m in range(grad_accum): lo = ((step - 1) * grad_accum + m) * micro_batch batch = [data[i] for i in order[lo:lo + micro_batch]] width = max(len(ids) for ids, _ in batch) x = torch.full((len(batch), width), tok.pad_token_id or tok.eos_token_id) y = torch.full((len(batch), width), -100) mask = torch.zeros((len(batch), width), dtype=torch.long) for r, (ids, plen) in enumerate(batch): x[r, :len(ids)] = torch.tensor(ids) mask[r, :len(ids)] = 1 y[r, plen:len(ids)] = torch.tensor(ids[plen:]) # loss on the answer only with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=x.cuda(), attention_mask=mask.cuda(), labels=y.cuda()).loss / grad_accum loss.backward() step_loss += loss.item() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() opt.zero_grad(set_to_none=True) if step % 10 == 0 or step == total: history.append({"step": step, "loss": round(step_loss, 4), "lr": lr_at(step - 1), "elapsed_s": round(time.time() - started, 1)}) if step in save_at: save(step, step_loss) if step % 25 == 0 or step in save_at: flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() await asyncio.to_thread(train) versions = await asyncio.gather(*[asyncio.wrap_future(u) for u in uploads]) flyte.report.replace(training_html(history, published, total, train_examples, BASE_MODEL)) flyte.report.flush() return json.dumps({"steps": save_at, "versions": versions, "history": history, "published": published, "total_steps": total, "train_s": round(time.time() - started, 1)}) # {{/docs-fragment finetune}} # {{docs-fragment collect}} async def collect_results(train_run: str) -> dict[int, dict]: """The newest published scores for each checkpoint of one training run, keyed by step.""" from flyte.remote import Artifact rows: dict[int, dict] = {} async for art in Artifact.listall.aio(name=RESULTS_ARTIFACT, train_run=train_run): step = int(art.partitions["step"]) if step in rows: # listall is newest first; a backfill publishes a newer version continue f = await art.to_python.aio(File) async with f.open("rb") as fh: rows[step] = json.loads(bytes(await fh.read())) rows[step]["published_at"] = art.pb2.created_at.ToDatetime().timestamp() return rows async def checkpoint_times(train_run: str) -> dict[int, float]: from flyte.remote import Artifact return {int(a.partitions["step"]): a.pb2.created_at.ToDatetime().timestamp() async for a in Artifact.listall.aio(name=CHECKPOINT_ARTIFACT, train_run=train_run)} # {{/docs-fragment collect}} # {{docs-fragment promote}} async def promote(train_run: str, rows: dict[int, dict], best: int) -> str: """Publish the winning checkpoint again, as the release-candidate artifact with a model card.""" from flyte.remote import Artifact ckpt = await Artifact.get.aio(CHECKPOINT_ARTIFACT, train_run=train_run, step=str(best)) card = await artifacts.Card.create_from.aio(content=release_card(train_run, rows, best), format="html", card_type="model") scores = rows[best]["scores"] art = await Artifact.create.aio( await ckpt.to_python.aio(Dir), name=RELEASE_ARTIFACT, version=f"{train_run}-step{best:05d}", kind="model", description=f"step {best} of {train_run}: " + ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()), attrs={"train_run": train_run, "step": str(best), **{k: f"{v['accuracy']:.2f}" for k, v in scores.items()}}, card=card, parents=[ckpt.artifact_version_id], ) return art.version # {{/docs-fragment promote}} # {{docs-fragment driver}} @driver_env.task(report=True) async def train_and_watch( profile: str = "full", train_examples: int = 50_000, n_checkpoints: int = 8, learning_rate: float = 3e-5, wait_minutes: int = 40, ) -> str: """Train in the background, redraw the leaderboard as scores arrive, then promote the winner.""" train_run = flyte.ctx().action.run_name started = time.time() trainer = asyncio.create_task(finetune(train_run=train_run, profile=profile, train_examples=train_examples, n_checkpoints=n_checkpoints, learning_rate=learning_rate)) info, rows, deadline = None, {}, None while True: rows = await collect_results(train_run) times = await checkpoint_times(train_run) if trainer.done() and info is None: info = json.loads(trainer.result()) # re-raises if training failed deadline = time.time() + wait_minutes * 60 expected = len(info["steps"]) if info else n_checkpoints + 1 await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=False), do_flush=True) if info and (len(rows) >= expected or time.time() > deadline): break await asyncio.sleep(30) best = pick_best(rows) release = await promote(train_run, rows, best["step"]) if best else None await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, started, info, expected, final=True, release=release), do_flush=True) return json.dumps({"best_step": best["step"] if best else None, "release_version": release, "evaluated": sorted(rows), "expected": info["steps"]}) # {{/docs-fragment driver}} @driver_env.task(report=True) async def refresh_leaderboard(train_run: str) -> str: """Redraw the leaderboard for a finished training run, for example after a backfill.""" rows = await collect_results(train_run) times = await checkpoint_times(train_run) await flyte.report.replace.aio( leaderboard_html(train_run, rows, times, min(times.values()), None, len(times), final=True), do_flush=True) best = pick_best(rows) return json.dumps({"best_step": best["step"] if best else None, "evaluated": sorted(rows)}) # {{docs-fragment run}} if __name__ == "__main__": import evals flyte.init_from_config() if "--leaderboard" in sys.argv: run = flyte.run(refresh_leaderboard, train_run=sys.argv[sys.argv.index("--leaderboard") + 1]) else: # The evaluator must be deployed, with its trigger active, before the first checkpoint lands. flyte.deploy(evals.eval_env) if "--smoke" in sys.argv: run = flyte.run(train_and_watch, profile="smoke", train_examples=1_600, n_checkpoints=2, wait_minutes=20) else: run = flyte.run(train_and_watch) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/checkpoint_evals/train.py* ## Results A run with the defaults fine-tuned SmolLM2-360M on 50,000 MetaMathQA problems: 1,562 optimizer steps in 13.6 minutes on one L40S. The trainer published step 0 and eight checkpoints, and the trigger started nine eval runs, each scoring 1,319 GSM8K problems, all 2,376 ARC-Easy questions, and 2,000 MMLU questions on three L4s. Each eval run took about 80 seconds. The first checkpoints came 25 to 50 seconds apart, so their eval runs overlapped each other and training; from step 390 on, checkpoints were 100 to 200 seconds apart and each eval run finished before the next checkpoint was saved. The last scores landed within two minutes of the end of training, and the whole run took 19 minutes. | Step | GSM8K | ARC-Easy | MMLU (guard) | Ship rule | | --- | --- | --- | --- | --- | | 0 (base) | 3.1 | 68.1 | 35.9 | base model | | 49 | 6.1 | 59.7 | 36.1 | passes | | 98 | 11.1 | 57.7 | 35.5 | passes | | 195 | 15.1 | 57.2 | 35.5 | passes | | 390 | 16.3 | 54.7 | 34.8 | passes | | 586 | 20.2 | 55.0 | 34.4 | passes | | 781 | 21.6 | 55.1 | 34.5 | passes | | 1172 | 23.3 | 54.6 | 33.6 | fails | | 1562 | 23.8 | 54.4 | 33.9 | release candidate | Accuracy in percent. One standard error is about 1.2 points on GSM8K and 1.1 on MMLU. ![The trainer's report: the release candidate, learning curves for GSM8K, ARC-Easy and the MMLU guard, and the checkpoints-by-benchmarks table with the ship rule](../../../_static/images/tutorials/checkpoint-evals/leaderboard.png) GSM8K goes from 3% to 24%. Most of the gain comes early: more than half of it by step 195, an eighth of the way through. The base model mostly answers with a bare number; the fine-tuned one works the problem step by step and ends with "The answer is", the MetaMathQA format. ![The timeline of eval runs against training, with the early evals overlapping each other and every eval running while training continues, and GSM8K answers from the base model and the release candidate](../../../_static/images/tutorials/checkpoint-evals/timeline-generations.png) MMLU drifts down by about two points, which is exactly the guard's limit. Step 1172 fails the guard at 33.6, and step 1562 passes at 33.85, so the last checkpoint became the release candidate. In an earlier run with the same settings, both of the last two checkpoints scored just under the limit and the ship rule picked step 781 instead. The limit is 2 points, and one standard error of a single MMLU score is 1.1 points, but what the rule compares is the difference between two scores on the same 2,000 questions. A fixed threshold on that difference decides on noise near the boundary. A paired test, such as McNemar's test on the per-question right and wrong answers of the base model and the checkpoint, tells whether a drop is real; a larger guard set narrows the noise. ARC-Easy is the surprise: it falls 13 points, most of it in the first 49 steps. The ship rule does not look at it, so this regression would ship. ## Add a benchmark to every checkpoint Was the ARC-Easy drop real? Its prompt, `Question: ...` followed by `Answer:`, is exactly the SFT prompt, so a fine-tuned model may expect a worked solution there rather than a short answer. `benchmarks.py` has a second ARC prompt, `ARC_PROMPTS["2"]`, ending in `The answer is:`, the phrase that precedes the final answer in the training data. The benchmark version selects the prompt, and bumping a benchmark's version re-scores it on every checkpoint. To run the experiment, make two changes to `BENCHMARKS` in `config.py`: bump ARC-Easy to version `"2"`, and register ARC-Challenge with the same prompt. CODE11 `--backfill` re-runs the suite on every checkpoint of a training run, with extra benchmarks added. It passes the checkpoint artifacts as run inputs. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # /// """Evaluate every checkpoint: an eval suite that runs itself whenever a checkpoint is published. new version of math-sft-checkpoint โ”€โ”€(OnArtifact trigger)โ”€โ”€> evaluate_checkpoint โ”œโ”€ run_generate gsm8k (L4 GPU, vLLM) โ”œโ”€ run_choice arc_easy (L4 GPU, log-likelihood) โ””โ”€ run_choice mmlu (L4 GPU, log-likelihood, the regression guard) -> publish scores as a new version of math-sft-checkpoint-evals The evaluator knows nothing about the trainer. It is deployed once, and its trigger launches one eval run per new checkpoint version, while training keeps going. Each benchmark result is cached per (checkpoint, benchmark, benchmark version), so re-evaluating old checkpoints with a new benchmark only runs the new one. python evals.py # deploy the evaluator and its trigger python evals.py --backfill arc_challenge # add a benchmark to every checkpoint # (register it in config.BENCHMARKS first) """ import asyncio import json import sys import time import flyte import flyte.artifacts as artifacts import flyte.report from benchmarks import load_items, score_choice, score_generate from config import ( BENCHMARKS, CHECKPOINT_ARTIFACT, DEFAULT_SUITE, RESULTS_ARTIFACT, SMOKE_LIMIT, driver_image, gpu_image, ) from flyte.io import Dir, File from reports import scorecard_html # {{docs-fragment envs}} # Generative evals: one L4 per (checkpoint, benchmark). vLLM runs in the task's process, and # uses PyTorch's sampler instead of FlashInfer's, which would JIT-compile with nvcc at startup. generate_env = flyte.TaskEnvironment( name="ckpt-evals-generate", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"VLLM_ENABLE_V1_MULTIPROCESSING": "0", "VLLM_USE_FLASHINFER_SAMPLER": "0", "TOKENIZERS_PARALLELISM": "false"}, ) # Multiple-choice evals score every answer option's log-likelihood, one L4 per benchmark. choice_env = flyte.TaskEnvironment( name="ckpt-evals-choice", image=gpu_image, resources=flyte.Resources(cpu=4, memory="24Gi", gpu="L4:1", disk="40Gi"), env_vars={"TOKENIZERS_PARALLELISM": "false"}, ) eval_env = flyte.TaskEnvironment( name="ckpt-evals", image=driver_image, resources=flyte.Resources(cpu=1, memory="2Gi"), depends_on=[generate_env, choice_env], ) # The cache key is the task inputs (checkpoint, benchmark, benchmark version, limit) under one # explicit cache version, so editing a report does not throw away finished evals. EVAL_CACHE = flyte.Cache("override", version_override="checkpoint-evals-1") # {{/docs-fragment envs}} # {{docs-fragment benchmark_tasks}} @generate_env.task(cache=EVAL_CACHE, retries=1) def run_generate(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one generative benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_generate(model_dir, load_items(benchmark, limit, version), version)) @choice_env.task(cache=EVAL_CACHE, retries=1) def run_choice(checkpoint: Dir, benchmark: str, version: str, limit: int) -> str: """Score one checkpoint on one multiple-choice benchmark.""" model_dir = checkpoint.download_sync() return json.dumps(score_choice(model_dir, load_items(benchmark, limit, version), benchmark, version)) # {{/docs-fragment benchmark_tasks}} # {{docs-fragment trigger}} on_checkpoint = flyte.Trigger( name="eval_new_checkpoint", description="Run the eval suite on every new version of the math SFT checkpoint", automation=flyte.OnArtifact(name=CHECKPOINT_ARTIFACT), inputs={ "checkpoint": flyte.TriggeredArtifact, "step": flyte.TriggeredPartition("step"), "train_run": flyte.TriggeredPartition("train_run"), "profile": flyte.TriggeredPartition("profile"), }, ) # {{/docs-fragment trigger}} # {{docs-fragment evaluate}} @eval_env.task(triggers=[on_checkpoint], report=True, produces_artifacts=True) async def evaluate_checkpoint( checkpoint: Dir, step: str, train_run: str, profile: str = "full", suite: list[str] = DEFAULT_SUITE ) -> File: """Fan the suite out over one checkpoint and publish the scores as an artifact version.""" started = time.time() calls = [] for name in suite: spec = BENCHMARKS[name] limit = SMOKE_LIMIT if profile == "smoke" else spec["limit"] task = run_generate if spec["kind"] == "generate" else run_choice calls.append(task.aio(checkpoint=checkpoint, benchmark=name, version=spec["version"], limit=limit)) scores = {s["benchmark"]: s for s in map(json.loads, await asyncio.gather(*calls))} result = {"train_run": train_run, "step": int(step), "profile": profile, "checkpoint": checkpoint.path, "eval_run": flyte.ctx().action.run_name, "started_at": started, "finished_at": time.time(), "scores": scores} await flyte.report.replace.aio(scorecard_html(result), do_flush=True) path = "/tmp/scores.json" with open(path, "w") as f: json.dump(result, f) summary = ", ".join(f"{k} {v['accuracy']:.1f}" for k, v in scores.items()) return artifacts.new(await File.from_local(path), artifacts.Metadata( name=RESULTS_ARTIFACT, description=f"step {int(step)} of {train_run}: {summary}", partitions={"train_run": train_run, "step": step, "profile": profile}, attrs={k: f"{v['accuracy']:.2f}" for k, v in scores.items()}, )) # {{/docs-fragment evaluate}} # {{docs-fragment backfill}} def backfill(train_run: str, extra: list[str]) -> list[str]: """Re-run the suite plus ``extra`` benchmarks on every checkpoint of one training run. Benchmarks that already ran on a checkpoint come back from the cache; only ``extra`` runs. """ from flyte.remote import Artifact unknown = [b for b in extra if b not in BENCHMARKS] if unknown: raise ValueError(f"add {unknown} to BENCHMARKS in config.py before backfilling") suite = DEFAULT_SUITE + [b for b in extra if b not in DEFAULT_SUITE] urls = [] for art in Artifact.listall(name=CHECKPOINT_ARTIFACT, train_run=train_run, latest_per_partition=True): p = art.partitions run = flyte.run(evaluate_checkpoint, checkpoint=art, step=p["step"], train_run=train_run, profile=p["profile"], suite=suite) urls.append(run.url) return urls # {{/docs-fragment backfill}} if __name__ == "__main__": flyte.init_from_config() if "--backfill" in sys.argv: i = sys.argv.index("--backfill") for url in backfill(sys.argv[i + 1], sys.argv[i + 2:]): print(url) else: # Deploying registers the tasks and activates the trigger. flyte.deploy(eval_env) CODE12bash python evals.py --backfill arc_challenge python train.py --leaderboard ``` The backfill started nine eval runs. In each one, GSM8K and MMLU came back from the cache in a tenth of a second, and only ARC-Easy v2 and ARC-Challenge ran, about 30 and 50 seconds on an L4. The leaderboard keeps only the newest scores for each checkpoint, so the table below combines the leaderboard from before the backfill (ARC-Easy v1) with the one after it: | Step | ARC-Easy v1 | ARC-Easy v2 | ARC-Challenge | | --- | --- | --- | --- | | 0 (base) | 68.1 | 69.7 | 37.5 | | 49 | 59.7 | 64.4 | 37.5 | | 195 | 57.2 | 59.5 | 36.1 | | 781 | 55.1 | 58.7 | 35.8 | | 1562 | 54.4 | 56.4 | 35.6 | The new prompt slows the drop in the first steps, but ARC-Easy still loses 13 points by the end. The drop survives a second prompt format. ARC-Challenge, where the base model scores 37.5% against 25% for chance, moves by two points. The next ship rule should guard ARC-Easy too. With that rule, no checkpoint of this run ships, and the fix belongs in the training data, for example by mixing general text back into the math SFT. ## At real scale - **Bigger checkpoints.** A 70B checkpoint does not fit one GPU. Point `generate_env` at a multi-GPU node and set vLLM's `tensor_parallel_size`, or serve the checkpoint once as an app and point every benchmark task at it. - **A real suite.** Production suites have dozens of tasks, each with its own prompt format and scorer, often from a harness such as [OLMES](https://github.com/allenai/olmes) or lm-evaluation-harness. Each one becomes a cached task in the fan-out, with its own version. - **Pretraining runs.** A trainer that writes thousands of checkpoints can publish every Nth one, or publish them all and filter the trigger on a partition such as `eval_tier="full"`. - **Gate the run.** The driver already sees the guard scores while training runs. It can abort the training run, or page someone, when a guard drops past its limit. ## Related - **Artifacts > Publish your own artifacts** - **Triggers > Trigger on new artifact versions** - **Triggers > Trigger on partitions** - **Tasks > Configure tasks > Caching** - **Tasks > Build tasks > Reports** === PAGE: https://www.union.ai/docs/v2/union/tutorials/frontier-ai/video-data-curation === Cut long-form films into shots, score every clip for exposure, blur, on-screen text, aesthetics and motion on pools of CPU and GPU workers, caption the keepers with a small vision-language model, and publish the result as a dataset artifact. # Curate a video dataset for generative video > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/video_data_curation). Text-to-video and world models are trained on short clips, a few seconds each, with a caption that says what happens in them. Nobody films clips like that. Labs start from long footage (films, stock video, gameplay, dashcams) and build the clips themselves: cut the footage at shot boundaries, throw away the shots a model should not learn from (black frames, blur, title cards, still images, ugly frames), and caption what is left. The published recipes all have this shape. [Open-Sora 2.0](https://arxiv.org/abs/2503.09642) splits video with scene detection and then filters on aesthetic, motion, blur and OCR scores before captioning ([its data tools](https://github.com/hpcaitech/Open-Sora/blob/main/tools/datasets/README.md)); [Stable Video Diffusion](https://arxiv.org/abs/2311.15127) showed that this kind of curation measurably improves the trained model; [Panda-70M](https://arxiv.org/abs/2402.19479) captioned 70 million clips with vision-language models. At that scale the hard part is the plumbing. Decoding and shot detection are CPU work. Each scorer is a different GPU model, and loading CLIP, an optical-flow network and a text detector for every few clips wastes more time than the scoring. Captioning is a third, larger model. The filter thresholds are guesses until you have seen the score distributions, and changing one must not mean decoding a petabyte of video again. This tutorial builds that pipeline at small scale on five Blender open movies, 56 minutes of footage: - a pool of CPU workers decodes the films in two-minute chunks, finds the shots, and cuts 2 to 10 second clips, all chunks at once; - a pool of GPU workers scores every clip with CLIP and the LAION aesthetic head, RAFT optical flow, and the CRAFT text detector, each model loaded once per worker; - a second GPU pool captions the kept clips with SmolVLM2; - every stage is cached per chunk, and each caption per clip, so a new threshold reruns only the selection; - the manifest and the kept clips are published as a dataset artifact with a card, next to a report with the funnel, contact sheets per filter, histograms, captions, and throughput per stage. ## How a chunk flows through the pipeline ```mermaid flowchart LR D["curate
CPU driver"] --> C1["cut_chunk
CPU pool"] D --> C2["cut_chunk
CPU pool"] D --> C3["... 31 chunks"] C1 -- "clips, frames,
exposure, sharpness" --> S1["score_chunk
GPU pool"] C2 --> S2["score_chunk
GPU pool"] S1 -- "aesthetic, motion,
text" --> F1["select
thresholds"] S2 --> F2["select"] F1 -- "kept clips" --> V1["caption_clip x N
VLM pool"] F2 --> V2["caption_clip x N"] V1 & V2 --> M["manifest + sample
dataset artifact, report"] classDef gpu fill:#3b82f633,stroke:#3b82f6,stroke-width:1.5px classDef cpu fill:#94a3b826,stroke:#94a3b8,stroke-width:1px class S1,S2,V1,V2 gpu class D,C1,C2,C3,F1,F2,M cpu ``` The driver runs one coroutine per chunk, so a chunk moves to the GPU pool as soon as it is cut and its clips are captioned as soon as they are scored. The three pools work at the same time on different chunks. | Need | Construct | | --- | --- | | Different hardware per stage | One `TaskEnvironment` per stage: CPU for decoding, L4 GPUs for scoring and captioning | | Load each model once, not once per chunk | `flyte.ReusePolicy` on every pool; models live in module globals of the replica | | Process every chunk at once, as soon as its input is ready | One `asyncio` coroutine per chunk, `asyncio.gather` over all of them | | Change a threshold without decoding again | `cache` on every task: per chunk for cutting and scoring, per clip for captions | | Pass clips and frames between stages | `flyte.io.Dir`, one per chunk | | Hand the dataset to training | `flyte.artifacts` with a data card | | See what each filter does | `report=True`, with Filters and Captions tabs | ## Getting started You need a Union cluster with NVIDIA L4 GPUs (any CUDA GPU with 16 GB works; change `score_env` and `caption_env` in `curate.py`). The tasks download the films and the models over the internet. ```bash git clone https://github.com/unionai/unionai-examples cd unionai-examples/v2/tutorials/video_data_curation python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films, no artifact python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached ``` ## The footage The five films are Blender Foundation open movies under Creative Commons Attribution licenses: Big Buck Bunny, Sintel, Tears of Steel, Elephants Dream and Spring. Together they have what a curation pipeline has to deal with: animation and live action, fast cuts and long takes, dark scenes, title cards and scrolling credits. Tears of Steel and Elephants Dream are read straight from download.blender.org. Blender serves Big Buck Bunny and Sintel only as zip archives now, which can't be read partway, and Spring isn't on that server, so those three come from their 720p transcodes on Wikimedia Commons. ``` """The raw footage: five Blender open movies, all CC BY, and how they are split into chunks. Tears of Steel and Elephants Dream are read straight from download.blender.org. Blender now serves Big Buck Bunny and Sintel only as zip archives, which can't be seeked over HTTP, and Spring isn't on that server, so those three come from the 720p transcodes on Wikimedia Commons. Every URL is a 720p or smaller rendition that ffmpeg can seek into with HTTP range requests, so a chunk reads only its own minutes of the film. """ from dataclasses import dataclass @dataclass(frozen=True) class Source: name: str title: str url: str duration_s: float credit: str license: str = "CC BY" COMMONS = "https://upload.wikimedia.org/wikipedia/commons/transcoded" # {{docs-fragment sources}} SOURCES = { s.name: s for s in [ Source( "big_buck_bunny", "Big Buck Bunny", f"{COMMONS}/c/c0/Big_Buck_Bunny_4K.webm/Big_Buck_Bunny_4K.webm.720p.vp9.webm", 634.5, "(c) copyright 2008, Blender Foundation, peach.blender.org", "CC BY 3.0", ), Source( "sintel", "Sintel", f"{COMMONS}/f/f1/Sintel_movie_4K.webm/Sintel_movie_4K.webm.720p.vp9.webm", 888.0, "(c) copyright Blender Foundation, durian.blender.org", "CC BY 3.0", ), Source( "tears_of_steel", "Tears of Steel", "https://download.blender.org/demo/movies/ToS/tears_of_steel_720p.mov", 734.0, "(CC) Blender Foundation, mango.blender.org", "CC BY 3.0", ), Source( "elephants_dream", "Elephants Dream", "https://download.blender.org/ED/elephantsdream-720-h264-st-aac.mov", 653.0, "(c) copyright 2006, Blender Foundation, Netherlands Media Art Institute, orange.blender.org", "CC BY 2.5", ), Source( "spring", "Spring", f"{COMMONS}/a/a5/Spring_-_Blender_Open_Movie.webm/Spring_-_Blender_Open_Movie.webm.720p.vp9.webm", 464.0, "(CC) Blender Foundation, studio.blender.org", "CC BY 4.0", ), ] } # {{/docs-fragment sources}} @dataclass(frozen=True) class Chunk: """A few minutes of one film: the unit of decoding, scene detection, scoring and caching.""" source: str start_s: int end_s: int @property def id(self) -> str: return f"{self.source}-{self.start_s:04d}" # {{docs-fragment chunks}} def plan_chunks(names: list[str], chunk_s: int, head_s: int = 0, tail_s: int = 0) -> list[Chunk]: """Split each film into chunks of ``chunk_s`` seconds. With ``head_s`` and ``tail_s`` set, only the film's opening (title cards) and ending (credits) are used, which keeps a smoke run short and still gives the text filter work to do. """ chunks = [] for name in names: dur = int(SOURCES[name].duration_s) windows = [(0, dur)] if not head_s else [(0, min(head_s, dur - tail_s))] + ([(dur - tail_s, dur)] if tail_s else []) for a, b in windows: chunks += [Chunk(name, t, min(t + chunk_s, b)) for t in range(a, b, chunk_s) if min(t + chunk_s, b) - t >= 10] return chunks # {{/docs-fragment chunks}} CODE2 """The raw footage: five Blender open movies, all CC BY, and how they are split into chunks. Tears of Steel and Elephants Dream are read straight from download.blender.org. Blender now serves Big Buck Bunny and Sintel only as zip archives, which can't be seeked over HTTP, and Spring isn't on that server, so those three come from the 720p transcodes on Wikimedia Commons. Every URL is a 720p or smaller rendition that ffmpeg can seek into with HTTP range requests, so a chunk reads only its own minutes of the film. """ from dataclasses import dataclass @dataclass(frozen=True) class Source: name: str title: str url: str duration_s: float credit: str license: str = "CC BY" COMMONS = "https://upload.wikimedia.org/wikipedia/commons/transcoded" # {{docs-fragment sources}} SOURCES = { s.name: s for s in [ Source( "big_buck_bunny", "Big Buck Bunny", f"{COMMONS}/c/c0/Big_Buck_Bunny_4K.webm/Big_Buck_Bunny_4K.webm.720p.vp9.webm", 634.5, "(c) copyright 2008, Blender Foundation, peach.blender.org", "CC BY 3.0", ), Source( "sintel", "Sintel", f"{COMMONS}/f/f1/Sintel_movie_4K.webm/Sintel_movie_4K.webm.720p.vp9.webm", 888.0, "(c) copyright Blender Foundation, durian.blender.org", "CC BY 3.0", ), Source( "tears_of_steel", "Tears of Steel", "https://download.blender.org/demo/movies/ToS/tears_of_steel_720p.mov", 734.0, "(CC) Blender Foundation, mango.blender.org", "CC BY 3.0", ), Source( "elephants_dream", "Elephants Dream", "https://download.blender.org/ED/elephantsdream-720-h264-st-aac.mov", 653.0, "(c) copyright 2006, Blender Foundation, Netherlands Media Art Institute, orange.blender.org", "CC BY 2.5", ), Source( "spring", "Spring", f"{COMMONS}/a/a5/Spring_-_Blender_Open_Movie.webm/Spring_-_Blender_Open_Movie.webm.720p.vp9.webm", 464.0, "(CC) Blender Foundation, studio.blender.org", "CC BY 4.0", ), ] } # {{/docs-fragment sources}} @dataclass(frozen=True) class Chunk: """A few minutes of one film: the unit of decoding, scene detection, scoring and caching.""" source: str start_s: int end_s: int @property def id(self) -> str: return f"{self.source}-{self.start_s:04d}" # {{docs-fragment chunks}} def plan_chunks(names: list[str], chunk_s: int, head_s: int = 0, tail_s: int = 0) -> list[Chunk]: """Split each film into chunks of ``chunk_s`` seconds. With ``head_s`` and ``tail_s`` set, only the film's opening (title cards) and ending (credits) are used, which keeps a smoke run short and still gives the text filter work to do. """ chunks = [] for name in names: dur = int(SOURCES[name].duration_s) windows = [(0, dur)] if not head_s else [(0, min(head_s, dur - tail_s))] + ([(dur - tail_s, dur)] if tail_s else []) for a, b in windows: chunks += [Chunk(name, t, min(t + chunk_s, b)) for t in range(a, b, chunk_s) if min(t + chunk_s, b) - t >= 10] return chunks # {{/docs-fragment chunks}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/video_data_curation/sources.py* ## Cutting chunks into clips on the CPU `ffmpeg` reads one chunk of a remote film with HTTP range requests, so a task downloads only its own two minutes, and writes a 360p, 24 fps proxy. Every later step works on the proxy. ``` """CPU stage: decode a chunk, find the shot boundaries, cut clips, and sample their frames. Each clip keeps four sample points. At each one we save the frame and the frame two steps later: the first frames feed the aesthetic scorer, the text detector and the captioner, and the pairs feed optical flow. Exposure, sharpness and a frame-difference motion estimate are cheap enough to compute here, on the CPU, while the frames are in memory. """ import json import math import os import subprocess from concurrent.futures import ThreadPoolExecutor # Identify the client to the media servers, as Wikimedia's user-agent policy asks. USER_AGENT = "unionai-examples video-data-curation tutorial (https://github.com/unionai/unionai-examples)" FPS = 24 # every source is resampled to 24 fps HEIGHT = 360 # proxy resolution; the scorers and the captioner work at or below this MIN_S, MAX_S = 2.0, 10.0 # clip length bounds, as in Open-Sora's pipeline TRIM = 2 # frames dropped at each end of a shot, to stay clear of the cut itself GAP = 2 # frames between the two frames of a motion pair POSITIONS = (0.125, 0.375, 0.625, 0.875) # where in each clip the frames are sampled def ffmpeg(*args: str) -> None: subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *args], check=True) # {{docs-fragment decode}} def decode_window(url: str, start_s: float, duration_s: float, out: str) -> None: """Read ``duration_s`` seconds of a remote film into a 360p, 24 fps H.264 proxy. ``-ss`` before ``-i`` seeks with HTTP range requests, so only this window is downloaded. A keyframe every second keeps cutting clips out of the proxy fast and exact. """ ffmpeg("-user_agent", USER_AGENT, "-ss", str(start_s), "-i", url, "-t", str(duration_s), "-vf", f"fps={FPS},scale=-2:{HEIGHT}", "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-g", str(FPS), "-pix_fmt", "yuv420p", out) # {{/docs-fragment decode}} # {{docs-fragment shots}} def detect_shots(path: str) -> list[tuple[int, int]]: """Shot boundaries as (first frame, end frame) with PySceneDetect's adaptive content detector.""" from scenedetect import AdaptiveDetector, SceneManager, open_video video = open_video(path) manager = SceneManager() manager.add_detector(AdaptiveDetector()) manager.detect_scenes(video) return [(a.get_frames(), b.get_frames()) for a, b in manager.get_scene_list(start_in_scene=True)] def shots_to_clips(shots: list[tuple[int, int]]) -> tuple[list[tuple[int, int, int]], int]: """Trim each shot, drop the ones under 2 s, and split the ones over 10 s into equal pieces. Returns (start frame, end frame, shot index) per clip, and the number of shots dropped. """ clips, short = [], 0 for i, (a, b) in enumerate(shots): a, b = a + TRIM, b - TRIM n = b - a if n < MIN_S * FPS: short += 1 continue k = math.ceil(n / (MAX_S * FPS)) clips += [(a + round(j * n / k), a + round((j + 1) * n / k), i) for j in range(k)] return clips, short # {{/docs-fragment shots}} # {{docs-fragment sample}} def sample_frames(proxy: str, clips: list[tuple[int, int, int]], ids: list[str], out_dir: str) -> list[dict]: """One pass over the proxy: save each clip's frame pairs and compute its CPU statistics.""" import cv2 import numpy as np wanted: dict[int, list[tuple[int, int, str]]] = {} # frame -> [(clip, sample point, "a"|"b")] for c, (a, b, _) in enumerate(clips): for k, p in enumerate(POSITIONS): f = a + int(p * (b - a - GAP)) wanted.setdefault(f, []).append((c, k, "a")) wanted.setdefault(f + GAP, []).append((c, k, "b")) stats = [{"brightness": [], "sharpness": [], "frame_diff": []} for _ in clips] first: dict[tuple[int, int], np.ndarray] = {} cap = cv2.VideoCapture(proxy) f, last = 0, max(wanted) while f <= last: ok, frame = cap.read() if not ok: break for c, k, side in wanted.get(f, []): cv2.imwrite(f"{out_dir}/frames/{ids[c]}_{k}{side}.jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 92]) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if side == "a": first[(c, k)] = gray stats[c]["brightness"].append(float(gray.mean())) stats[c]["sharpness"].append(float(cv2.Laplacian(gray, cv2.CV_64F).var())) if k == 1: # a small thumbnail for the report and the card h = 108 thumb = cv2.resize(frame, (round(frame.shape[1] * h / frame.shape[0]), h), interpolation=cv2.INTER_AREA) cv2.imwrite(f"{out_dir}/thumbs/{ids[c]}.jpg", thumb, [cv2.IMWRITE_JPEG_QUALITY, 80]) else: diff = np.abs(gray.astype(np.int16) - first.pop((c, k)).astype(np.int16)).mean() stats[c]["frame_diff"].append(float(diff) / GAP) f += 1 cap.release() return [{k: round(sum(v) / max(len(v), 1), 3) for k, v in s.items()} for s in stats] # {{/docs-fragment sample}} def cut_clips(proxy: str, clips: list[tuple[int, int, int]], ids: list[str], out_dir: str, workers: int = 4) -> None: """Write each clip as its own small MP4, ready to train on or to look at.""" def cut(c: int) -> None: a, b, _ = clips[c] ffmpeg("-ss", f"{a / FPS:.3f}", "-i", proxy, "-frames:v", str(b - a), "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "24", "-pix_fmt", "yuv420p", "-movflags", "+faststart", f"{out_dir}/clips/{ids[c]}.mp4") with ThreadPoolExecutor(workers) as pool: list(pool.map(cut, range(len(clips)))) def write_index(out_dir: str, rows: list[dict]) -> None: with open(os.path.join(out_dir, "clips.json"), "w") as f: json.dump(rows, f) CODE3 """CPU stage: decode a chunk, find the shot boundaries, cut clips, and sample their frames. Each clip keeps four sample points. At each one we save the frame and the frame two steps later: the first frames feed the aesthetic scorer, the text detector and the captioner, and the pairs feed optical flow. Exposure, sharpness and a frame-difference motion estimate are cheap enough to compute here, on the CPU, while the frames are in memory. """ import json import math import os import subprocess from concurrent.futures import ThreadPoolExecutor # Identify the client to the media servers, as Wikimedia's user-agent policy asks. USER_AGENT = "unionai-examples video-data-curation tutorial (https://github.com/unionai/unionai-examples)" FPS = 24 # every source is resampled to 24 fps HEIGHT = 360 # proxy resolution; the scorers and the captioner work at or below this MIN_S, MAX_S = 2.0, 10.0 # clip length bounds, as in Open-Sora's pipeline TRIM = 2 # frames dropped at each end of a shot, to stay clear of the cut itself GAP = 2 # frames between the two frames of a motion pair POSITIONS = (0.125, 0.375, 0.625, 0.875) # where in each clip the frames are sampled def ffmpeg(*args: str) -> None: subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *args], check=True) # {{docs-fragment decode}} def decode_window(url: str, start_s: float, duration_s: float, out: str) -> None: """Read ``duration_s`` seconds of a remote film into a 360p, 24 fps H.264 proxy. ``-ss`` before ``-i`` seeks with HTTP range requests, so only this window is downloaded. A keyframe every second keeps cutting clips out of the proxy fast and exact. """ ffmpeg("-user_agent", USER_AGENT, "-ss", str(start_s), "-i", url, "-t", str(duration_s), "-vf", f"fps={FPS},scale=-2:{HEIGHT}", "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-g", str(FPS), "-pix_fmt", "yuv420p", out) # {{/docs-fragment decode}} # {{docs-fragment shots}} def detect_shots(path: str) -> list[tuple[int, int]]: """Shot boundaries as (first frame, end frame) with PySceneDetect's adaptive content detector.""" from scenedetect import AdaptiveDetector, SceneManager, open_video video = open_video(path) manager = SceneManager() manager.add_detector(AdaptiveDetector()) manager.detect_scenes(video) return [(a.get_frames(), b.get_frames()) for a, b in manager.get_scene_list(start_in_scene=True)] def shots_to_clips(shots: list[tuple[int, int]]) -> tuple[list[tuple[int, int, int]], int]: """Trim each shot, drop the ones under 2 s, and split the ones over 10 s into equal pieces. Returns (start frame, end frame, shot index) per clip, and the number of shots dropped. """ clips, short = [], 0 for i, (a, b) in enumerate(shots): a, b = a + TRIM, b - TRIM n = b - a if n < MIN_S * FPS: short += 1 continue k = math.ceil(n / (MAX_S * FPS)) clips += [(a + round(j * n / k), a + round((j + 1) * n / k), i) for j in range(k)] return clips, short # {{/docs-fragment shots}} # {{docs-fragment sample}} def sample_frames(proxy: str, clips: list[tuple[int, int, int]], ids: list[str], out_dir: str) -> list[dict]: """One pass over the proxy: save each clip's frame pairs and compute its CPU statistics.""" import cv2 import numpy as np wanted: dict[int, list[tuple[int, int, str]]] = {} # frame -> [(clip, sample point, "a"|"b")] for c, (a, b, _) in enumerate(clips): for k, p in enumerate(POSITIONS): f = a + int(p * (b - a - GAP)) wanted.setdefault(f, []).append((c, k, "a")) wanted.setdefault(f + GAP, []).append((c, k, "b")) stats = [{"brightness": [], "sharpness": [], "frame_diff": []} for _ in clips] first: dict[tuple[int, int], np.ndarray] = {} cap = cv2.VideoCapture(proxy) f, last = 0, max(wanted) while f <= last: ok, frame = cap.read() if not ok: break for c, k, side in wanted.get(f, []): cv2.imwrite(f"{out_dir}/frames/{ids[c]}_{k}{side}.jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 92]) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if side == "a": first[(c, k)] = gray stats[c]["brightness"].append(float(gray.mean())) stats[c]["sharpness"].append(float(cv2.Laplacian(gray, cv2.CV_64F).var())) if k == 1: # a small thumbnail for the report and the card h = 108 thumb = cv2.resize(frame, (round(frame.shape[1] * h / frame.shape[0]), h), interpolation=cv2.INTER_AREA) cv2.imwrite(f"{out_dir}/thumbs/{ids[c]}.jpg", thumb, [cv2.IMWRITE_JPEG_QUALITY, 80]) else: diff = np.abs(gray.astype(np.int16) - first.pop((c, k)).astype(np.int16)).mean() stats[c]["frame_diff"].append(float(diff) / GAP) f += 1 cap.release() return [{k: round(sum(v) / max(len(v), 1), 3) for k, v in s.items()} for s in stats] # {{/docs-fragment sample}} def cut_clips(proxy: str, clips: list[tuple[int, int, int]], ids: list[str], out_dir: str, workers: int = 4) -> None: """Write each clip as its own small MP4, ready to train on or to look at.""" def cut(c: int) -> None: a, b, _ = clips[c] ffmpeg("-ss", f"{a / FPS:.3f}", "-i", proxy, "-frames:v", str(b - a), "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "24", "-pix_fmt", "yuv420p", "-movflags", "+faststart", f"{out_dir}/clips/{ids[c]}.mp4") with ThreadPoolExecutor(workers) as pool: list(pool.map(cut, range(len(clips)))) def write_index(out_dir: str, rows: list[dict]) -> None: with open(os.path.join(out_dir, "clips.json"), "w") as f: json.dump(rows, f) CODE4 """CPU stage: decode a chunk, find the shot boundaries, cut clips, and sample their frames. Each clip keeps four sample points. At each one we save the frame and the frame two steps later: the first frames feed the aesthetic scorer, the text detector and the captioner, and the pairs feed optical flow. Exposure, sharpness and a frame-difference motion estimate are cheap enough to compute here, on the CPU, while the frames are in memory. """ import json import math import os import subprocess from concurrent.futures import ThreadPoolExecutor # Identify the client to the media servers, as Wikimedia's user-agent policy asks. USER_AGENT = "unionai-examples video-data-curation tutorial (https://github.com/unionai/unionai-examples)" FPS = 24 # every source is resampled to 24 fps HEIGHT = 360 # proxy resolution; the scorers and the captioner work at or below this MIN_S, MAX_S = 2.0, 10.0 # clip length bounds, as in Open-Sora's pipeline TRIM = 2 # frames dropped at each end of a shot, to stay clear of the cut itself GAP = 2 # frames between the two frames of a motion pair POSITIONS = (0.125, 0.375, 0.625, 0.875) # where in each clip the frames are sampled def ffmpeg(*args: str) -> None: subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *args], check=True) # {{docs-fragment decode}} def decode_window(url: str, start_s: float, duration_s: float, out: str) -> None: """Read ``duration_s`` seconds of a remote film into a 360p, 24 fps H.264 proxy. ``-ss`` before ``-i`` seeks with HTTP range requests, so only this window is downloaded. A keyframe every second keeps cutting clips out of the proxy fast and exact. """ ffmpeg("-user_agent", USER_AGENT, "-ss", str(start_s), "-i", url, "-t", str(duration_s), "-vf", f"fps={FPS},scale=-2:{HEIGHT}", "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-g", str(FPS), "-pix_fmt", "yuv420p", out) # {{/docs-fragment decode}} # {{docs-fragment shots}} def detect_shots(path: str) -> list[tuple[int, int]]: """Shot boundaries as (first frame, end frame) with PySceneDetect's adaptive content detector.""" from scenedetect import AdaptiveDetector, SceneManager, open_video video = open_video(path) manager = SceneManager() manager.add_detector(AdaptiveDetector()) manager.detect_scenes(video) return [(a.get_frames(), b.get_frames()) for a, b in manager.get_scene_list(start_in_scene=True)] def shots_to_clips(shots: list[tuple[int, int]]) -> tuple[list[tuple[int, int, int]], int]: """Trim each shot, drop the ones under 2 s, and split the ones over 10 s into equal pieces. Returns (start frame, end frame, shot index) per clip, and the number of shots dropped. """ clips, short = [], 0 for i, (a, b) in enumerate(shots): a, b = a + TRIM, b - TRIM n = b - a if n < MIN_S * FPS: short += 1 continue k = math.ceil(n / (MAX_S * FPS)) clips += [(a + round(j * n / k), a + round((j + 1) * n / k), i) for j in range(k)] return clips, short # {{/docs-fragment shots}} # {{docs-fragment sample}} def sample_frames(proxy: str, clips: list[tuple[int, int, int]], ids: list[str], out_dir: str) -> list[dict]: """One pass over the proxy: save each clip's frame pairs and compute its CPU statistics.""" import cv2 import numpy as np wanted: dict[int, list[tuple[int, int, str]]] = {} # frame -> [(clip, sample point, "a"|"b")] for c, (a, b, _) in enumerate(clips): for k, p in enumerate(POSITIONS): f = a + int(p * (b - a - GAP)) wanted.setdefault(f, []).append((c, k, "a")) wanted.setdefault(f + GAP, []).append((c, k, "b")) stats = [{"brightness": [], "sharpness": [], "frame_diff": []} for _ in clips] first: dict[tuple[int, int], np.ndarray] = {} cap = cv2.VideoCapture(proxy) f, last = 0, max(wanted) while f <= last: ok, frame = cap.read() if not ok: break for c, k, side in wanted.get(f, []): cv2.imwrite(f"{out_dir}/frames/{ids[c]}_{k}{side}.jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 92]) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if side == "a": first[(c, k)] = gray stats[c]["brightness"].append(float(gray.mean())) stats[c]["sharpness"].append(float(cv2.Laplacian(gray, cv2.CV_64F).var())) if k == 1: # a small thumbnail for the report and the card h = 108 thumb = cv2.resize(frame, (round(frame.shape[1] * h / frame.shape[0]), h), interpolation=cv2.INTER_AREA) cv2.imwrite(f"{out_dir}/thumbs/{ids[c]}.jpg", thumb, [cv2.IMWRITE_JPEG_QUALITY, 80]) else: diff = np.abs(gray.astype(np.int16) - first.pop((c, k)).astype(np.int16)).mean() stats[c]["frame_diff"].append(float(diff) / GAP) f += 1 cap.release() return [{k: round(sum(v) / max(len(v), 1), 3) for k, v in s.items()} for s in stats] # {{/docs-fragment sample}} def cut_clips(proxy: str, clips: list[tuple[int, int, int]], ids: list[str], out_dir: str, workers: int = 4) -> None: """Write each clip as its own small MP4, ready to train on or to look at.""" def cut(c: int) -> None: a, b, _ = clips[c] ffmpeg("-ss", f"{a / FPS:.3f}", "-i", proxy, "-frames:v", str(b - a), "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "24", "-pix_fmt", "yuv420p", "-movflags", "+faststart", f"{out_dir}/clips/{ids[c]}.mp4") with ThreadPoolExecutor(workers) as pool: list(pool.map(cut, range(len(clips)))) def write_index(out_dir: str, rows: list[dict]) -> None: with open(os.path.join(out_dir, "clips.json"), "w") as f: json.dump(rows, f) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/video_data_curation/shots.py* The task returns a `Dir` with the clips as MP4 files, their frames and thumbnails, and an index, plus the same index as JSON for the driver: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} CODE5 """GPU stage: aesthetic, motion and text scores for every clip, and captions for the kept ones. Models are loaded on first use and kept in module globals. In a reusable environment the Python process outlives the task call, so each replica loads each model once and every later call on that replica reuses it. """ import socket import threading import time import shots AESTHETIC_HEAD = ( "https://github.com/christophschuhmann/improved-aesthetic-predictor/raw/main/sac%2Blogos%2Bava1-l14-linearMSE.pth" ) _models: dict = {} _lock = threading.Lock() def replica() -> str: return socket.gethostname() # {{docs-fragment load}} def scorers() -> dict: """CLIP ViT-L/14 with the LAION aesthetic head, RAFT optical flow, and the CRAFT text detector.""" with _lock: if "clip" in _models: return _models import easyocr import torch from torchvision.models.optical_flow import Raft_Large_Weights, raft_large from transformers import CLIPModel, CLIPProcessor t0 = time.time() clip_id = "openai/clip-vit-large-patch14" head = torch.nn.Sequential( # the improved-aesthetic-predictor MLP, on L2-normalized CLIP embeddings torch.nn.Linear(768, 1024), torch.nn.Dropout(0.2), torch.nn.Linear(1024, 128), torch.nn.Dropout(0.2), torch.nn.Linear(128, 64), torch.nn.Dropout(0.1), torch.nn.Linear(64, 16), torch.nn.Linear(16, 1), ) state = torch.hub.load_state_dict_from_url(AESTHETIC_HEAD, map_location="cpu", file_name="aesthetic-l14.pth") head.load_state_dict({k.removeprefix("layers."): v for k, v in state.items()}) weights = Raft_Large_Weights.DEFAULT _models.update( clip=CLIPModel.from_pretrained(clip_id, torch_dtype=torch.float16).cuda().eval(), clip_processor=CLIPProcessor.from_pretrained(clip_id), aesthetic=head.cuda().eval(), raft=raft_large(weights=weights).cuda().eval(), raft_transforms=weights.transforms(), # Detection only: we need where the text is, not what it says. ocr=easyocr.Reader(["en"], gpu=True, recognizer=False, verbose=False), load_s=round(time.time() - t0, 1), ) print(f"loaded scorers on {replica()} in {_models['load_s']}s") return _models # {{/docs-fragment load}} def _frames(chunk_dir: str, clip_id: str, side: str = "a"): from PIL import Image return [Image.open(f"{chunk_dir}/frames/{clip_id}_{k}{side}.jpg").convert("RGB") for k in range(len(shots.POSITIONS))] # {{docs-fragment score}} def aesthetic(m: dict, images: list) -> list[float]: """The LAION aesthetic predictor (a 1 to 10 scale) on each image.""" import torch with torch.inference_mode(): pixels = m["clip_processor"](images=images, return_tensors="pt")["pixel_values"].cuda().half() emb = m["clip"].get_image_features(pixel_values=pixels).float() return m["aesthetic"](emb / emb.norm(dim=-1, keepdim=True)).squeeze(-1).tolist() def motion(m: dict, firsts: list, seconds: list, height: int = 256) -> list[float]: """Mean RAFT optical-flow magnitude per pair, in pixels per frame at ``height`` px tall.""" import numpy as np import torch import torch.nn.functional as F w = round(firsts[0].width * height / firsts[0].height / 8) * 8 # RAFT needs sides divisible by 8 def batch(images): t = torch.from_numpy(np.stack([np.asarray(i) for i in images])).permute(0, 3, 1, 2).cuda() return F.interpolate(t.float(), size=(height, w), mode="bilinear", antialias=True).clamp(0, 255).to(torch.uint8) with torch.inference_mode(): a, b = m["raft_transforms"](batch(firsts), batch(seconds)) flow = m["raft"](a, b)[-1] # the last of RAFT's iterative refinements return (flow.norm(dim=1).mean(dim=(1, 2)) / shots.GAP).tolist() def text_area(m: dict, images: list) -> list[float]: """Share of each frame covered by detected text boxes.""" import numpy as np out = [] for img in images: arr = np.asarray(img) boxes, polys = m["ocr"].detect(arr) area = sum((x1 - x0) * (y1 - y0) for x0, x1, y0, y1 in boxes[0]) for p in polys[0]: # rotated boxes, by the shoelace formula xs, ys = [q[0] for q in p], [q[1] for q in p] area += abs(sum(xs[i] * ys[i - 1] - xs[i - 1] * ys[i] for i in range(len(p)))) / 2 out.append(min(area / (arr.shape[0] * arr.shape[1]), 1.0)) return out def score_clips(chunk_dir: str, clip_ids: list[str]) -> tuple[list[dict], dict]: """Score every clip of one chunk. Returns per-clip scores and GPU seconds per scorer.""" import torch m = scorers() seconds = {"aesthetic": 0.0, "motion": 0.0, "text": 0.0} rows = [] for cid in clip_ids: firsts, pairs = _frames(chunk_dir, cid, "a"), _frames(chunk_dir, cid, "b") row = {"id": cid} for name, fn, agg in ( ("aesthetic", lambda: aesthetic(m, firsts), lambda v: sum(v) / len(v)), ("motion", lambda: motion(m, firsts, pairs), lambda v: sum(v) / len(v)), ("text", lambda: text_area(m, firsts), max), # a title card in any sampled frame counts ): t0 = time.time() row[name] = round(float(agg(fn())), 4) torch.cuda.synchronize() seconds[name] += time.time() - t0 rows.append(row) return rows, {k: round(v, 2) for k, v in seconds.items()} # {{/docs-fragment score}} CAPTION_PROMPT = ( "These are four frames from one short video clip, in order. Write one sentence of at most 40 " "words that describes the clip for a text-to-video training set: the main subject, what " "happens, the setting, and how the camera moves. Describe only what you can see." ) # {{docs-fragment caption}} def captioner(model_id: str) -> tuple[dict, float]: """The captioning model and its processor; also how long this call spent loading them (0 if warm).""" with _lock: if _models.get("vlm_id") == model_id: return _models, 0.0 import torch from transformers import AutoModelForImageTextToText, AutoProcessor t0 = time.time() processor = AutoProcessor.from_pretrained(model_id) processor.image_processor.do_image_splitting = False # one tile per frame is plenty at 360p model = AutoModelForImageTextToText.from_pretrained(model_id, torch_dtype=torch.bfloat16).cuda().eval() _models.update(vlm_id=model_id, vlm=model, vlm_processor=processor) load_s = round(time.time() - t0, 1) print(f"loaded {model_id} on {replica()} in {load_s}s") return _models, load_s def caption(model_id: str, chunk_dir: str, clip_id: str, max_new_tokens: int = 72) -> tuple[str, float, float]: """Caption one clip from its four sampled frames. Returns the caption, GPU seconds and load seconds.""" import torch m, load_s = captioner(model_id) images = _frames(chunk_dir, clip_id, "a") content = [{"type": "image"} for _ in images] + [{"type": "text", "text": CAPTION_PROMPT}] processor = m["vlm_processor"] prompt = processor.apply_chat_template([{"role": "user", "content": content}], add_generation_prompt=True) with _lock: # one generation at a time on the GPU; downloads for other calls overlap with it t0 = time.time() inputs = processor(text=prompt, images=[images], return_tensors="pt").to("cuda", dtype=torch.bfloat16) with torch.inference_mode(): out = m["vlm"].generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False) text = processor.batch_decode(out[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0] return " ".join(text.split()), time.time() - t0, load_s # {{/docs-fragment caption}} CODE6 """GPU stage: aesthetic, motion and text scores for every clip, and captions for the kept ones. Models are loaded on first use and kept in module globals. In a reusable environment the Python process outlives the task call, so each replica loads each model once and every later call on that replica reuses it. """ import socket import threading import time import shots AESTHETIC_HEAD = ( "https://github.com/christophschuhmann/improved-aesthetic-predictor/raw/main/sac%2Blogos%2Bava1-l14-linearMSE.pth" ) _models: dict = {} _lock = threading.Lock() def replica() -> str: return socket.gethostname() # {{docs-fragment load}} def scorers() -> dict: """CLIP ViT-L/14 with the LAION aesthetic head, RAFT optical flow, and the CRAFT text detector.""" with _lock: if "clip" in _models: return _models import easyocr import torch from torchvision.models.optical_flow import Raft_Large_Weights, raft_large from transformers import CLIPModel, CLIPProcessor t0 = time.time() clip_id = "openai/clip-vit-large-patch14" head = torch.nn.Sequential( # the improved-aesthetic-predictor MLP, on L2-normalized CLIP embeddings torch.nn.Linear(768, 1024), torch.nn.Dropout(0.2), torch.nn.Linear(1024, 128), torch.nn.Dropout(0.2), torch.nn.Linear(128, 64), torch.nn.Dropout(0.1), torch.nn.Linear(64, 16), torch.nn.Linear(16, 1), ) state = torch.hub.load_state_dict_from_url(AESTHETIC_HEAD, map_location="cpu", file_name="aesthetic-l14.pth") head.load_state_dict({k.removeprefix("layers."): v for k, v in state.items()}) weights = Raft_Large_Weights.DEFAULT _models.update( clip=CLIPModel.from_pretrained(clip_id, torch_dtype=torch.float16).cuda().eval(), clip_processor=CLIPProcessor.from_pretrained(clip_id), aesthetic=head.cuda().eval(), raft=raft_large(weights=weights).cuda().eval(), raft_transforms=weights.transforms(), # Detection only: we need where the text is, not what it says. ocr=easyocr.Reader(["en"], gpu=True, recognizer=False, verbose=False), load_s=round(time.time() - t0, 1), ) print(f"loaded scorers on {replica()} in {_models['load_s']}s") return _models # {{/docs-fragment load}} def _frames(chunk_dir: str, clip_id: str, side: str = "a"): from PIL import Image return [Image.open(f"{chunk_dir}/frames/{clip_id}_{k}{side}.jpg").convert("RGB") for k in range(len(shots.POSITIONS))] # {{docs-fragment score}} def aesthetic(m: dict, images: list) -> list[float]: """The LAION aesthetic predictor (a 1 to 10 scale) on each image.""" import torch with torch.inference_mode(): pixels = m["clip_processor"](images=images, return_tensors="pt")["pixel_values"].cuda().half() emb = m["clip"].get_image_features(pixel_values=pixels).float() return m["aesthetic"](emb / emb.norm(dim=-1, keepdim=True)).squeeze(-1).tolist() def motion(m: dict, firsts: list, seconds: list, height: int = 256) -> list[float]: """Mean RAFT optical-flow magnitude per pair, in pixels per frame at ``height`` px tall.""" import numpy as np import torch import torch.nn.functional as F w = round(firsts[0].width * height / firsts[0].height / 8) * 8 # RAFT needs sides divisible by 8 def batch(images): t = torch.from_numpy(np.stack([np.asarray(i) for i in images])).permute(0, 3, 1, 2).cuda() return F.interpolate(t.float(), size=(height, w), mode="bilinear", antialias=True).clamp(0, 255).to(torch.uint8) with torch.inference_mode(): a, b = m["raft_transforms"](batch(firsts), batch(seconds)) flow = m["raft"](a, b)[-1] # the last of RAFT's iterative refinements return (flow.norm(dim=1).mean(dim=(1, 2)) / shots.GAP).tolist() def text_area(m: dict, images: list) -> list[float]: """Share of each frame covered by detected text boxes.""" import numpy as np out = [] for img in images: arr = np.asarray(img) boxes, polys = m["ocr"].detect(arr) area = sum((x1 - x0) * (y1 - y0) for x0, x1, y0, y1 in boxes[0]) for p in polys[0]: # rotated boxes, by the shoelace formula xs, ys = [q[0] for q in p], [q[1] for q in p] area += abs(sum(xs[i] * ys[i - 1] - xs[i - 1] * ys[i] for i in range(len(p)))) / 2 out.append(min(area / (arr.shape[0] * arr.shape[1]), 1.0)) return out def score_clips(chunk_dir: str, clip_ids: list[str]) -> tuple[list[dict], dict]: """Score every clip of one chunk. Returns per-clip scores and GPU seconds per scorer.""" import torch m = scorers() seconds = {"aesthetic": 0.0, "motion": 0.0, "text": 0.0} rows = [] for cid in clip_ids: firsts, pairs = _frames(chunk_dir, cid, "a"), _frames(chunk_dir, cid, "b") row = {"id": cid} for name, fn, agg in ( ("aesthetic", lambda: aesthetic(m, firsts), lambda v: sum(v) / len(v)), ("motion", lambda: motion(m, firsts, pairs), lambda v: sum(v) / len(v)), ("text", lambda: text_area(m, firsts), max), # a title card in any sampled frame counts ): t0 = time.time() row[name] = round(float(agg(fn())), 4) torch.cuda.synchronize() seconds[name] += time.time() - t0 rows.append(row) return rows, {k: round(v, 2) for k, v in seconds.items()} # {{/docs-fragment score}} CAPTION_PROMPT = ( "These are four frames from one short video clip, in order. Write one sentence of at most 40 " "words that describes the clip for a text-to-video training set: the main subject, what " "happens, the setting, and how the camera moves. Describe only what you can see." ) # {{docs-fragment caption}} def captioner(model_id: str) -> tuple[dict, float]: """The captioning model and its processor; also how long this call spent loading them (0 if warm).""" with _lock: if _models.get("vlm_id") == model_id: return _models, 0.0 import torch from transformers import AutoModelForImageTextToText, AutoProcessor t0 = time.time() processor = AutoProcessor.from_pretrained(model_id) processor.image_processor.do_image_splitting = False # one tile per frame is plenty at 360p model = AutoModelForImageTextToText.from_pretrained(model_id, torch_dtype=torch.bfloat16).cuda().eval() _models.update(vlm_id=model_id, vlm=model, vlm_processor=processor) load_s = round(time.time() - t0, 1) print(f"loaded {model_id} on {replica()} in {load_s}s") return _models, load_s def caption(model_id: str, chunk_dir: str, clip_id: str, max_new_tokens: int = 72) -> tuple[str, float, float]: """Caption one clip from its four sampled frames. Returns the caption, GPU seconds and load seconds.""" import torch m, load_s = captioner(model_id) images = _frames(chunk_dir, clip_id, "a") content = [{"type": "image"} for _ in images] + [{"type": "text", "text": CAPTION_PROMPT}] processor = m["vlm_processor"] prompt = processor.apply_chat_template([{"role": "user", "content": content}], add_generation_prompt=True) with _lock: # one generation at a time on the GPU; downloads for other calls overlap with it t0 = time.time() inputs = processor(text=prompt, images=[images], return_tensors="pt").to("cuda", dtype=torch.bfloat16) with torch.inference_mode(): out = m["vlm"].generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False) text = processor.batch_decode(out[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0] return " ".join(text.split()), time.time() - t0, load_s # {{/docs-fragment caption}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/video_data_curation/scoring.py* The task downloads one chunk's `Dir` and runs the scorers in a thread, so the replica's event loop stays responsive: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} CODE7 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} CODE8 """GPU stage: aesthetic, motion and text scores for every clip, and captions for the kept ones. Models are loaded on first use and kept in module globals. In a reusable environment the Python process outlives the task call, so each replica loads each model once and every later call on that replica reuses it. """ import socket import threading import time import shots AESTHETIC_HEAD = ( "https://github.com/christophschuhmann/improved-aesthetic-predictor/raw/main/sac%2Blogos%2Bava1-l14-linearMSE.pth" ) _models: dict = {} _lock = threading.Lock() def replica() -> str: return socket.gethostname() # {{docs-fragment load}} def scorers() -> dict: """CLIP ViT-L/14 with the LAION aesthetic head, RAFT optical flow, and the CRAFT text detector.""" with _lock: if "clip" in _models: return _models import easyocr import torch from torchvision.models.optical_flow import Raft_Large_Weights, raft_large from transformers import CLIPModel, CLIPProcessor t0 = time.time() clip_id = "openai/clip-vit-large-patch14" head = torch.nn.Sequential( # the improved-aesthetic-predictor MLP, on L2-normalized CLIP embeddings torch.nn.Linear(768, 1024), torch.nn.Dropout(0.2), torch.nn.Linear(1024, 128), torch.nn.Dropout(0.2), torch.nn.Linear(128, 64), torch.nn.Dropout(0.1), torch.nn.Linear(64, 16), torch.nn.Linear(16, 1), ) state = torch.hub.load_state_dict_from_url(AESTHETIC_HEAD, map_location="cpu", file_name="aesthetic-l14.pth") head.load_state_dict({k.removeprefix("layers."): v for k, v in state.items()}) weights = Raft_Large_Weights.DEFAULT _models.update( clip=CLIPModel.from_pretrained(clip_id, torch_dtype=torch.float16).cuda().eval(), clip_processor=CLIPProcessor.from_pretrained(clip_id), aesthetic=head.cuda().eval(), raft=raft_large(weights=weights).cuda().eval(), raft_transforms=weights.transforms(), # Detection only: we need where the text is, not what it says. ocr=easyocr.Reader(["en"], gpu=True, recognizer=False, verbose=False), load_s=round(time.time() - t0, 1), ) print(f"loaded scorers on {replica()} in {_models['load_s']}s") return _models # {{/docs-fragment load}} def _frames(chunk_dir: str, clip_id: str, side: str = "a"): from PIL import Image return [Image.open(f"{chunk_dir}/frames/{clip_id}_{k}{side}.jpg").convert("RGB") for k in range(len(shots.POSITIONS))] # {{docs-fragment score}} def aesthetic(m: dict, images: list) -> list[float]: """The LAION aesthetic predictor (a 1 to 10 scale) on each image.""" import torch with torch.inference_mode(): pixels = m["clip_processor"](images=images, return_tensors="pt")["pixel_values"].cuda().half() emb = m["clip"].get_image_features(pixel_values=pixels).float() return m["aesthetic"](emb / emb.norm(dim=-1, keepdim=True)).squeeze(-1).tolist() def motion(m: dict, firsts: list, seconds: list, height: int = 256) -> list[float]: """Mean RAFT optical-flow magnitude per pair, in pixels per frame at ``height`` px tall.""" import numpy as np import torch import torch.nn.functional as F w = round(firsts[0].width * height / firsts[0].height / 8) * 8 # RAFT needs sides divisible by 8 def batch(images): t = torch.from_numpy(np.stack([np.asarray(i) for i in images])).permute(0, 3, 1, 2).cuda() return F.interpolate(t.float(), size=(height, w), mode="bilinear", antialias=True).clamp(0, 255).to(torch.uint8) with torch.inference_mode(): a, b = m["raft_transforms"](batch(firsts), batch(seconds)) flow = m["raft"](a, b)[-1] # the last of RAFT's iterative refinements return (flow.norm(dim=1).mean(dim=(1, 2)) / shots.GAP).tolist() def text_area(m: dict, images: list) -> list[float]: """Share of each frame covered by detected text boxes.""" import numpy as np out = [] for img in images: arr = np.asarray(img) boxes, polys = m["ocr"].detect(arr) area = sum((x1 - x0) * (y1 - y0) for x0, x1, y0, y1 in boxes[0]) for p in polys[0]: # rotated boxes, by the shoelace formula xs, ys = [q[0] for q in p], [q[1] for q in p] area += abs(sum(xs[i] * ys[i - 1] - xs[i - 1] * ys[i] for i in range(len(p)))) / 2 out.append(min(area / (arr.shape[0] * arr.shape[1]), 1.0)) return out def score_clips(chunk_dir: str, clip_ids: list[str]) -> tuple[list[dict], dict]: """Score every clip of one chunk. Returns per-clip scores and GPU seconds per scorer.""" import torch m = scorers() seconds = {"aesthetic": 0.0, "motion": 0.0, "text": 0.0} rows = [] for cid in clip_ids: firsts, pairs = _frames(chunk_dir, cid, "a"), _frames(chunk_dir, cid, "b") row = {"id": cid} for name, fn, agg in ( ("aesthetic", lambda: aesthetic(m, firsts), lambda v: sum(v) / len(v)), ("motion", lambda: motion(m, firsts, pairs), lambda v: sum(v) / len(v)), ("text", lambda: text_area(m, firsts), max), # a title card in any sampled frame counts ): t0 = time.time() row[name] = round(float(agg(fn())), 4) torch.cuda.synchronize() seconds[name] += time.time() - t0 rows.append(row) return rows, {k: round(v, 2) for k, v in seconds.items()} # {{/docs-fragment score}} CAPTION_PROMPT = ( "These are four frames from one short video clip, in order. Write one sentence of at most 40 " "words that describes the clip for a text-to-video training set: the main subject, what " "happens, the setting, and how the camera moves. Describe only what you can see." ) # {{docs-fragment caption}} def captioner(model_id: str) -> tuple[dict, float]: """The captioning model and its processor; also how long this call spent loading them (0 if warm).""" with _lock: if _models.get("vlm_id") == model_id: return _models, 0.0 import torch from transformers import AutoModelForImageTextToText, AutoProcessor t0 = time.time() processor = AutoProcessor.from_pretrained(model_id) processor.image_processor.do_image_splitting = False # one tile per frame is plenty at 360p model = AutoModelForImageTextToText.from_pretrained(model_id, torch_dtype=torch.bfloat16).cuda().eval() _models.update(vlm_id=model_id, vlm=model, vlm_processor=processor) load_s = round(time.time() - t0, 1) print(f"loaded {model_id} on {replica()} in {load_s}s") return _models, load_s def caption(model_id: str, chunk_dir: str, clip_id: str, max_new_tokens: int = 72) -> tuple[str, float, float]: """Caption one clip from its four sampled frames. Returns the caption, GPU seconds and load seconds.""" import torch m, load_s = captioner(model_id) images = _frames(chunk_dir, clip_id, "a") content = [{"type": "image"} for _ in images] + [{"type": "text", "text": CAPTION_PROMPT}] processor = m["vlm_processor"] prompt = processor.apply_chat_template([{"role": "user", "content": content}], add_generation_prompt=True) with _lock: # one generation at a time on the GPU; downloads for other calls overlap with it t0 = time.time() inputs = processor(text=prompt, images=[images], return_tensors="pt").to("cuda", dtype=torch.bfloat16) with torch.inference_mode(): out = m["vlm"].generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False) text = processor.batch_decode(out[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0] return " ".join(text.split()), time.time() - t0, load_s # {{/docs-fragment caption}} CODE9 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} CODE10 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} CODE11 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/video_data_curation/curate.py* Every task caches its results. With `cache="auto"`, the cache key covers the task's inputs and the source of the task function, but not the helper modules it calls. A fix in `shots.py` or `scoring.py` would otherwise keep serving results computed by the old code, so the cache is salted with a hash of those modules: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} CODE12 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/video_data_curation/curate.py* The dataset is a directory: a parquet manifest with one row per candidate clip (source, time range, every score, every filter result, the keep flag and the caption), every kept clip as an MP4 under `clips/`, frame strips for a sample of them, the thresholds, and the attribution the CC BY licenses require. The driver copies the kept clips out of the `cut_chunk` outputs, so the dataset doesn't depend on intermediate task outputs. The manifest still records each clip's `cut_uri` in those outputs, for looking at the rejected ones. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "curate" # params = "" # /// """Curate long-form footage into short, filtered, captioned clips for training a video model. for each chunk of a few minutes of film, all chunks at once: cut_chunk (CPU pool) decode to a 360p proxy, detect shots, cut 2-10 s clips, sample frames, exposure and sharpness score_chunk (GPU pool) aesthetic (CLIP + LAION head), motion (RAFT), text (CRAFT) select thresholds -> keep or reject, first failing filter caption_clip (VLM pool) a small vision-language model captions each kept clip manifest (parquet) + kept clips -> dataset artifact with a card; a report with the funnel, contact sheets per filter, score histograms, captions and throughput per stage This is the shape of the data pipelines behind open video generators such as Open-Sora 2.0 and Stable Video Diffusion, scaled down to five Blender open movies, 56 minutes of footage. Every stage before captioning is cached per chunk, and each caption per clip, so changing a threshold and running again recomputes only the selection and any newly kept captions. python curate.py # all five films: 31 chunks, 56 minutes python curate.py --smoke # 4 one-minute chunks from two films python curate.py --set min_aesthetic=5.0 # change a threshold; everything upstream is cached """ import asyncio import hashlib import json import os import socket import sys import tempfile import time from dataclasses import asdict, dataclass, fields from pathlib import Path import flyte import flyte.artifacts as artifacts import flyte.report import reports import scoring import shots from flyte.io import Dir, File from sources import SOURCES, plan_chunks VLM = "HuggingFaceTB/SmolVLM2-2.2B-Instruct" # {{docs-fragment cache}} # "auto" cache keys hash each task's own source, not the helper modules it calls. Salting with # a hash of those modules means editing shots.py or scoring.py invalidates the cached results. HELPERS = ("sources.py", "shots.py", "scoring.py") SALT = hashlib.sha256(b"".join((Path(__file__).parent / f).read_bytes() for f in HELPERS)).hexdigest()[:12] CACHE = flyte.Cache("auto", salt=SALT) # {{/docs-fragment cache}} # {{docs-fragment images}} # unionai-reuse provides the bridge that reusable environments need. cpu_image = ( flyte.Image.from_debian_base(name="video-curation-cpu") .with_apt_packages("ffmpeg") .with_pip_packages( "scenedetect==0.6.7", "opencv-python-headless==4.11.0.86", "numpy<2.3", "pandas==2.3.3", "pyarrow==21.0.0", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # The default PyPI wheels of torch 2.9 carry CUDA 12.8. gpu_image = ( flyte.Image.from_debian_base(name="video-curation-gpu") .with_pip_packages("torch==2.9.1", "torchvision==0.24.1") .with_pip_packages( "transformers==4.57.1", "accelerate==1.10.1", "num2words==0.5.14", "easyocr==1.7.2", "opencv-python-headless==4.11.0.86", "numpy<2.3", "Pillow==11.3.0", "unionai-reuse==0.2.1", ) ) # {{/docs-fragment images}} # {{docs-fragment envs}} # Decoding and shot detection: a warm pool of CPU replicas that takes one chunk at a time each. cpu_env = flyte.TaskEnvironment( name="video-curation-cut", image=cpu_image, resources=flyte.Resources(cpu=4, memory="8Gi", disk="20Gi"), reusable=flyte.ReusePolicy(replicas=(1, 5), concurrency=1, idle_ttl=600, scaledown_ttl=120), ) # Scoring: CLIP, RAFT and the text detector load once per replica and stay on the GPU. score_env = flyte.TaskEnvironment( name="video-curation-score", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=2, concurrency=1, idle_ttl=600), ) # Captioning: a different model with a different lifetime, so its own pool. Several calls # share a replica: while one clip generates, the next one's frames download. caption_env = flyte.TaskEnvironment( name="video-curation-caption", image=gpu_image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="L4:1"), reusable=flyte.ReusePolicy(replicas=(1, 2), concurrency=4, idle_ttl=600, scaledown_ttl=180), ) driver_env = flyte.TaskEnvironment( name="video-curation-driver", image=cpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[cpu_env, score_env, caption_env], ) # {{/docs-fragment envs}} # {{docs-fragment cut}} @cpu_env.task(cache=CACHE, retries=2) async def cut_chunk(source: str, start_s: int, end_s: int) -> tuple[Dir, str]: """Decode one chunk of a film, cut it into clips, and sample each clip's frames.""" src = SOURCES[source] out = tempfile.mkdtemp(prefix="chunk-") for sub in ("frames", "thumbs", "clips"): os.makedirs(f"{out}/{sub}") proxy = f"{tempfile.mkdtemp()}/proxy.mp4" began = t = time.time() seconds = {} shots.decode_window(src.url, start_s, end_s - start_s, proxy) seconds["decode"], t = time.time() - t, time.time() found = shots.detect_shots(proxy) clips, short = shots.shots_to_clips(found) seconds["shots"], t = time.time() - t, time.time() ids = [f"{source}-{start_s:04d}-{i:03d}" for i in range(len(clips))] stats = shots.sample_frames(proxy, clips, ids, out) shots.cut_clips(proxy, clips, ids, out) seconds["sample_and_cut"] = time.time() - t rows = [ {"id": cid, "source": source, "chunk": f"{source}-{start_s:04d}", "shot": shot, "start_s": round(start_s + a / shots.FPS, 3), "end_s": round(start_s + b / shots.FPS, 3), "duration_s": round((b - a) / shots.FPS, 3), **s} for cid, (a, b, shot), s in zip(ids, clips, stats) ] shots.write_index(out, rows) summary = {"shots": len(found), "short_shots": short, "clips": len(rows), "footage_s": end_s - start_s, "seconds": {k: round(v, 1) for k, v in seconds.items()}, "replica": socket.gethostname(), "ran": [began, time.time()]} print(f"{source} {start_s}-{end_s}s: {len(found)} shots -> {len(rows)} clips in {sum(seconds.values()):.0f}s") return await Dir.from_local(out), json.dumps({"summary": summary, "clips": rows}) # {{/docs-fragment cut}} # {{docs-fragment score}} @score_env.task(cache=CACHE, retries=2) async def score_chunk(chunk: Dir) -> str: """Aesthetic, motion and text scores for every clip of one chunk, on one GPU.""" began = time.time() local = await chunk.download() with open(f"{local}/clips.json") as f: ids = [c["id"] for c in json.load(f)] cold = "clip" not in scoring._models t0 = time.time() rows, seconds = await asyncio.to_thread(scoring.score_clips, local, ids) print(f"scored {len(ids)} clips in {time.time() - t0:.1f}s on {scoring.replica()} {seconds}") return json.dumps({"scores": rows, "seconds": seconds, "replica": scoring.replica(), "load_s": scoring._models["load_s"] if cold else 0.0, "ran": [began, time.time()]}) # {{/docs-fragment score}} # {{docs-fragment caption}} @caption_env.task(cache=CACHE, retries=2) async def caption_clip(chunk: Dir, clip_id: str, model: str = VLM) -> str: """Caption one kept clip from its four sampled frames. Cached per clip.""" began = time.time() local = tempfile.mkdtemp() os.makedirs(f"{local}/frames") await asyncio.gather(*[ File.from_existing_remote(f"{chunk.path}/frames/{clip_id}_{k}a.jpg").download(f"{local}/frames/{clip_id}_{k}a.jpg") for k in range(len(shots.POSITIONS)) ]) text, seconds, load_s = await asyncio.to_thread(scoring.caption, model, local, clip_id) return json.dumps({"caption": text, "seconds": round(seconds, 3), "replica": scoring.replica(), "load_s": load_s, "ran": [began, time.time()]}) # {{/docs-fragment caption}} # {{docs-fragment select}} @dataclass class Thresholds: """Every clip must pass all five filters. Tune them on the report's histograms.""" min_brightness: float = 20.0 # mean luma over the 4 frames, 0-255: drops dark and mostly black shots max_brightness: float = 235.0 # drops white flashes min_sharpness: float = 20.0 # variance of the Laplacian at 360p: drops blurry frames max_text: float = 0.02 # share of the frame covered by text: drops titles and credits min_aesthetic: float = 4.5 # LAION aesthetic score, 1-10 min_motion: float = 0.1 # optical flow, px per frame at 256 px tall: drops still shots max_motion: float = 20.0 # drops whip pans and flashes that flow can't follow FILTERS = ("exposure", "blur", "text", "aesthetic", "motion") def select(clip: dict, t: Thresholds) -> dict: """Which filters a clip passes, the first one it fails, and whether it is kept.""" passed = { "exposure": t.min_brightness <= clip["brightness"] <= t.max_brightness, "blur": clip["sharpness"] >= t.min_sharpness, "text": clip["text"] <= t.max_text, "aesthetic": clip["aesthetic"] >= t.min_aesthetic, "motion": t.min_motion <= clip["motion"] <= t.max_motion, } first_fail = next((f for f in FILTERS if not passed[f]), "") return {**{f"pass_{f}": ok for f, ok in passed.items()}, "first_fail": first_fail, "keep": not first_fail} # {{/docs-fragment select}} async def read_remote(path: str) -> bytes: async with File.from_existing_remote(path).open("rb") as f: return bytes(await f.read()) # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def curate( sources: list[str] = list(SOURCES), chunk_s: int = 120, head_s: int = 0, tail_s: int = 0, thresholds: Thresholds = Thresholds(), vlm: str = VLM, sample_size: int = 24, publish: bool = True, ) -> Dir: """Turn whole films (or their first ``head_s`` and last ``tail_s`` seconds) into a captioned clip dataset.""" started = time.time() chunks = plan_chunks(sources, chunk_s, head_s, tail_s) clips: list[dict] = [] summaries: dict[str, dict] = {} dirs: dict[str, Dir] = {} calls: list[dict] = [] # one row per task call: stage, timing, replica, model load, cache hit lock = asyncio.Lock() async def call(stage: str, label: str, coro) -> tuple: """Await one task call and record it for the timeline and the throughput table.""" called = time.time() result = await coro info = json.loads(result[1] if stage == "cut" else result) info = info.get("summary", info) began, ended = info["ran"] # A cache hit returns the outputs of an earlier run, with that run's timestamps. row = {"stage": stage, "label": label, "replica": info["replica"], "load_s": info.get("load_s", 0.0), "cached": began < called - 1, "start": began, "end": ended} calls.append(row) return result, row async def process(chunk) -> None: with flyte.group(chunk.id): (d, cut), row = await call("cut", chunk.id, cut_chunk(chunk.source, chunk.start_s, chunk.end_s)) cut = json.loads(cut) row.update(clips=len(cut["clips"]), busy_s=sum(cut["summary"]["seconds"].values())) scored = {"scores": []} if cut["clips"]: scored, row = await call("score", chunk.id, score_chunk(d)) scored = json.loads(scored) row.update(clips=len(cut["clips"]), busy_s=sum(scored["seconds"].values()), per_scorer=scored["seconds"]) mine = [{**c, **s} for c, s in zip(cut["clips"], scored["scores"])] for c in mine: c.update(select(c, thresholds)) async def cap(c: dict) -> None: r, row = await call("caption", c["id"], caption_clip(d, c["id"], vlm)) r = json.loads(r) row.update(clips=1, busy_s=r["seconds"]) c["caption"] = r["caption"] await asyncio.gather(*[cap(c) for c in mine if c["keep"]]) async with lock: dirs[chunk.id], summaries[chunk.id] = d, cut["summary"] clips.extend(mine) await flyte.report.replace.aio( reports.live(clips, summaries, calls, len(chunks), thresholds, started, time.time()), do_flush=True) await asyncio.gather(*[process(c) for c in chunks]) wall_s = time.time() - started clips.sort(key=lambda c: c["id"]) for c in clips: c.setdefault("caption", "") c["cut_uri"] = f"{dirs[c['chunk']].path}/clips/{c['id']}.mp4" # the cut stage's copy, every clip c["clip"] = f"clips/{c['id']}.mp4" if c["keep"] else "" # inside the dataset, kept clips only # Thumbnails and frame strips for the report and the card, fetched only for the clips shown. shown = reports.pick_examples(clips, thresholds, sample_size) thumbs = dict(zip(shown["thumbs"], await asyncio.gather(*[ read_remote(f"{dirs[c.rsplit('-', 1)[0]].path}/thumbs/{c}.jpg") for c in shown["thumbs"]]))) frames = {cid: await asyncio.gather(*[read_remote(f"{dirs[cid.rsplit('-', 1)[0]].path}/frames/{cid}_{k}a.jpg") for k in range(len(shots.POSITIONS))]) for cid in shown["sample"]} out = build_dataset(clips, shown["sample"], frames, thresholds) # Copy every kept clip into the dataset, so it doesn't depend on intermediate task outputs. gate = asyncio.Semaphore(32) async def copy(c: dict) -> None: async with gate: await File.from_existing_remote(c["cut_uri"]).download(f"{out}/{c['clip']}") await asyncio.gather(*[copy(c) for c in clips if c["keep"]]) ctx = dict(clips=clips, summaries=summaries, calls=calls, thresholds=thresholds, wall_s=wall_s, origin=started, thumbs=thumbs, frames=frames, sample=shown["sample"], vlm=vlm) await flyte.report.replace.aio(reports.overview(**ctx)) flyte.report.get_tab("Filters").replace(reports.filters_tab(**ctx)) flyte.report.get_tab("Captions").replace(reports.captions_tab(**ctx)) await flyte.report.flush.aio() dataset = await Dir.from_local(out) if not publish: return dataset kept = [c for c in clips if c["keep"]] card = await artifacts.Card.create_from.aio(content=reports.card(**ctx), format="html", card_type="data") metadata = artifacts.Metadata( name="blender-open-movie-clips", kind="data", description=f"{len(kept)} captioned 2-10 s clips ({sum(c['duration_s'] for c in kept) / 60:.1f} min) " f"curated from {len(clips)} candidates in {len(sources)} Blender open movies (CC BY)", attrs={"clips": str(len(kept)), "candidates": str(len(clips)), "captioner": vlm, "thresholds": json.dumps(asdict(thresholds)), "license": "CC BY (see ATTRIBUTION.txt)"}, card=card, ) return artifacts.new(dataset, metadata) # {{/docs-fragment driver}} # {{docs-fragment manifest}} def build_dataset(clips: list[dict], sample: list[str], frames: dict, thresholds: Thresholds) -> str: """The manifest as parquet, frame strips for a sample of clips, and the attribution.""" import pandas as pd out = tempfile.mkdtemp(prefix="dataset-") os.makedirs(f"{out}/sample") os.makedirs(f"{out}/clips") columns = ["id", "source", "chunk", "shot", "start_s", "end_s", "duration_s", "brightness", "sharpness", "frame_diff", "text", "aesthetic", "motion", *[f"pass_{f}" for f in FILTERS], "first_fail", "keep", "caption", "clip", "cut_uri"] df = pd.DataFrame(clips)[columns] df["title"] = df["source"].map(lambda s: SOURCES[s].title) df["license"] = df["source"].map(lambda s: SOURCES[s].license) df.to_parquet(f"{out}/manifest.parquet", index=False) for cid in sample: with open(f"{out}/sample/{cid}.jpg", "wb") as f: f.write(reports.strip_jpeg(frames[cid])) with open(f"{out}/thresholds.json", "w") as f: json.dump(asdict(thresholds), f, indent=2) with open(f"{out}/ATTRIBUTION.txt", "w") as f: f.write("Clips cut from Blender Foundation open movies, used under Creative Commons Attribution licenses.\n\n") f.writelines(f"{s.title}: {s.credit}. {s.license}. Source: {s.url}\n" for s in SOURCES.values()) return out # {{/docs-fragment manifest}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() kwargs: dict = {} if "--smoke" in sys.argv: kwargs = dict(sources=["big_buck_bunny", "tears_of_steel"], head_s=60, tail_s=60, chunk_s=60, sample_size=8, publish=False) if "--set" in sys.argv: # e.g. --set min_aesthetic=5.0,max_text=0.01 pairs = dict(p.split("=") for p in sys.argv[sys.argv.index("--set") + 1].split(",")) names = {f.name for f in fields(Thresholds)} kwargs["thresholds"] = Thresholds(**{k: float(v) for k, v in pairs.items() if k in names}) run = flyte.run(curate, **kwargs) print(run.url) # {{/docs-fragment run}} CODE13bash python curate.py --set min_aesthetic=5.0 ``` That run took 13 seconds. All 31 cut and 31 score calls and all 222 caption calls were cache hits; the driver only reapplied the thresholds, rebuilt the manifest and the report, copied the kept clips, and published a new version of the artifact. The aesthetic filter now rejects 195 clips, and 222 remain. Lowering the threshold to 4.3 instead kept 383 clips and captioned only the 14 that were new. That run took 54 seconds, most of it starting two caption replicas. ![The rerun with a stricter aesthetic threshold: every task call is a cache hit](../../../_static/images/tutorials/video-data-curation/threshold-rerun.png) ### What the first runs taught us - **The 500M captioner was not good enough.** SmolVLM2-500M wrote three-sentence paragraphs and invented details: a man "talking to the camera" in a shot of rocket engines. The 2.2B model, asked for one sentence of what it can see, wrote captions like the ones above at 97 clips per GPU-minute on an L4. - **The motion threshold was set by looking.** A first threshold of 0.3 pixels per frame rejected slow pans and characters talking in Big Buck Bunny, which score 0.1 to 0.3. Truly still shots score under 0.05. The default is now 0.1. - **Timestamps have to come from inside the task.** Timing each call from the driver counted the time a call waited for a free replica as work, and showed every queued chunk as running from the start of the run. ## At real scale The pipeline is the same at a million hours; the numbers around it change. - **Shard by file, not by minute.** Real collections are millions of files; a chunk becomes a batch of files, and `flyte.map` or a bounded `asyncio.gather` keeps the fan-out under control. - **Batch the models.** Here each chunk scores a few dozen clips. Scoring hundreds of frames per forward pass, and captioning with a batched server such as vLLM, raises GPU throughput by an order of magnitude. - **Add the filters this sample doesn't need.** Deduplication by embedding, camera-motion classification, NSFW and watermark detection, and a quality classifier trained on human ratings all fit as more scorers in the GPU stage. - **Write clips once.** This tutorial copies the kept clips into the dataset, which is cheap for 370 clips. At scale, write each clip straight to its final, content-addressed location in the cut stage, and let the dataset be the manifest of paths. - **Keep the thresholds out of the expensive stages.** Because selection runs after the cached scores, a data team can try a new mixture of thresholds on the whole collection in minutes. ## Credits Big Buck Bunny (c) copyright 2008, Blender Foundation, peach.blender.org, CC BY 3.0. Sintel (c) copyright Blender Foundation, durian.blender.org, CC BY 3.0. Tears of Steel (CC) Blender Foundation, mango.blender.org, CC BY 3.0. Elephants Dream (c) copyright 2006, Blender Foundation, Netherlands Media Art Institute, orange.blender.org, CC BY 2.5. Spring (CC) Blender Foundation, studio.blender.org, CC BY 4.0. The frames on this page are from these films. ## Related - **Tasks > Configure tasks > Reusable containers** - **Tasks > Configure tasks > Caching** - **Tasks > Build tasks > Reports** - **Artifacts > Publish your own artifacts** === PAGE: https://www.union.ai/docs/v2/union/tutorials/frontier-ai/sparse-autoencoders === Harvest a language model's activations once, train a grid of TopK sparse autoencoders in parallel on GPUs, and have Claude label and score the features they find. # Find features in a language model with sparse autoencoders > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/sparse_autoencoders). A language model's neurons rarely mean one thing each. A single neuron fires on Korean text, on HTTP headers, and on the word "however", because the model packs more concepts into its activations than it has dimensions. Interpretability teams undo this packing with a *sparse autoencoder* (SAE): a wide, one-layer autoencoder trained to rewrite each activation vector as a sparse sum of learned directions. Each direction is a *feature*, and many of them turn out to mean one thing a person can name. Anthropic used SAEs to find millions of such features in Claude 3 Sonnet ([Scaling Monosemanticity](https://transformer-circuits.pub/2024/scaling-monosemanticity/index.html)), OpenAI trained a 16-million-feature SAE on GPT-4 and introduced the TopK SAE this tutorial uses ([Gao et al., 2024](https://arxiv.org/abs/2406.04093)), and Google DeepMind released SAEs for every layer of Gemma 2 ([Gemma Scope](https://arxiv.org/abs/2408.05147)). The work has the same shape at every lab: - **Harvest** activations from a model over a large text corpus, at the layers you care about. - **Train** one SAE per layer and per size, a grid of GPU jobs that read the same activations. - **Evaluate** every SAE on how much of the activation it reconstructs, how sparse it is, how many of its features never fire, and how much worse the model gets with the SAE spliced in. - **Label** features automatically with an LLM, and score the labels, since nobody can read millions of features by hand ([Bills et al., 2023](https://openaipublic.blob.core.windows.net/neuron-explainer/paper/index.html); [Paulo et al., 2024](https://arxiv.org/abs/2410.13928)). At scale, the harvest is the expensive part. It is many terabytes of activations, and you do not want to recompute it each time someone tries another SAE width. The grid is wide: one SAE per (layer, width, sparsity). And the labeling is hundreds of thousands of LLM calls that you do not want to pay for twice when a job retries. This tutorial runs the whole loop on Pythia-70m, a small open model, with [Claude](https://www.anthropic.com/claude) as the labeler. By the end you will have: - a cached activation harvest, stored as one directory of shards per layer; - a grid of TopK SAEs, one GPU task per (layer, width), each training three sparsities at once; - variance explained, L0, dead features, and loss recovered for every SAE; - Claude's explanation of a random sample of the features that fire often enough to test, each scored on held-out text; - a feature browser in the run's report, sorted so the most convincing features come first; - the most interpretable SAE published as an artifact with a model card. ```mermaid flowchart LR H["harvest_activations
GPU, cached"] -- "Dir per layer" --> T1["train_sae
layer 1, 4096"] H --> T2["train_sae
layer 1, 16384"] H --> T3["..."] H --> T6["train_sae
layer 5, 16384"] T2 -- "sampled features" --> L1["label_features
Claude, traced"] T6 --> L3["label_features
Claude, traced"] T1 & T3 & L1 & L3 --> D["find_features
report"] D --> A["artifact:
best SAE"] classDef gpu fill:#2a78d633,stroke:#2a78d6,stroke-width:1.5px classDef llm fill:#e8790033,stroke:#e87900,stroke-width:1.5px classDef cpu fill:#94a3b826,stroke:#94a3b8,stroke-width:1px class H,T1,T2,T3,T6 gpu class L1,L3 llm class D,A cpu ``` ## What Flyte adds | Need | Construct | | --- | --- | | Compute the activations once, and keep them | `cache="auto"` on the harvest task, which returns a `flyte.io.Dir` per layer | | Train a grid of SAEs at once | One GPU task per (layer, width), launched together with `asyncio.gather` | | Add a width without redoing the rest | Caching on every task, salted with a version for each helper module: a re-run only trains the new grid cells | | Never pay twice for the same Claude call | `@flyte.trace` on each call, so a retried task replays the recorded answer | | Watch training, then read the features | A live report per trainer, and a feature browser tab in the driver's report | | Hand the result to other teams | `flyte.artifacts` with a model card | ## Getting started You need a Union cluster with NVIDIA L4 GPUs (or any CUDA GPU with 24 GB of memory), and an Anthropic API key stored as a secret. The code reads a secret named `anthropic-api-key`. To use a secret with another name, set `ANTHROPIC_SECRET` when you launch. ```bash flyte create secret anthropic-api-key git clone https://github.com/unionai/unionai-examples cd unionai-examples/v2/tutorials/sparse_autoencoders python find_features.py # 3 layers x 2 widths, 8M tokens python find_features.py --smoke # 1 layer x 1 width, 0.5M tokens ``` ## The image and environments One image serves every task: PyTorch, Transformers and Datasets for the model, and the Anthropic SDK for the labeler. The harvest and the trainers each take one GPU. Autointerp is API calls, so it runs on CPU, and its environment is the only one that holds the API key. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "find_features" # params = "layers=[3] widths=[4096] n_tokens=500000 steps=600 features_per_sae=8" # /// """Find interpretable features in a language model with sparse autoencoders, and label them with Claude. harvest_activations (GPU, cached) Pythia-70m over FineWeb: residual stream at several layers -> Dir per layer -> N x train_sae (GPU each) one (layer, width) per task: TopK SAEs at k = 16, 32, 64, then variance explained, L0, dead features, and loss with the SAE spliced in -> M x label_features (CPU) Claude explains sampled features and is scored on held-out contexts -> report (feature browser) -> publish the most interpretable SAE as an artifact The harvest is cached on its inputs. Re-running with another width, k, or step budget reuses the activations, and every (layer, width) that was already trained, and only trains what is new. python find_features.py # 3 layers x 2 widths, 8M tokens, about 30 minutes python find_features.py --smoke # 1 layer x 1 width, 0.5M tokens python find_features.py --widths 4096 16384 32768 # reuses the harvest and the first two widths """ import argparse import asyncio import json import os import tempfile import time from dataclasses import dataclass, field from pathlib import Path import autointerp import flyte import flyte.artifacts as artifacts import flyte.report import reports from flyte.io import Dir, File MODEL = "EleutherAI/pythia-70m-deduped" CLAUDE = "claude-opus-5-5" # The name of the secret that holds your Anthropic API key. Set ANTHROPIC_SECRET when you # launch to use a secret with another name. ANTHROPIC_SECRET = os.getenv("ANTHROPIC_SECRET", "anthropic-api-key") # Bump when sae.py changes (the SAE, its training, its metrics, or feature sampling). train_sae # salts its cache with this; cache="auto" alone hashes only the task's own body. SAE_VERSION = "topk-auxk/2" # Set SAE_DEVICE=cpu to run a tiny version on a laptop with flyte's local mode. DEVICE = os.getenv("SAE_DEVICE", "cuda") # {{docs-fragment envs}} image = flyte.Image.from_debian_base(name="sae-features").with_pip_packages( "torch==2.9.1", "transformers==4.57.3", "datasets==4.4.2", "numpy<3", "anthropic==2.6.0", ) # One GPU per task: the harvest, and every SAE trainer. sae.py is imported inside the tasks. gpu_env = flyte.TaskEnvironment( name="sae-gpu", image=image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L4:1", disk="80Gi"), cache="auto", include=["sae.py"], ) # Autointerp is API calls, so CPU only. Only this environment holds the API key. interp_env = flyte.TaskEnvironment( name="sae-autointerp", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), secrets=[flyte.Secret(key=ANTHROPIC_SECRET, as_env_var="ANTHROPIC_API_KEY")], cache="auto", ) driver_env = flyte.TaskEnvironment( name="sae-driver", image=image, resources=flyte.Resources(cpu=2, memory="8Gi"), # The driver declares label_features when it calls it, so it needs the same secret name. env_vars={"ANTHROPIC_SECRET": ANTHROPIC_SECRET}, depends_on=[gpu_env, interp_env], ) # {{/docs-fragment envs}} @dataclass class Harvest: model: str dataset: str layers: list[int] ctx_len: int d_model: int n_seqs: int acts: list[Dir] # one per layer: shard_*.npy, float16 [sequences, ctx_len, d_model] tokens: File # int32 [sequences, ctx_len] @dataclass class SAEStats: layer: int width: int k: int fve: float l0: float dead_frac: float ce_clean: float ce_sae: float ce_zero: float loss_recovered: float density_hist: dict = field(default_factory=dict) @dataclass class Trained: layer: int width: int ks: list[int] stats: list[SAEStats] weights: list[File] # one per k curve: list[dict] train_s: float examples: File | None = None # sampled features with their contexts, for the k that gets labeled label_k: int = 0 # {{docs-fragment harvest}} @gpu_env.task async def harvest_activations( layers: list[int], n_tokens: int = 8_000_000, ctx_len: int = 128, dataset: str = "HuggingFaceFW/fineweb:sample-10BT", shard_seqs: int = 4096, ) -> Harvest: """Run Pythia over FineWeb and save the residual stream after each layer in ``layers``. Each context is the first ``ctx_len`` tokens of one document. Activations are float16 shards, one directory per layer, so a trainer downloads only the layer it needs. """ import numpy as np import torch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL).to(DEVICE).eval() name, _, config = dataset.partition(":") stream = load_dataset(name, name=config or None, split="train", streaming=True) n_seqs = n_tokens // ctx_len rows: list[list[int]] = [] texts: list[str] = [] for doc in stream: texts.append(doc["text"]) if len(texts) == 1000: enc = tok(texts, truncation=True, max_length=ctx_len)["input_ids"] rows += [ids for ids in enc if len(ids) == ctx_len] texts = [] if len(rows) >= n_seqs: break tokens = np.array(rows[:n_seqs], dtype=np.int32) print(f"{len(tokens):,} contexts of {ctx_len} tokens from {dataset}") captured: dict[int, torch.Tensor] = {} for layer in layers: model.gpt_neox.layers[layer].register_forward_hook( lambda _m, _i, out, layer=layer: captured.__setitem__(layer, out[0] if isinstance(out, tuple) else out)) root = Path(tempfile.mkdtemp()) for layer in layers: (root / f"layer_{layer}").mkdir() d_model = model.config.hidden_size with torch.no_grad(): for shard, s in enumerate(range(0, len(tokens), shard_seqs)): chunk = tokens[s:s + shard_seqs] out = {layer: np.empty((len(chunk), ctx_len, d_model), dtype=np.float16) for layer in layers} for b in range(0, len(chunk), 256): model(input_ids=torch.as_tensor(chunk[b:b + 256], dtype=torch.long, device=DEVICE)) for layer in layers: out[layer][b:b + 256] = captured[layer].clamp(-6e4, 6e4).half().cpu().numpy() for layer in layers: np.save(root / f"layer_{layer}" / f"shard_{shard:03d}.npy", out[layer]) np.save(root / "tokens.npy", tokens) print(f"saved {len(layers)} layers x {len(tokens) * ctx_len:,} tokens") acts = await asyncio.gather(*[Dir.from_local(str(root / f"layer_{layer}")) for layer in layers]) return Harvest(model=MODEL, dataset=dataset, layers=layers, ctx_len=ctx_len, d_model=d_model, n_seqs=len(tokens), acts=list(acts), tokens=await File.from_local(str(root / "tokens.npy"))) # {{/docs-fragment harvest}} async def load_layer(harvest: Harvest, layer: int): """Download one layer's shards and put them on the GPU, with the token ids.""" import numpy as np import torch local = Path(await harvest.acts[harvest.layers.index(layer)].download()) shards = sorted(local.rglob("shard_*.npy")) acts = torch.cat([torch.from_numpy(np.load(p)).to(DEVICE) for p in shards]) tokens = np.load(await harvest.tokens.download()) return acts, tokens # {{docs-fragment train}} @gpu_env.task(report=True, cache=flyte.Cache("auto", salt=SAE_VERSION)) async def train_sae( harvest: Harvest, layer: int, width: int, ks: list[int], steps: int = 8000, batch_size: int = 4096, label_k: int = 32, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, held_out: float = 0.05, seed: int = 0, ) -> Trained: """Train one TopK SAE per k on one layer, evaluate each on held-out text, and sample features to label.""" import sae as S import torch from transformers import AutoModelForCausalLM, AutoTokenizer torch.backends.cuda.matmul.allow_tf32 = True acts, tokens = await load_layer(harvest, layer) n_train = int(len(acts) * (1 - held_out)) print(f"layer {layer}: {n_train:,} training and {len(acts) - n_train:,} held-out contexts, width {width}, k {ks}") started = time.time() curve_so_far: list[dict] = [] def on_log(point: dict) -> None: # stream the training curves into this task's report curve_so_far.append(point) flyte.report.replace(reports.training(layer, width, ks, steps, curve_so_far, time.time() - started)) flyte.report.flush() # Training runs in a worker thread, so the report can stream from the callback. saes, scale, curve = await asyncio.to_thread(S.train, acts[:n_train], width, ks, steps, batch_size, seed=seed, on_log=on_log) train_s = time.time() - started print(f"trained {len(ks)} SAEs for {steps} steps in {train_s / 60:.1f} min") # Evaluate on held-out contexts: reconstruction, sparsity, and what the model loses with the SAE in place. model = AutoModelForCausalLM.from_pretrained(harvest.model).to(DEVICE).eval() eval_tokens = torch.as_tensor(tokens[n_train:][:512], dtype=torch.long, device=DEVICE) ce = S.spliced_losses(model, eval_tokens, layer, saes, scale) stats = [] for sae in saes: m = S.reconstruction_metrics(sae, acts[n_train:], scale) st = SAEStats(layer=layer, width=width, k=sae.k, fve=m["fve"], l0=m["l0"], dead_frac=m["dead_frac"], ce_clean=ce["clean"], ce_sae=ce[f"k{sae.k}"], ce_zero=ce["zero"], loss_recovered=S.loss_recovered(ce["clean"], ce[f"k{sae.k}"], ce["zero"]), density_hist=S.density_histogram(m["density"])) print(f" k={sae.k}: FVE {st.fve:.3f}, L0 {st.l0:.1f}, dead {st.dead_frac:.1%}, " f"loss {st.ce_clean:.3f} -> {st.ce_sae:.3f} (zero {st.ce_zero:.3f}), recovered {st.loss_recovered:.1%}") stats.append(st) out = Path(tempfile.mkdtemp()) weights = [] for sae in saes: path = out / f"sae_L{layer}_w{width}_k{sae.k}.pt" torch.save({"state_dict": sae.state_dict(), "scale": scale, "layer": layer, "width": width, "k": sae.k, "d_model": sae.d_model, "model": harvest.model, "hook": f"gpt_neox.layers.{layer} output"}, path) weights.append(await File.from_local(str(path))) examples = None if n_features and label_k in ks: tok = AutoTokenizer.from_pretrained(harvest.model) feats = S.feature_examples(saes[ks.index(label_k)], acts, tokens, scale, lambda t: tok.decode([t]), n_features=n_features, n_top=n_top, n_sampled=n_sampled, seed=seed + layer) path = out / "examples.json" path.write_text(json.dumps(feats)) examples = await File.from_local(str(path)) print(f" sampled {len(feats)} features for autointerp") return Trained(layer=layer, width=width, ks=ks, stats=stats, weights=weights, curve=curve, train_s=round(train_s, 1), examples=examples, label_k=label_k if examples else 0) # {{/docs-fragment train}} # {{docs-fragment claude}} class Unanswered(Exception): """Claude gave no complete JSON answer: a refusal, or output cut off at max_tokens.""" async def ask_claude(system: str, prompt: str, schema: dict, max_tokens: int = 4096) -> str: import anthropic client = anthropic.AsyncAnthropic(max_retries=8) message = await client.messages.create( model=CLAUDE, max_tokens=max_tokens, system=system, output_config={"effort": "low", "format": {"type": "json_schema", "schema": schema}}, messages=[{"role": "user", "content": prompt}], ) # Any thinking counts toward max_tokens, so check that the answer finished before reading it. if message.stop_reason != "end_turn": raise Unanswered(f"stop_reason={message.stop_reason}") text = next((b.text for b in message.content if b.type == "text"), None) if text is None: raise Unanswered("no text block") return text @flyte.trace async def explain_feature(layer: int, feature: int, prompt: str) -> str: """Claude's explanation of one feature. Traced, so a retried task replays it instead of paying again.""" return await ask_claude(autointerp.EXPLAIN_SYSTEM, prompt, autointerp.EXPLAIN_SCHEMA) @flyte.trace async def detect_feature(layer: int, feature: int, prompt: str) -> str: """Claude's guess of which held-out excerpts the explanation predicts. Traced, like the explanation.""" return await ask_claude(autointerp.DETECT_SYSTEM, prompt, autointerp.DETECT_SCHEMA) # {{/docs-fragment claude}} # {{docs-fragment label}} @interp_env.task(retries=1, cache=flyte.Cache("auto", salt=autointerp.VERSION)) async def label_features(layer: int, width: int, k: int, examples: File, concurrency: int = 8) -> str: """Explain each sampled feature, then score every explanation on the feature's held-out contexts. Each feature is also scored with another feature's explanation. That control shows what the test gives an explanation that is fluent but wrong. A feature whose calls fail is recorded as unlabeled, so one bad answer never fails the whole task. """ with open(await examples.download()) as f: features = json.load(f) gate = asyncio.Semaphore(concurrency) unlabeled: list[dict] = [] async def explain(feat: dict) -> dict | None: try: async with gate: answer = json.loads(await explain_feature(layer, feat["feature"], autointerp.explain_prompt(feat))) return {**feat, **answer} except Exception as exc: # Unanswered, malformed JSON, or an API error that outlived the retries unlabeled.append({"feature": feat["feature"], "error": f"explain: {exc}"}) return None labeled = [f for f in await asyncio.gather(*[explain(f) for f in features]) if f is not None] shuffled = [labeled[(i + 1) % len(labeled)]["explanation"] for i in range(len(labeled))] async def score(feat: dict, explanation: str) -> float | None: test = autointerp.detect_set(feat, seed=feat["feature"]) try: async with gate: answer = await detect_feature(layer, feat["feature"], autointerp.detect_prompt(explanation, test)) return autointerp.detection_score(answer, test) except Exception as exc: unlabeled.append({"feature": feat["feature"], "error": f"detect: {exc}"}) return None real = await asyncio.gather(*[score(f, f["explanation"]) for f in labeled]) control = await asyncio.gather(*[score(f, e) for f, e in zip(labeled, shuffled)]) scored = [] for feat, s, c in zip(labeled, real, control): if s is None or c is None: continue feat.update(score=s, control=c) scored.append(feat) print(f" #{feat['feature']}: {s:.2f} (control {c:.2f}) {feat['explanation']}") if scored: print(f"layer {layer}: mean detection {sum(f['score'] for f in scored) / len(scored):.2f}, " f"mismatched control {sum(f['control'] for f in scored) / len(scored):.2f}") unlabeled = list({u["feature"]: u for u in unlabeled}.values()) # one entry per feature for u in unlabeled: print(f" #{u['feature']} unlabeled: {u['error']}") return json.dumps({"layer": layer, "width": width, "k": k, "features": scored, "unlabeled": unlabeled}) # {{/docs-fragment label}} # {{docs-fragment publish}} async def publish(best: Trained, stats: SAEStats, labeled: dict, run_name: str) -> File: card = await artifacts.Card.create_from.aio(content=reports.card(best, stats, labeled, run_name), format="html", card_type="model") scores = [f["score"] for f in labeled["features"]] metadata = artifacts.Metadata.create_model_metadata( name="pythia-70m-topk-sae", description=(f"TopK SAE on Pythia-70m-deduped layer {stats.layer}: {stats.width} features, k={stats.k}, " f"{stats.fve:.0%} variance explained, {stats.loss_recovered:.0%} loss recovered"), framework="PyTorch", model_type="TopK sparse autoencoder", architecture=f"d_model 512 -> {stats.width} -> 512, TopK k={stats.k}", task="interpretability", modality=("text",), serial_format="pt", card=card, attrs={"layer": str(stats.layer), "width": str(stats.width), "k": str(stats.k), "fve": f"{stats.fve:.4f}", "loss_recovered": f"{stats.loss_recovered:.4f}", "dead_frac": f"{stats.dead_frac:.4f}", "detection": f"{sum(scores) / len(scores):.3f}"}, ) return artifacts.new(best.weights[best.ks.index(stats.k)], metadata) # {{/docs-fragment publish}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def find_features( layers: list[int] = [1, 3, 5], widths: list[int] = [4096, 16384], ks: list[int] = [16, 32, 64], n_tokens: int = 8_000_000, steps: int = 8000, label_k: int = 32, label_width: int = 16384, features_per_sae: int = 40, ) -> File: """Harvest activations, train an SAE grid in parallel, label features with Claude, and publish the best SAE.""" if label_width not in widths: label_width = max(widths) started = time.time() await flyte.report.replace.aio(reports.page_start(layers, widths, ks, n_tokens), do_flush=True) harvest = await harvest_activations(layers=layers, n_tokens=n_tokens) trained: list[Trained] = await asyncio.gather(*[ train_sae(harvest, layer, width, ks, steps=steps, label_k=label_k, n_features=features_per_sae if width == label_width else 0) for layer in layers for width in widths ]) await flyte.report.replace.aio(reports.overview(trained, [], harvest, time.time() - started), do_flush=True) labeled = [json.loads(s) for s in await asyncio.gather(*[ label_features(t.layer, t.width, t.label_k, t.examples) for t in trained if t.examples is not None ])] await flyte.report.replace.aio(reports.overview(trained, labeled, harvest, time.time() - started)) flyte.report.get_tab("Feature browser").replace(reports.browser(labeled)) await flyte.report.flush.aio() # The SAE whose features Claude explained best, by mean detection score. mean = lambda lab: sum(f["score"] for f in lab["features"]) / len(lab["features"]) best_labels = max((lab for lab in labeled if lab["features"]), key=mean) best = next(t for t in trained if (t.layer, t.width) == (best_labels["layer"], best_labels["width"])) stats = next(s for s in best.stats if s.k == best_labels["k"]) return await publish(best, stats, best_labels, flyte.ctx().action.run_name) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--smoke", action="store_true", help="1 layer, 1 width, 0.5M tokens, 8 features") parser.add_argument("--widths", type=int, nargs="+", default=[4096, 16384]) args = parser.parse_args() flyte.init_from_config() if args.smoke: run = flyte.run(find_features, layers=[3], widths=[4096], n_tokens=500_000, steps=600, features_per_sae=8) else: run = flyte.run(find_features, widths=args.widths) print(run.url) # {{/docs-fragment run}} CODE2 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "find_features" # params = "layers=[3] widths=[4096] n_tokens=500000 steps=600 features_per_sae=8" # /// """Find interpretable features in a language model with sparse autoencoders, and label them with Claude. harvest_activations (GPU, cached) Pythia-70m over FineWeb: residual stream at several layers -> Dir per layer -> N x train_sae (GPU each) one (layer, width) per task: TopK SAEs at k = 16, 32, 64, then variance explained, L0, dead features, and loss with the SAE spliced in -> M x label_features (CPU) Claude explains sampled features and is scored on held-out contexts -> report (feature browser) -> publish the most interpretable SAE as an artifact The harvest is cached on its inputs. Re-running with another width, k, or step budget reuses the activations, and every (layer, width) that was already trained, and only trains what is new. python find_features.py # 3 layers x 2 widths, 8M tokens, about 30 minutes python find_features.py --smoke # 1 layer x 1 width, 0.5M tokens python find_features.py --widths 4096 16384 32768 # reuses the harvest and the first two widths """ import argparse import asyncio import json import os import tempfile import time from dataclasses import dataclass, field from pathlib import Path import autointerp import flyte import flyte.artifacts as artifacts import flyte.report import reports from flyte.io import Dir, File MODEL = "EleutherAI/pythia-70m-deduped" CLAUDE = "claude-opus-5-5" # The name of the secret that holds your Anthropic API key. Set ANTHROPIC_SECRET when you # launch to use a secret with another name. ANTHROPIC_SECRET = os.getenv("ANTHROPIC_SECRET", "anthropic-api-key") # Bump when sae.py changes (the SAE, its training, its metrics, or feature sampling). train_sae # salts its cache with this; cache="auto" alone hashes only the task's own body. SAE_VERSION = "topk-auxk/2" # Set SAE_DEVICE=cpu to run a tiny version on a laptop with flyte's local mode. DEVICE = os.getenv("SAE_DEVICE", "cuda") # {{docs-fragment envs}} image = flyte.Image.from_debian_base(name="sae-features").with_pip_packages( "torch==2.9.1", "transformers==4.57.3", "datasets==4.4.2", "numpy<3", "anthropic==2.6.0", ) # One GPU per task: the harvest, and every SAE trainer. sae.py is imported inside the tasks. gpu_env = flyte.TaskEnvironment( name="sae-gpu", image=image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L4:1", disk="80Gi"), cache="auto", include=["sae.py"], ) # Autointerp is API calls, so CPU only. Only this environment holds the API key. interp_env = flyte.TaskEnvironment( name="sae-autointerp", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), secrets=[flyte.Secret(key=ANTHROPIC_SECRET, as_env_var="ANTHROPIC_API_KEY")], cache="auto", ) driver_env = flyte.TaskEnvironment( name="sae-driver", image=image, resources=flyte.Resources(cpu=2, memory="8Gi"), # The driver declares label_features when it calls it, so it needs the same secret name. env_vars={"ANTHROPIC_SECRET": ANTHROPIC_SECRET}, depends_on=[gpu_env, interp_env], ) # {{/docs-fragment envs}} @dataclass class Harvest: model: str dataset: str layers: list[int] ctx_len: int d_model: int n_seqs: int acts: list[Dir] # one per layer: shard_*.npy, float16 [sequences, ctx_len, d_model] tokens: File # int32 [sequences, ctx_len] @dataclass class SAEStats: layer: int width: int k: int fve: float l0: float dead_frac: float ce_clean: float ce_sae: float ce_zero: float loss_recovered: float density_hist: dict = field(default_factory=dict) @dataclass class Trained: layer: int width: int ks: list[int] stats: list[SAEStats] weights: list[File] # one per k curve: list[dict] train_s: float examples: File | None = None # sampled features with their contexts, for the k that gets labeled label_k: int = 0 # {{docs-fragment harvest}} @gpu_env.task async def harvest_activations( layers: list[int], n_tokens: int = 8_000_000, ctx_len: int = 128, dataset: str = "HuggingFaceFW/fineweb:sample-10BT", shard_seqs: int = 4096, ) -> Harvest: """Run Pythia over FineWeb and save the residual stream after each layer in ``layers``. Each context is the first ``ctx_len`` tokens of one document. Activations are float16 shards, one directory per layer, so a trainer downloads only the layer it needs. """ import numpy as np import torch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL).to(DEVICE).eval() name, _, config = dataset.partition(":") stream = load_dataset(name, name=config or None, split="train", streaming=True) n_seqs = n_tokens // ctx_len rows: list[list[int]] = [] texts: list[str] = [] for doc in stream: texts.append(doc["text"]) if len(texts) == 1000: enc = tok(texts, truncation=True, max_length=ctx_len)["input_ids"] rows += [ids for ids in enc if len(ids) == ctx_len] texts = [] if len(rows) >= n_seqs: break tokens = np.array(rows[:n_seqs], dtype=np.int32) print(f"{len(tokens):,} contexts of {ctx_len} tokens from {dataset}") captured: dict[int, torch.Tensor] = {} for layer in layers: model.gpt_neox.layers[layer].register_forward_hook( lambda _m, _i, out, layer=layer: captured.__setitem__(layer, out[0] if isinstance(out, tuple) else out)) root = Path(tempfile.mkdtemp()) for layer in layers: (root / f"layer_{layer}").mkdir() d_model = model.config.hidden_size with torch.no_grad(): for shard, s in enumerate(range(0, len(tokens), shard_seqs)): chunk = tokens[s:s + shard_seqs] out = {layer: np.empty((len(chunk), ctx_len, d_model), dtype=np.float16) for layer in layers} for b in range(0, len(chunk), 256): model(input_ids=torch.as_tensor(chunk[b:b + 256], dtype=torch.long, device=DEVICE)) for layer in layers: out[layer][b:b + 256] = captured[layer].clamp(-6e4, 6e4).half().cpu().numpy() for layer in layers: np.save(root / f"layer_{layer}" / f"shard_{shard:03d}.npy", out[layer]) np.save(root / "tokens.npy", tokens) print(f"saved {len(layers)} layers x {len(tokens) * ctx_len:,} tokens") acts = await asyncio.gather(*[Dir.from_local(str(root / f"layer_{layer}")) for layer in layers]) return Harvest(model=MODEL, dataset=dataset, layers=layers, ctx_len=ctx_len, d_model=d_model, n_seqs=len(tokens), acts=list(acts), tokens=await File.from_local(str(root / "tokens.npy"))) # {{/docs-fragment harvest}} async def load_layer(harvest: Harvest, layer: int): """Download one layer's shards and put them on the GPU, with the token ids.""" import numpy as np import torch local = Path(await harvest.acts[harvest.layers.index(layer)].download()) shards = sorted(local.rglob("shard_*.npy")) acts = torch.cat([torch.from_numpy(np.load(p)).to(DEVICE) for p in shards]) tokens = np.load(await harvest.tokens.download()) return acts, tokens # {{docs-fragment train}} @gpu_env.task(report=True, cache=flyte.Cache("auto", salt=SAE_VERSION)) async def train_sae( harvest: Harvest, layer: int, width: int, ks: list[int], steps: int = 8000, batch_size: int = 4096, label_k: int = 32, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, held_out: float = 0.05, seed: int = 0, ) -> Trained: """Train one TopK SAE per k on one layer, evaluate each on held-out text, and sample features to label.""" import sae as S import torch from transformers import AutoModelForCausalLM, AutoTokenizer torch.backends.cuda.matmul.allow_tf32 = True acts, tokens = await load_layer(harvest, layer) n_train = int(len(acts) * (1 - held_out)) print(f"layer {layer}: {n_train:,} training and {len(acts) - n_train:,} held-out contexts, width {width}, k {ks}") started = time.time() curve_so_far: list[dict] = [] def on_log(point: dict) -> None: # stream the training curves into this task's report curve_so_far.append(point) flyte.report.replace(reports.training(layer, width, ks, steps, curve_so_far, time.time() - started)) flyte.report.flush() # Training runs in a worker thread, so the report can stream from the callback. saes, scale, curve = await asyncio.to_thread(S.train, acts[:n_train], width, ks, steps, batch_size, seed=seed, on_log=on_log) train_s = time.time() - started print(f"trained {len(ks)} SAEs for {steps} steps in {train_s / 60:.1f} min") # Evaluate on held-out contexts: reconstruction, sparsity, and what the model loses with the SAE in place. model = AutoModelForCausalLM.from_pretrained(harvest.model).to(DEVICE).eval() eval_tokens = torch.as_tensor(tokens[n_train:][:512], dtype=torch.long, device=DEVICE) ce = S.spliced_losses(model, eval_tokens, layer, saes, scale) stats = [] for sae in saes: m = S.reconstruction_metrics(sae, acts[n_train:], scale) st = SAEStats(layer=layer, width=width, k=sae.k, fve=m["fve"], l0=m["l0"], dead_frac=m["dead_frac"], ce_clean=ce["clean"], ce_sae=ce[f"k{sae.k}"], ce_zero=ce["zero"], loss_recovered=S.loss_recovered(ce["clean"], ce[f"k{sae.k}"], ce["zero"]), density_hist=S.density_histogram(m["density"])) print(f" k={sae.k}: FVE {st.fve:.3f}, L0 {st.l0:.1f}, dead {st.dead_frac:.1%}, " f"loss {st.ce_clean:.3f} -> {st.ce_sae:.3f} (zero {st.ce_zero:.3f}), recovered {st.loss_recovered:.1%}") stats.append(st) out = Path(tempfile.mkdtemp()) weights = [] for sae in saes: path = out / f"sae_L{layer}_w{width}_k{sae.k}.pt" torch.save({"state_dict": sae.state_dict(), "scale": scale, "layer": layer, "width": width, "k": sae.k, "d_model": sae.d_model, "model": harvest.model, "hook": f"gpt_neox.layers.{layer} output"}, path) weights.append(await File.from_local(str(path))) examples = None if n_features and label_k in ks: tok = AutoTokenizer.from_pretrained(harvest.model) feats = S.feature_examples(saes[ks.index(label_k)], acts, tokens, scale, lambda t: tok.decode([t]), n_features=n_features, n_top=n_top, n_sampled=n_sampled, seed=seed + layer) path = out / "examples.json" path.write_text(json.dumps(feats)) examples = await File.from_local(str(path)) print(f" sampled {len(feats)} features for autointerp") return Trained(layer=layer, width=width, ks=ks, stats=stats, weights=weights, curve=curve, train_s=round(train_s, 1), examples=examples, label_k=label_k if examples else 0) # {{/docs-fragment train}} # {{docs-fragment claude}} class Unanswered(Exception): """Claude gave no complete JSON answer: a refusal, or output cut off at max_tokens.""" async def ask_claude(system: str, prompt: str, schema: dict, max_tokens: int = 4096) -> str: import anthropic client = anthropic.AsyncAnthropic(max_retries=8) message = await client.messages.create( model=CLAUDE, max_tokens=max_tokens, system=system, output_config={"effort": "low", "format": {"type": "json_schema", "schema": schema}}, messages=[{"role": "user", "content": prompt}], ) # Any thinking counts toward max_tokens, so check that the answer finished before reading it. if message.stop_reason != "end_turn": raise Unanswered(f"stop_reason={message.stop_reason}") text = next((b.text for b in message.content if b.type == "text"), None) if text is None: raise Unanswered("no text block") return text @flyte.trace async def explain_feature(layer: int, feature: int, prompt: str) -> str: """Claude's explanation of one feature. Traced, so a retried task replays it instead of paying again.""" return await ask_claude(autointerp.EXPLAIN_SYSTEM, prompt, autointerp.EXPLAIN_SCHEMA) @flyte.trace async def detect_feature(layer: int, feature: int, prompt: str) -> str: """Claude's guess of which held-out excerpts the explanation predicts. Traced, like the explanation.""" return await ask_claude(autointerp.DETECT_SYSTEM, prompt, autointerp.DETECT_SCHEMA) # {{/docs-fragment claude}} # {{docs-fragment label}} @interp_env.task(retries=1, cache=flyte.Cache("auto", salt=autointerp.VERSION)) async def label_features(layer: int, width: int, k: int, examples: File, concurrency: int = 8) -> str: """Explain each sampled feature, then score every explanation on the feature's held-out contexts. Each feature is also scored with another feature's explanation. That control shows what the test gives an explanation that is fluent but wrong. A feature whose calls fail is recorded as unlabeled, so one bad answer never fails the whole task. """ with open(await examples.download()) as f: features = json.load(f) gate = asyncio.Semaphore(concurrency) unlabeled: list[dict] = [] async def explain(feat: dict) -> dict | None: try: async with gate: answer = json.loads(await explain_feature(layer, feat["feature"], autointerp.explain_prompt(feat))) return {**feat, **answer} except Exception as exc: # Unanswered, malformed JSON, or an API error that outlived the retries unlabeled.append({"feature": feat["feature"], "error": f"explain: {exc}"}) return None labeled = [f for f in await asyncio.gather(*[explain(f) for f in features]) if f is not None] shuffled = [labeled[(i + 1) % len(labeled)]["explanation"] for i in range(len(labeled))] async def score(feat: dict, explanation: str) -> float | None: test = autointerp.detect_set(feat, seed=feat["feature"]) try: async with gate: answer = await detect_feature(layer, feat["feature"], autointerp.detect_prompt(explanation, test)) return autointerp.detection_score(answer, test) except Exception as exc: unlabeled.append({"feature": feat["feature"], "error": f"detect: {exc}"}) return None real = await asyncio.gather(*[score(f, f["explanation"]) for f in labeled]) control = await asyncio.gather(*[score(f, e) for f, e in zip(labeled, shuffled)]) scored = [] for feat, s, c in zip(labeled, real, control): if s is None or c is None: continue feat.update(score=s, control=c) scored.append(feat) print(f" #{feat['feature']}: {s:.2f} (control {c:.2f}) {feat['explanation']}") if scored: print(f"layer {layer}: mean detection {sum(f['score'] for f in scored) / len(scored):.2f}, " f"mismatched control {sum(f['control'] for f in scored) / len(scored):.2f}") unlabeled = list({u["feature"]: u for u in unlabeled}.values()) # one entry per feature for u in unlabeled: print(f" #{u['feature']} unlabeled: {u['error']}") return json.dumps({"layer": layer, "width": width, "k": k, "features": scored, "unlabeled": unlabeled}) # {{/docs-fragment label}} # {{docs-fragment publish}} async def publish(best: Trained, stats: SAEStats, labeled: dict, run_name: str) -> File: card = await artifacts.Card.create_from.aio(content=reports.card(best, stats, labeled, run_name), format="html", card_type="model") scores = [f["score"] for f in labeled["features"]] metadata = artifacts.Metadata.create_model_metadata( name="pythia-70m-topk-sae", description=(f"TopK SAE on Pythia-70m-deduped layer {stats.layer}: {stats.width} features, k={stats.k}, " f"{stats.fve:.0%} variance explained, {stats.loss_recovered:.0%} loss recovered"), framework="PyTorch", model_type="TopK sparse autoencoder", architecture=f"d_model 512 -> {stats.width} -> 512, TopK k={stats.k}", task="interpretability", modality=("text",), serial_format="pt", card=card, attrs={"layer": str(stats.layer), "width": str(stats.width), "k": str(stats.k), "fve": f"{stats.fve:.4f}", "loss_recovered": f"{stats.loss_recovered:.4f}", "dead_frac": f"{stats.dead_frac:.4f}", "detection": f"{sum(scores) / len(scores):.3f}"}, ) return artifacts.new(best.weights[best.ks.index(stats.k)], metadata) # {{/docs-fragment publish}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def find_features( layers: list[int] = [1, 3, 5], widths: list[int] = [4096, 16384], ks: list[int] = [16, 32, 64], n_tokens: int = 8_000_000, steps: int = 8000, label_k: int = 32, label_width: int = 16384, features_per_sae: int = 40, ) -> File: """Harvest activations, train an SAE grid in parallel, label features with Claude, and publish the best SAE.""" if label_width not in widths: label_width = max(widths) started = time.time() await flyte.report.replace.aio(reports.page_start(layers, widths, ks, n_tokens), do_flush=True) harvest = await harvest_activations(layers=layers, n_tokens=n_tokens) trained: list[Trained] = await asyncio.gather(*[ train_sae(harvest, layer, width, ks, steps=steps, label_k=label_k, n_features=features_per_sae if width == label_width else 0) for layer in layers for width in widths ]) await flyte.report.replace.aio(reports.overview(trained, [], harvest, time.time() - started), do_flush=True) labeled = [json.loads(s) for s in await asyncio.gather(*[ label_features(t.layer, t.width, t.label_k, t.examples) for t in trained if t.examples is not None ])] await flyte.report.replace.aio(reports.overview(trained, labeled, harvest, time.time() - started)) flyte.report.get_tab("Feature browser").replace(reports.browser(labeled)) await flyte.report.flush.aio() # The SAE whose features Claude explained best, by mean detection score. mean = lambda lab: sum(f["score"] for f in lab["features"]) / len(lab["features"]) best_labels = max((lab for lab in labeled if lab["features"]), key=mean) best = next(t for t in trained if (t.layer, t.width) == (best_labels["layer"], best_labels["width"])) stats = next(s for s in best.stats if s.k == best_labels["k"]) return await publish(best, stats, best_labels, flyte.ctx().action.run_name) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--smoke", action="store_true", help="1 layer, 1 width, 0.5M tokens, 8 features") parser.add_argument("--widths", type=int, nargs="+", default=[4096, 16384]) args = parser.parse_args() flyte.init_from_config() if args.smoke: run = flyte.run(find_features, layers=[3], widths=[4096], n_tokens=500_000, steps=600, features_per_sae=8) else: run = flyte.run(find_features, widths=args.widths) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/sparse_autoencoders/find_features.py* The environment sets `cache="auto"`, so the harvest's output is stored under a key made from its inputs and the task function's own code. Any later run with the same layers, token count, and dataset gets the same `Dir`s back without starting a GPU. `cache="auto"` hashes only the body of the task function, not the modules it calls. `train_sae` does its work in `sae.py`, and `label_features` in `autointerp.py`, so each of those tasks salts its cache with a version string: `flyte.Cache("auto", salt=SAE_VERSION)` and `flyte.Cache("auto", salt=autointerp.VERSION)`. Bump the version when you change the module, or a re-run returns results computed with the old code. ## The TopK sparse autoencoder The SAE encodes an activation into a code as wide as the number of features, keeps the k largest entries, and decodes back with one unit-norm direction per feature. Choosing k sets the sparsity directly, where older SAEs tuned an L1 penalty to reach it. ``` """TopK sparse autoencoders in plain PyTorch: the model, its training loop, and its metrics. This file never imports Flyte. The pipeline imports it inside its GPU tasks. A sparse autoencoder (SAE) rewrites one activation vector of a language model as a sparse sum of learned directions, its features. A TopK SAE (Gao et al., 2024) keeps exactly the k largest encoder pre-activations per token and zeroes the rest, so the sparsity is set directly instead of being tuned through an L1 penalty: z = ReLU(TopK((x - b_dec) @ W_enc + b_enc)) x_hat = z @ W_dec + b_dec """ import math import numpy as np import torch import torch.nn.functional as F from torch import nn # {{docs-fragment model}} class TopKSAE(nn.Module): def __init__(self, d_model: int, width: int, k: int): super().__init__() self.d_model, self.width, self.k = d_model, width, k w_dec = torch.randn(width, d_model) w_dec /= w_dec.norm(dim=1, keepdim=True) self.W_dec = nn.Parameter(w_dec) # one unit-norm direction per feature self.W_enc = nn.Parameter(w_dec.T.clone()) # tied at init, trained separately self.b_enc = nn.Parameter(torch.zeros(width)) self.b_dec = nn.Parameter(torch.zeros(d_model)) def pre_acts(self, x: torch.Tensor) -> torch.Tensor: return (x - self.b_dec) @ self.W_enc + self.b_enc def encode(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """The k active features per token: their indices, their values, and every pre-activation.""" pre = self.pre_acts(x) vals, idx = pre.topk(self.k, dim=-1) return idx, F.relu(vals), pre def decode(self, idx: torch.Tensor, vals: torch.Tensor) -> torch.Tensor: # A sum of k decoder rows per token, without materializing the width-sized code. return F.embedding_bag(idx, self.W_dec, per_sample_weights=vals, mode="sum") + self.b_dec def forward(self, x: torch.Tensor) -> torch.Tensor: idx, vals, _ = self.encode(x) return self.decode(idx, vals) @torch.no_grad() def normalize_decoder(self) -> None: self.W_dec.data /= self.W_dec.data.norm(dim=1, keepdim=True).clamp_min(1e-8) # {{/docs-fragment model}} def aux_loss(sae: TopKSAE, pre: torch.Tensor, err: torch.Tensor, dead: torch.Tensor) -> torch.Tensor: """AuxK: the dead features' top pre-activations must explain what the live ones missed. This gives dead features a gradient, so fewer of them stay dead (Gao et al., section 2.4). """ n_dead = int(dead.sum()) if n_dead == 0: return pre.new_zeros(()) k_aux = min(sae.d_model // 2, n_dead) vals, idx = pre.masked_fill(~dead, -torch.inf).topk(k_aux, dim=-1) err_hat = F.embedding_bag(idx, sae.W_dec, per_sample_weights=F.relu(vals), mode="sum") return (err - err_hat).pow(2).sum(-1).mean() / err.pow(2).sum(-1).mean().clamp_min(1e-8) # {{docs-fragment train}} def train( acts: torch.Tensor, # [sequences, positions, d_model] float16, on the GPU width: int, ks: list[int], steps: int, batch_size: int = 4096, lr: float | None = None, seed: int = 0, log_every: int = 250, on_log=None, ) -> tuple[list[TopKSAE], float, list[dict]]: """Train one TopK SAE per k on the same batches. Position 0 is skipped (see ``token_index``).""" torch.manual_seed(seed) device = acts.device n_seq, ctx, d = acts.shape scale = activation_scale(acts) # Gao et al. scale the learning rate as 1/sqrt(width). lr = lr or 2e-4 * math.sqrt(16384 / width) saes = [TopKSAE(d, width, k).to(device) for k in ks] sample = gather(acts, token_index(n_seq, ctx, 32_768, device), scale) for sae in saes: sae.b_dec.data = sample.median(dim=0).values # a robust center for the decoder bias opts = [torch.optim.Adam(s.parameters(), lr=lr, betas=(0.9, 0.999)) for s in saes] decay_from = int(steps * 0.8) sched = lambda step: min(1.0, (step + 1) / 100) * min(1.0, (steps - step) / max(steps - decay_from, 1)) last_fired = [torch.zeros(width, dtype=torch.long, device=device) for _ in saes] dead_after = max(1, 1_000_000 // batch_size) # a feature is dead after 1M tokens without firing curve: list[dict] = [] for step in range(steps): x = gather(acts, token_index(n_seq, ctx, batch_size, device), scale) point = {"step": step + 1} for i, (sae, opt) in enumerate(zip(saes, opts)): for g in opt.param_groups: g["lr"] = lr * sched(step) idx, vals, pre = sae.encode(x) x_hat = sae.decode(idx, vals) err = x - x_hat nmse = err.pow(2).sum(-1).mean() / (x - x.mean(0)).pow(2).sum(-1).mean() dead = (step - last_fired[i]) > dead_after loss = nmse + aux_loss(sae, pre, err.detach(), dead) / 32 opt.zero_grad(set_to_none=True) loss.backward() opt.step() sae.normalize_decoder() last_fired[i][idx[vals > 0]] = step point[f"k{sae.k}"] = nmse.item() point[f"dead_k{sae.k}"] = float(dead.float().mean()) if step % log_every == 0 or step == steps - 1: curve.append(point) if on_log: on_log(point) return saes, scale, curve # {{/docs-fragment train}} def token_index(n_seq: int, ctx: int, n: int, device) -> tuple[torch.Tensor, torch.Tensor]: """Random (sequence, position) pairs, never position 0. The first token of every context carries a residual norm many times larger than any other (an attention sink), so SAE work on Pythia conventionally leaves it out. """ return (torch.randint(0, n_seq, (n,), device=device), torch.randint(1, ctx, (n,), device=device)) def gather(acts: torch.Tensor, index: tuple[torch.Tensor, torch.Tensor], scale: float) -> torch.Tensor: return acts[index].float() * scale def activation_scale(acts: torch.Tensor) -> float: """A constant that makes the mean squared norm of an activation equal d_model (as in Gemma Scope).""" x = acts[token_index(acts.shape[0], acts.shape[1], 65_536, acts.device)].float() return float(math.sqrt(acts.shape[-1] / x.pow(2).sum(-1).mean())) # {{docs-fragment metrics}} @torch.no_grad() def reconstruction_metrics(sae: TopKSAE, acts: torch.Tensor, scale: float, chunk: int = 128) -> dict: """Fraction of variance explained, L0, dead features, and each feature's firing rate, on held-out tokens.""" x_all = acts[:, 1:] mean = x_all.reshape(-1, x_all.shape[-1]).float().mean(0) * scale sse = sst = l0 = 0.0 fires = torch.zeros(sae.width, device=acts.device) n = 0 for s in range(0, x_all.shape[0], chunk): x = x_all[s:s + chunk].reshape(-1, x_all.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) x_hat = sae.decode(idx, vals) sse += float((x - x_hat).pow(2).sum()) sst += float((x - mean).pow(2).sum()) on = vals > 0 l0 += float(on.sum()) fires.index_add_(0, idx[on], torch.ones(int(on.sum()), device=acts.device)) n += x.shape[0] density = (fires / n).cpu().numpy() return {"fve": 1 - sse / sst, "l0": l0 / n, "dead_frac": float((density == 0).mean()), "density": density, "tokens": n} @torch.no_grad() def spliced_losses(model, tokens: torch.Tensor, layer: int, saes: list[TopKSAE], scale: float, batch: int = 64) -> dict: """Next-token loss with layer ``layer``'s output left alone, replaced by each SAE's reconstruction, or zeroed. Position 0 is never touched, the same as in training. """ block = model.gpt_neox.layers[layer] state: dict = {"replace": None} def hook(_module, _inputs, output): hidden = output[0] if isinstance(output, tuple) else output if state["replace"] is None: return output new = hidden.clone() new[:, 1:] = state["replace"](hidden[:, 1:]) return (new, *output[1:]) if isinstance(output, tuple) else new def through(sae): def f(h): x = h.reshape(-1, h.shape[-1]).float() * scale return (sae(x) / scale).reshape(h.shape).to(h.dtype) return f def loss() -> float: total = 0.0 for s in range(0, tokens.shape[0], batch): t = tokens[s:s + batch] total += float(model(input_ids=t, labels=t).loss) * t.shape[0] return total / tokens.shape[0] handle = block.register_forward_hook(hook) try: out = {"clean": loss()} state["replace"] = torch.zeros_like out["zero"] = loss() for sae in saes: state["replace"] = through(sae) out[f"k{sae.k}"] = loss() finally: handle.remove() return out def loss_recovered(clean: float, spliced: float, zero: float) -> float: """1.0 when the reconstruction is as good as the real activations, 0.0 when it is no better than zeros.""" return (zero - spliced) / (zero - clean) # {{/docs-fragment metrics}} # {{docs-fragment examples}} @torch.no_grad() def feature_examples( sae: TopKSAE, acts: torch.Tensor, tokens: np.ndarray, scale: float, decode_token, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, n_detect: int = 8, before: int = 24, after: int = 8, seed: int = 0, chunk: int = 128, ) -> list[dict]: """For a random sample of live features: contexts to explain it from, a held-out test set, and a histogram. Claude explains a feature from its ``n_top`` strongest contexts plus ``n_sampled`` contexts drawn from the rest of its clear firings. Top contexts alone hide what a feature does at moderate strength, which is most of its firings (Paulo et al., 2024). The test set for each feature mixes ``n_detect`` contexts where it fires clearly (none of them among its top contexts) with ``n_detect`` random contexts where it does not fire at all. Autointerp scores an explanation by how well it predicts which is which. """ rng = np.random.default_rng(seed) n_seq, ctx, _ = acts.shape # Pass 1: how many contexts each feature fires in. seq_hits = torch.zeros(sae.width, device=acts.device) for s in range(0, n_seq, chunk): x = acts[s:s + chunk, 1:].reshape(-1, acts.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) per_seq = torch.zeros(min(chunk, n_seq - s), sae.width, device=acts.device) rows = torch.arange(per_seq.shape[0], device=acts.device).repeat_interleave((ctx - 1) * sae.k) per_seq.index_put_((rows, idx.flatten()), (vals.flatten() > 0).float(), accumulate=True) seq_hits += (per_seq > 0).float().sum(0) # Sample uniformly among features that fire in enough contexts to fill both example sets. enough = (seq_hits >= 2 * (n_top + n_sampled + n_detect)) & (seq_hits <= n_seq - 2 * n_detect) eligible = torch.nonzero(enough).flatten().cpu().numpy() feats = np.sort(rng.choice(eligible, size=min(n_features, len(eligible)), replace=False)) # Pass 2: every activation of the sampled features, at every position. col = torch.full((sae.width,), -1, dtype=torch.long, device=acts.device) col[torch.as_tensor(feats, device=acts.device)] = torch.arange(len(feats), device=acts.device) f_acts = torch.zeros(n_seq, ctx, len(feats), dtype=torch.float16, device=acts.device) for s in range(0, n_seq, chunk): block = acts[s:s + chunk, 1:] x = block.reshape(-1, acts.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) c = col[idx] keep = (c >= 0) & (vals > 0) rows = torch.arange(x.shape[0], device=acts.device).unsqueeze(1).expand_as(idx)[keep] flat = torch.zeros(x.shape[0], len(feats), dtype=torch.float16, device=acts.device) flat[rows, c[keep]] = vals[keep].half() f_acts[s:s + block.shape[0], 1:] = flat.reshape(block.shape[0], ctx - 1, len(feats)) def window(seq: int, center: int, values: np.ndarray) -> dict: # Every excerpt has the same length, shifted inward at the context's edges, so that # length never tells the detection test which excerpts are positives. size = before + after + 1 lo = min(max(1, center - before), ctx - size) hi = lo + size return {"tokens": [decode_token(int(t)) for t in tokens[seq, lo:hi]], "acts": [round(float(v), 3) for v in values[seq, lo:hi]]} out = [] for j, f in enumerate(feats): a = f_acts[:, :, j].float() seq_max, seq_arg = a.max(dim=1) order = torch.argsort(seq_max, descending=True).cpu().numpy() seq_max, seq_arg, a_np = seq_max.cpu().numpy(), seq_arg.cpu().numpy(), a.cpu().numpy() active = order[seq_max[order] > 0] top = active[:n_top] rest = active[n_top:] # Held-out positives: contexts outside the top where the feature still fires clearly, at # least a quarter of its peak. Weaker firings are near the SAE's noise floor. clear = rest[seq_max[rest] >= 0.25 * seq_max[top[0]]] enough_clear = len(clear) >= n_sampled + n_detect pool = clear if enough_clear else rest[:4 * (n_sampled + n_detect)] picked = rng.choice(pool, size=min(n_sampled + n_detect, len(pool)), replace=False) sampled, test_on = np.sort(picked[:n_sampled]), picked[n_sampled:] test_on_set = [{**window(int(sq), int(seq_arg[sq]), a_np), "active": True} for sq in test_on] quiet = np.nonzero(seq_max == 0)[0] test_off = rng.choice(quiet, size=min(n_detect, len(quiet)), replace=False) if len(quiet) else [] test_off_set = [{**window(int(sq), int(rng.integers(before + 1, ctx - after)), a_np), "active": False} for sq in test_off] nz = a_np[a_np > 0] counts, edges = np.histogram(nz, bins=24, range=(0, float(nz.max()))) out.append({ "feature": int(f), "density": float(len(nz) / (n_seq * (ctx - 1))), "context_rate": float(len(active) / n_seq), "max_act": float(nz.max()), "hist": {"counts": counts.tolist(), "edges": [round(float(e), 3) for e in edges]}, "top": [window(int(sq), int(seq_arg[sq]), a_np) for sq in top], "sampled_clear": bool(enough_clear), # False: sampled from its next-strongest contexts instead "sampled": sorted((window(int(sq), int(seq_arg[sq]), a_np) for sq in sampled), key=lambda w: -max(w["acts"])), "test": test_on_set + test_off_set, }) return out # {{/docs-fragment examples}} def density_histogram(density: np.ndarray, lo: float = -6.0, hi: float = 0.0, step: float = 0.5) -> dict: """How many features fire at each log10 rate, with dead features counted separately.""" alive = density[density > 0] edges = np.arange(lo, hi + step, step) counts, _ = np.histogram(np.log10(alive), bins=edges) return {"edges": edges.tolist(), "counts": counts.tolist(), "dead": int((density == 0).sum())} CODE3 """TopK sparse autoencoders in plain PyTorch: the model, its training loop, and its metrics. This file never imports Flyte. The pipeline imports it inside its GPU tasks. A sparse autoencoder (SAE) rewrites one activation vector of a language model as a sparse sum of learned directions, its features. A TopK SAE (Gao et al., 2024) keeps exactly the k largest encoder pre-activations per token and zeroes the rest, so the sparsity is set directly instead of being tuned through an L1 penalty: z = ReLU(TopK((x - b_dec) @ W_enc + b_enc)) x_hat = z @ W_dec + b_dec """ import math import numpy as np import torch import torch.nn.functional as F from torch import nn # {{docs-fragment model}} class TopKSAE(nn.Module): def __init__(self, d_model: int, width: int, k: int): super().__init__() self.d_model, self.width, self.k = d_model, width, k w_dec = torch.randn(width, d_model) w_dec /= w_dec.norm(dim=1, keepdim=True) self.W_dec = nn.Parameter(w_dec) # one unit-norm direction per feature self.W_enc = nn.Parameter(w_dec.T.clone()) # tied at init, trained separately self.b_enc = nn.Parameter(torch.zeros(width)) self.b_dec = nn.Parameter(torch.zeros(d_model)) def pre_acts(self, x: torch.Tensor) -> torch.Tensor: return (x - self.b_dec) @ self.W_enc + self.b_enc def encode(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """The k active features per token: their indices, their values, and every pre-activation.""" pre = self.pre_acts(x) vals, idx = pre.topk(self.k, dim=-1) return idx, F.relu(vals), pre def decode(self, idx: torch.Tensor, vals: torch.Tensor) -> torch.Tensor: # A sum of k decoder rows per token, without materializing the width-sized code. return F.embedding_bag(idx, self.W_dec, per_sample_weights=vals, mode="sum") + self.b_dec def forward(self, x: torch.Tensor) -> torch.Tensor: idx, vals, _ = self.encode(x) return self.decode(idx, vals) @torch.no_grad() def normalize_decoder(self) -> None: self.W_dec.data /= self.W_dec.data.norm(dim=1, keepdim=True).clamp_min(1e-8) # {{/docs-fragment model}} def aux_loss(sae: TopKSAE, pre: torch.Tensor, err: torch.Tensor, dead: torch.Tensor) -> torch.Tensor: """AuxK: the dead features' top pre-activations must explain what the live ones missed. This gives dead features a gradient, so fewer of them stay dead (Gao et al., section 2.4). """ n_dead = int(dead.sum()) if n_dead == 0: return pre.new_zeros(()) k_aux = min(sae.d_model // 2, n_dead) vals, idx = pre.masked_fill(~dead, -torch.inf).topk(k_aux, dim=-1) err_hat = F.embedding_bag(idx, sae.W_dec, per_sample_weights=F.relu(vals), mode="sum") return (err - err_hat).pow(2).sum(-1).mean() / err.pow(2).sum(-1).mean().clamp_min(1e-8) # {{docs-fragment train}} def train( acts: torch.Tensor, # [sequences, positions, d_model] float16, on the GPU width: int, ks: list[int], steps: int, batch_size: int = 4096, lr: float | None = None, seed: int = 0, log_every: int = 250, on_log=None, ) -> tuple[list[TopKSAE], float, list[dict]]: """Train one TopK SAE per k on the same batches. Position 0 is skipped (see ``token_index``).""" torch.manual_seed(seed) device = acts.device n_seq, ctx, d = acts.shape scale = activation_scale(acts) # Gao et al. scale the learning rate as 1/sqrt(width). lr = lr or 2e-4 * math.sqrt(16384 / width) saes = [TopKSAE(d, width, k).to(device) for k in ks] sample = gather(acts, token_index(n_seq, ctx, 32_768, device), scale) for sae in saes: sae.b_dec.data = sample.median(dim=0).values # a robust center for the decoder bias opts = [torch.optim.Adam(s.parameters(), lr=lr, betas=(0.9, 0.999)) for s in saes] decay_from = int(steps * 0.8) sched = lambda step: min(1.0, (step + 1) / 100) * min(1.0, (steps - step) / max(steps - decay_from, 1)) last_fired = [torch.zeros(width, dtype=torch.long, device=device) for _ in saes] dead_after = max(1, 1_000_000 // batch_size) # a feature is dead after 1M tokens without firing curve: list[dict] = [] for step in range(steps): x = gather(acts, token_index(n_seq, ctx, batch_size, device), scale) point = {"step": step + 1} for i, (sae, opt) in enumerate(zip(saes, opts)): for g in opt.param_groups: g["lr"] = lr * sched(step) idx, vals, pre = sae.encode(x) x_hat = sae.decode(idx, vals) err = x - x_hat nmse = err.pow(2).sum(-1).mean() / (x - x.mean(0)).pow(2).sum(-1).mean() dead = (step - last_fired[i]) > dead_after loss = nmse + aux_loss(sae, pre, err.detach(), dead) / 32 opt.zero_grad(set_to_none=True) loss.backward() opt.step() sae.normalize_decoder() last_fired[i][idx[vals > 0]] = step point[f"k{sae.k}"] = nmse.item() point[f"dead_k{sae.k}"] = float(dead.float().mean()) if step % log_every == 0 or step == steps - 1: curve.append(point) if on_log: on_log(point) return saes, scale, curve # {{/docs-fragment train}} def token_index(n_seq: int, ctx: int, n: int, device) -> tuple[torch.Tensor, torch.Tensor]: """Random (sequence, position) pairs, never position 0. The first token of every context carries a residual norm many times larger than any other (an attention sink), so SAE work on Pythia conventionally leaves it out. """ return (torch.randint(0, n_seq, (n,), device=device), torch.randint(1, ctx, (n,), device=device)) def gather(acts: torch.Tensor, index: tuple[torch.Tensor, torch.Tensor], scale: float) -> torch.Tensor: return acts[index].float() * scale def activation_scale(acts: torch.Tensor) -> float: """A constant that makes the mean squared norm of an activation equal d_model (as in Gemma Scope).""" x = acts[token_index(acts.shape[0], acts.shape[1], 65_536, acts.device)].float() return float(math.sqrt(acts.shape[-1] / x.pow(2).sum(-1).mean())) # {{docs-fragment metrics}} @torch.no_grad() def reconstruction_metrics(sae: TopKSAE, acts: torch.Tensor, scale: float, chunk: int = 128) -> dict: """Fraction of variance explained, L0, dead features, and each feature's firing rate, on held-out tokens.""" x_all = acts[:, 1:] mean = x_all.reshape(-1, x_all.shape[-1]).float().mean(0) * scale sse = sst = l0 = 0.0 fires = torch.zeros(sae.width, device=acts.device) n = 0 for s in range(0, x_all.shape[0], chunk): x = x_all[s:s + chunk].reshape(-1, x_all.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) x_hat = sae.decode(idx, vals) sse += float((x - x_hat).pow(2).sum()) sst += float((x - mean).pow(2).sum()) on = vals > 0 l0 += float(on.sum()) fires.index_add_(0, idx[on], torch.ones(int(on.sum()), device=acts.device)) n += x.shape[0] density = (fires / n).cpu().numpy() return {"fve": 1 - sse / sst, "l0": l0 / n, "dead_frac": float((density == 0).mean()), "density": density, "tokens": n} @torch.no_grad() def spliced_losses(model, tokens: torch.Tensor, layer: int, saes: list[TopKSAE], scale: float, batch: int = 64) -> dict: """Next-token loss with layer ``layer``'s output left alone, replaced by each SAE's reconstruction, or zeroed. Position 0 is never touched, the same as in training. """ block = model.gpt_neox.layers[layer] state: dict = {"replace": None} def hook(_module, _inputs, output): hidden = output[0] if isinstance(output, tuple) else output if state["replace"] is None: return output new = hidden.clone() new[:, 1:] = state["replace"](hidden[:, 1:]) return (new, *output[1:]) if isinstance(output, tuple) else new def through(sae): def f(h): x = h.reshape(-1, h.shape[-1]).float() * scale return (sae(x) / scale).reshape(h.shape).to(h.dtype) return f def loss() -> float: total = 0.0 for s in range(0, tokens.shape[0], batch): t = tokens[s:s + batch] total += float(model(input_ids=t, labels=t).loss) * t.shape[0] return total / tokens.shape[0] handle = block.register_forward_hook(hook) try: out = {"clean": loss()} state["replace"] = torch.zeros_like out["zero"] = loss() for sae in saes: state["replace"] = through(sae) out[f"k{sae.k}"] = loss() finally: handle.remove() return out def loss_recovered(clean: float, spliced: float, zero: float) -> float: """1.0 when the reconstruction is as good as the real activations, 0.0 when it is no better than zeros.""" return (zero - spliced) / (zero - clean) # {{/docs-fragment metrics}} # {{docs-fragment examples}} @torch.no_grad() def feature_examples( sae: TopKSAE, acts: torch.Tensor, tokens: np.ndarray, scale: float, decode_token, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, n_detect: int = 8, before: int = 24, after: int = 8, seed: int = 0, chunk: int = 128, ) -> list[dict]: """For a random sample of live features: contexts to explain it from, a held-out test set, and a histogram. Claude explains a feature from its ``n_top`` strongest contexts plus ``n_sampled`` contexts drawn from the rest of its clear firings. Top contexts alone hide what a feature does at moderate strength, which is most of its firings (Paulo et al., 2024). The test set for each feature mixes ``n_detect`` contexts where it fires clearly (none of them among its top contexts) with ``n_detect`` random contexts where it does not fire at all. Autointerp scores an explanation by how well it predicts which is which. """ rng = np.random.default_rng(seed) n_seq, ctx, _ = acts.shape # Pass 1: how many contexts each feature fires in. seq_hits = torch.zeros(sae.width, device=acts.device) for s in range(0, n_seq, chunk): x = acts[s:s + chunk, 1:].reshape(-1, acts.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) per_seq = torch.zeros(min(chunk, n_seq - s), sae.width, device=acts.device) rows = torch.arange(per_seq.shape[0], device=acts.device).repeat_interleave((ctx - 1) * sae.k) per_seq.index_put_((rows, idx.flatten()), (vals.flatten() > 0).float(), accumulate=True) seq_hits += (per_seq > 0).float().sum(0) # Sample uniformly among features that fire in enough contexts to fill both example sets. enough = (seq_hits >= 2 * (n_top + n_sampled + n_detect)) & (seq_hits <= n_seq - 2 * n_detect) eligible = torch.nonzero(enough).flatten().cpu().numpy() feats = np.sort(rng.choice(eligible, size=min(n_features, len(eligible)), replace=False)) # Pass 2: every activation of the sampled features, at every position. col = torch.full((sae.width,), -1, dtype=torch.long, device=acts.device) col[torch.as_tensor(feats, device=acts.device)] = torch.arange(len(feats), device=acts.device) f_acts = torch.zeros(n_seq, ctx, len(feats), dtype=torch.float16, device=acts.device) for s in range(0, n_seq, chunk): block = acts[s:s + chunk, 1:] x = block.reshape(-1, acts.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) c = col[idx] keep = (c >= 0) & (vals > 0) rows = torch.arange(x.shape[0], device=acts.device).unsqueeze(1).expand_as(idx)[keep] flat = torch.zeros(x.shape[0], len(feats), dtype=torch.float16, device=acts.device) flat[rows, c[keep]] = vals[keep].half() f_acts[s:s + block.shape[0], 1:] = flat.reshape(block.shape[0], ctx - 1, len(feats)) def window(seq: int, center: int, values: np.ndarray) -> dict: # Every excerpt has the same length, shifted inward at the context's edges, so that # length never tells the detection test which excerpts are positives. size = before + after + 1 lo = min(max(1, center - before), ctx - size) hi = lo + size return {"tokens": [decode_token(int(t)) for t in tokens[seq, lo:hi]], "acts": [round(float(v), 3) for v in values[seq, lo:hi]]} out = [] for j, f in enumerate(feats): a = f_acts[:, :, j].float() seq_max, seq_arg = a.max(dim=1) order = torch.argsort(seq_max, descending=True).cpu().numpy() seq_max, seq_arg, a_np = seq_max.cpu().numpy(), seq_arg.cpu().numpy(), a.cpu().numpy() active = order[seq_max[order] > 0] top = active[:n_top] rest = active[n_top:] # Held-out positives: contexts outside the top where the feature still fires clearly, at # least a quarter of its peak. Weaker firings are near the SAE's noise floor. clear = rest[seq_max[rest] >= 0.25 * seq_max[top[0]]] enough_clear = len(clear) >= n_sampled + n_detect pool = clear if enough_clear else rest[:4 * (n_sampled + n_detect)] picked = rng.choice(pool, size=min(n_sampled + n_detect, len(pool)), replace=False) sampled, test_on = np.sort(picked[:n_sampled]), picked[n_sampled:] test_on_set = [{**window(int(sq), int(seq_arg[sq]), a_np), "active": True} for sq in test_on] quiet = np.nonzero(seq_max == 0)[0] test_off = rng.choice(quiet, size=min(n_detect, len(quiet)), replace=False) if len(quiet) else [] test_off_set = [{**window(int(sq), int(rng.integers(before + 1, ctx - after)), a_np), "active": False} for sq in test_off] nz = a_np[a_np > 0] counts, edges = np.histogram(nz, bins=24, range=(0, float(nz.max()))) out.append({ "feature": int(f), "density": float(len(nz) / (n_seq * (ctx - 1))), "context_rate": float(len(active) / n_seq), "max_act": float(nz.max()), "hist": {"counts": counts.tolist(), "edges": [round(float(e), 3) for e in edges]}, "top": [window(int(sq), int(seq_arg[sq]), a_np) for sq in top], "sampled_clear": bool(enough_clear), # False: sampled from its next-strongest contexts instead "sampled": sorted((window(int(sq), int(seq_arg[sq]), a_np) for sq in sampled), key=lambda w: -max(w["acts"])), "test": test_on_set + test_off_set, }) return out # {{/docs-fragment examples}} def density_histogram(density: np.ndarray, lo: float = -6.0, hi: float = 0.0, step: float = 0.5) -> dict: """How many features fire at each log10 rate, with dead features counted separately.""" alive = density[density > 0] edges = np.arange(lo, hi + step, step) counts, _ = np.histogram(np.log10(alive), bins=edges) return {"edges": edges.tolist(), "counts": counts.tolist(), "dead": int((density == 0).sum())} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/sparse_autoencoders/sae.py* ## Train and evaluate the grid `train_sae` is one GPU task per (layer, width). It loads its layer onto the GPU, trains, and streams the training curves into its own report. Then it evaluates every SAE on held-out contexts and, for the width that gets labeled, samples features for Claude. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "find_features" # params = "layers=[3] widths=[4096] n_tokens=500000 steps=600 features_per_sae=8" # /// """Find interpretable features in a language model with sparse autoencoders, and label them with Claude. harvest_activations (GPU, cached) Pythia-70m over FineWeb: residual stream at several layers -> Dir per layer -> N x train_sae (GPU each) one (layer, width) per task: TopK SAEs at k = 16, 32, 64, then variance explained, L0, dead features, and loss with the SAE spliced in -> M x label_features (CPU) Claude explains sampled features and is scored on held-out contexts -> report (feature browser) -> publish the most interpretable SAE as an artifact The harvest is cached on its inputs. Re-running with another width, k, or step budget reuses the activations, and every (layer, width) that was already trained, and only trains what is new. python find_features.py # 3 layers x 2 widths, 8M tokens, about 30 minutes python find_features.py --smoke # 1 layer x 1 width, 0.5M tokens python find_features.py --widths 4096 16384 32768 # reuses the harvest and the first two widths """ import argparse import asyncio import json import os import tempfile import time from dataclasses import dataclass, field from pathlib import Path import autointerp import flyte import flyte.artifacts as artifacts import flyte.report import reports from flyte.io import Dir, File MODEL = "EleutherAI/pythia-70m-deduped" CLAUDE = "claude-opus-5-5" # The name of the secret that holds your Anthropic API key. Set ANTHROPIC_SECRET when you # launch to use a secret with another name. ANTHROPIC_SECRET = os.getenv("ANTHROPIC_SECRET", "anthropic-api-key") # Bump when sae.py changes (the SAE, its training, its metrics, or feature sampling). train_sae # salts its cache with this; cache="auto" alone hashes only the task's own body. SAE_VERSION = "topk-auxk/2" # Set SAE_DEVICE=cpu to run a tiny version on a laptop with flyte's local mode. DEVICE = os.getenv("SAE_DEVICE", "cuda") # {{docs-fragment envs}} image = flyte.Image.from_debian_base(name="sae-features").with_pip_packages( "torch==2.9.1", "transformers==4.57.3", "datasets==4.4.2", "numpy<3", "anthropic==2.6.0", ) # One GPU per task: the harvest, and every SAE trainer. sae.py is imported inside the tasks. gpu_env = flyte.TaskEnvironment( name="sae-gpu", image=image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L4:1", disk="80Gi"), cache="auto", include=["sae.py"], ) # Autointerp is API calls, so CPU only. Only this environment holds the API key. interp_env = flyte.TaskEnvironment( name="sae-autointerp", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), secrets=[flyte.Secret(key=ANTHROPIC_SECRET, as_env_var="ANTHROPIC_API_KEY")], cache="auto", ) driver_env = flyte.TaskEnvironment( name="sae-driver", image=image, resources=flyte.Resources(cpu=2, memory="8Gi"), # The driver declares label_features when it calls it, so it needs the same secret name. env_vars={"ANTHROPIC_SECRET": ANTHROPIC_SECRET}, depends_on=[gpu_env, interp_env], ) # {{/docs-fragment envs}} @dataclass class Harvest: model: str dataset: str layers: list[int] ctx_len: int d_model: int n_seqs: int acts: list[Dir] # one per layer: shard_*.npy, float16 [sequences, ctx_len, d_model] tokens: File # int32 [sequences, ctx_len] @dataclass class SAEStats: layer: int width: int k: int fve: float l0: float dead_frac: float ce_clean: float ce_sae: float ce_zero: float loss_recovered: float density_hist: dict = field(default_factory=dict) @dataclass class Trained: layer: int width: int ks: list[int] stats: list[SAEStats] weights: list[File] # one per k curve: list[dict] train_s: float examples: File | None = None # sampled features with their contexts, for the k that gets labeled label_k: int = 0 # {{docs-fragment harvest}} @gpu_env.task async def harvest_activations( layers: list[int], n_tokens: int = 8_000_000, ctx_len: int = 128, dataset: str = "HuggingFaceFW/fineweb:sample-10BT", shard_seqs: int = 4096, ) -> Harvest: """Run Pythia over FineWeb and save the residual stream after each layer in ``layers``. Each context is the first ``ctx_len`` tokens of one document. Activations are float16 shards, one directory per layer, so a trainer downloads only the layer it needs. """ import numpy as np import torch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL).to(DEVICE).eval() name, _, config = dataset.partition(":") stream = load_dataset(name, name=config or None, split="train", streaming=True) n_seqs = n_tokens // ctx_len rows: list[list[int]] = [] texts: list[str] = [] for doc in stream: texts.append(doc["text"]) if len(texts) == 1000: enc = tok(texts, truncation=True, max_length=ctx_len)["input_ids"] rows += [ids for ids in enc if len(ids) == ctx_len] texts = [] if len(rows) >= n_seqs: break tokens = np.array(rows[:n_seqs], dtype=np.int32) print(f"{len(tokens):,} contexts of {ctx_len} tokens from {dataset}") captured: dict[int, torch.Tensor] = {} for layer in layers: model.gpt_neox.layers[layer].register_forward_hook( lambda _m, _i, out, layer=layer: captured.__setitem__(layer, out[0] if isinstance(out, tuple) else out)) root = Path(tempfile.mkdtemp()) for layer in layers: (root / f"layer_{layer}").mkdir() d_model = model.config.hidden_size with torch.no_grad(): for shard, s in enumerate(range(0, len(tokens), shard_seqs)): chunk = tokens[s:s + shard_seqs] out = {layer: np.empty((len(chunk), ctx_len, d_model), dtype=np.float16) for layer in layers} for b in range(0, len(chunk), 256): model(input_ids=torch.as_tensor(chunk[b:b + 256], dtype=torch.long, device=DEVICE)) for layer in layers: out[layer][b:b + 256] = captured[layer].clamp(-6e4, 6e4).half().cpu().numpy() for layer in layers: np.save(root / f"layer_{layer}" / f"shard_{shard:03d}.npy", out[layer]) np.save(root / "tokens.npy", tokens) print(f"saved {len(layers)} layers x {len(tokens) * ctx_len:,} tokens") acts = await asyncio.gather(*[Dir.from_local(str(root / f"layer_{layer}")) for layer in layers]) return Harvest(model=MODEL, dataset=dataset, layers=layers, ctx_len=ctx_len, d_model=d_model, n_seqs=len(tokens), acts=list(acts), tokens=await File.from_local(str(root / "tokens.npy"))) # {{/docs-fragment harvest}} async def load_layer(harvest: Harvest, layer: int): """Download one layer's shards and put them on the GPU, with the token ids.""" import numpy as np import torch local = Path(await harvest.acts[harvest.layers.index(layer)].download()) shards = sorted(local.rglob("shard_*.npy")) acts = torch.cat([torch.from_numpy(np.load(p)).to(DEVICE) for p in shards]) tokens = np.load(await harvest.tokens.download()) return acts, tokens # {{docs-fragment train}} @gpu_env.task(report=True, cache=flyte.Cache("auto", salt=SAE_VERSION)) async def train_sae( harvest: Harvest, layer: int, width: int, ks: list[int], steps: int = 8000, batch_size: int = 4096, label_k: int = 32, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, held_out: float = 0.05, seed: int = 0, ) -> Trained: """Train one TopK SAE per k on one layer, evaluate each on held-out text, and sample features to label.""" import sae as S import torch from transformers import AutoModelForCausalLM, AutoTokenizer torch.backends.cuda.matmul.allow_tf32 = True acts, tokens = await load_layer(harvest, layer) n_train = int(len(acts) * (1 - held_out)) print(f"layer {layer}: {n_train:,} training and {len(acts) - n_train:,} held-out contexts, width {width}, k {ks}") started = time.time() curve_so_far: list[dict] = [] def on_log(point: dict) -> None: # stream the training curves into this task's report curve_so_far.append(point) flyte.report.replace(reports.training(layer, width, ks, steps, curve_so_far, time.time() - started)) flyte.report.flush() # Training runs in a worker thread, so the report can stream from the callback. saes, scale, curve = await asyncio.to_thread(S.train, acts[:n_train], width, ks, steps, batch_size, seed=seed, on_log=on_log) train_s = time.time() - started print(f"trained {len(ks)} SAEs for {steps} steps in {train_s / 60:.1f} min") # Evaluate on held-out contexts: reconstruction, sparsity, and what the model loses with the SAE in place. model = AutoModelForCausalLM.from_pretrained(harvest.model).to(DEVICE).eval() eval_tokens = torch.as_tensor(tokens[n_train:][:512], dtype=torch.long, device=DEVICE) ce = S.spliced_losses(model, eval_tokens, layer, saes, scale) stats = [] for sae in saes: m = S.reconstruction_metrics(sae, acts[n_train:], scale) st = SAEStats(layer=layer, width=width, k=sae.k, fve=m["fve"], l0=m["l0"], dead_frac=m["dead_frac"], ce_clean=ce["clean"], ce_sae=ce[f"k{sae.k}"], ce_zero=ce["zero"], loss_recovered=S.loss_recovered(ce["clean"], ce[f"k{sae.k}"], ce["zero"]), density_hist=S.density_histogram(m["density"])) print(f" k={sae.k}: FVE {st.fve:.3f}, L0 {st.l0:.1f}, dead {st.dead_frac:.1%}, " f"loss {st.ce_clean:.3f} -> {st.ce_sae:.3f} (zero {st.ce_zero:.3f}), recovered {st.loss_recovered:.1%}") stats.append(st) out = Path(tempfile.mkdtemp()) weights = [] for sae in saes: path = out / f"sae_L{layer}_w{width}_k{sae.k}.pt" torch.save({"state_dict": sae.state_dict(), "scale": scale, "layer": layer, "width": width, "k": sae.k, "d_model": sae.d_model, "model": harvest.model, "hook": f"gpt_neox.layers.{layer} output"}, path) weights.append(await File.from_local(str(path))) examples = None if n_features and label_k in ks: tok = AutoTokenizer.from_pretrained(harvest.model) feats = S.feature_examples(saes[ks.index(label_k)], acts, tokens, scale, lambda t: tok.decode([t]), n_features=n_features, n_top=n_top, n_sampled=n_sampled, seed=seed + layer) path = out / "examples.json" path.write_text(json.dumps(feats)) examples = await File.from_local(str(path)) print(f" sampled {len(feats)} features for autointerp") return Trained(layer=layer, width=width, ks=ks, stats=stats, weights=weights, curve=curve, train_s=round(train_s, 1), examples=examples, label_k=label_k if examples else 0) # {{/docs-fragment train}} # {{docs-fragment claude}} class Unanswered(Exception): """Claude gave no complete JSON answer: a refusal, or output cut off at max_tokens.""" async def ask_claude(system: str, prompt: str, schema: dict, max_tokens: int = 4096) -> str: import anthropic client = anthropic.AsyncAnthropic(max_retries=8) message = await client.messages.create( model=CLAUDE, max_tokens=max_tokens, system=system, output_config={"effort": "low", "format": {"type": "json_schema", "schema": schema}}, messages=[{"role": "user", "content": prompt}], ) # Any thinking counts toward max_tokens, so check that the answer finished before reading it. if message.stop_reason != "end_turn": raise Unanswered(f"stop_reason={message.stop_reason}") text = next((b.text for b in message.content if b.type == "text"), None) if text is None: raise Unanswered("no text block") return text @flyte.trace async def explain_feature(layer: int, feature: int, prompt: str) -> str: """Claude's explanation of one feature. Traced, so a retried task replays it instead of paying again.""" return await ask_claude(autointerp.EXPLAIN_SYSTEM, prompt, autointerp.EXPLAIN_SCHEMA) @flyte.trace async def detect_feature(layer: int, feature: int, prompt: str) -> str: """Claude's guess of which held-out excerpts the explanation predicts. Traced, like the explanation.""" return await ask_claude(autointerp.DETECT_SYSTEM, prompt, autointerp.DETECT_SCHEMA) # {{/docs-fragment claude}} # {{docs-fragment label}} @interp_env.task(retries=1, cache=flyte.Cache("auto", salt=autointerp.VERSION)) async def label_features(layer: int, width: int, k: int, examples: File, concurrency: int = 8) -> str: """Explain each sampled feature, then score every explanation on the feature's held-out contexts. Each feature is also scored with another feature's explanation. That control shows what the test gives an explanation that is fluent but wrong. A feature whose calls fail is recorded as unlabeled, so one bad answer never fails the whole task. """ with open(await examples.download()) as f: features = json.load(f) gate = asyncio.Semaphore(concurrency) unlabeled: list[dict] = [] async def explain(feat: dict) -> dict | None: try: async with gate: answer = json.loads(await explain_feature(layer, feat["feature"], autointerp.explain_prompt(feat))) return {**feat, **answer} except Exception as exc: # Unanswered, malformed JSON, or an API error that outlived the retries unlabeled.append({"feature": feat["feature"], "error": f"explain: {exc}"}) return None labeled = [f for f in await asyncio.gather(*[explain(f) for f in features]) if f is not None] shuffled = [labeled[(i + 1) % len(labeled)]["explanation"] for i in range(len(labeled))] async def score(feat: dict, explanation: str) -> float | None: test = autointerp.detect_set(feat, seed=feat["feature"]) try: async with gate: answer = await detect_feature(layer, feat["feature"], autointerp.detect_prompt(explanation, test)) return autointerp.detection_score(answer, test) except Exception as exc: unlabeled.append({"feature": feat["feature"], "error": f"detect: {exc}"}) return None real = await asyncio.gather(*[score(f, f["explanation"]) for f in labeled]) control = await asyncio.gather(*[score(f, e) for f, e in zip(labeled, shuffled)]) scored = [] for feat, s, c in zip(labeled, real, control): if s is None or c is None: continue feat.update(score=s, control=c) scored.append(feat) print(f" #{feat['feature']}: {s:.2f} (control {c:.2f}) {feat['explanation']}") if scored: print(f"layer {layer}: mean detection {sum(f['score'] for f in scored) / len(scored):.2f}, " f"mismatched control {sum(f['control'] for f in scored) / len(scored):.2f}") unlabeled = list({u["feature"]: u for u in unlabeled}.values()) # one entry per feature for u in unlabeled: print(f" #{u['feature']} unlabeled: {u['error']}") return json.dumps({"layer": layer, "width": width, "k": k, "features": scored, "unlabeled": unlabeled}) # {{/docs-fragment label}} # {{docs-fragment publish}} async def publish(best: Trained, stats: SAEStats, labeled: dict, run_name: str) -> File: card = await artifacts.Card.create_from.aio(content=reports.card(best, stats, labeled, run_name), format="html", card_type="model") scores = [f["score"] for f in labeled["features"]] metadata = artifacts.Metadata.create_model_metadata( name="pythia-70m-topk-sae", description=(f"TopK SAE on Pythia-70m-deduped layer {stats.layer}: {stats.width} features, k={stats.k}, " f"{stats.fve:.0%} variance explained, {stats.loss_recovered:.0%} loss recovered"), framework="PyTorch", model_type="TopK sparse autoencoder", architecture=f"d_model 512 -> {stats.width} -> 512, TopK k={stats.k}", task="interpretability", modality=("text",), serial_format="pt", card=card, attrs={"layer": str(stats.layer), "width": str(stats.width), "k": str(stats.k), "fve": f"{stats.fve:.4f}", "loss_recovered": f"{stats.loss_recovered:.4f}", "dead_frac": f"{stats.dead_frac:.4f}", "detection": f"{sum(scores) / len(scores):.3f}"}, ) return artifacts.new(best.weights[best.ks.index(stats.k)], metadata) # {{/docs-fragment publish}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def find_features( layers: list[int] = [1, 3, 5], widths: list[int] = [4096, 16384], ks: list[int] = [16, 32, 64], n_tokens: int = 8_000_000, steps: int = 8000, label_k: int = 32, label_width: int = 16384, features_per_sae: int = 40, ) -> File: """Harvest activations, train an SAE grid in parallel, label features with Claude, and publish the best SAE.""" if label_width not in widths: label_width = max(widths) started = time.time() await flyte.report.replace.aio(reports.page_start(layers, widths, ks, n_tokens), do_flush=True) harvest = await harvest_activations(layers=layers, n_tokens=n_tokens) trained: list[Trained] = await asyncio.gather(*[ train_sae(harvest, layer, width, ks, steps=steps, label_k=label_k, n_features=features_per_sae if width == label_width else 0) for layer in layers for width in widths ]) await flyte.report.replace.aio(reports.overview(trained, [], harvest, time.time() - started), do_flush=True) labeled = [json.loads(s) for s in await asyncio.gather(*[ label_features(t.layer, t.width, t.label_k, t.examples) for t in trained if t.examples is not None ])] await flyte.report.replace.aio(reports.overview(trained, labeled, harvest, time.time() - started)) flyte.report.get_tab("Feature browser").replace(reports.browser(labeled)) await flyte.report.flush.aio() # The SAE whose features Claude explained best, by mean detection score. mean = lambda lab: sum(f["score"] for f in lab["features"]) / len(lab["features"]) best_labels = max((lab for lab in labeled if lab["features"]), key=mean) best = next(t for t in trained if (t.layer, t.width) == (best_labels["layer"], best_labels["width"])) stats = next(s for s in best.stats if s.k == best_labels["k"]) return await publish(best, stats, best_labels, flyte.ctx().action.run_name) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--smoke", action="store_true", help="1 layer, 1 width, 0.5M tokens, 8 features") parser.add_argument("--widths", type=int, nargs="+", default=[4096, 16384]) args = parser.parse_args() flyte.init_from_config() if args.smoke: run = flyte.run(find_features, layers=[3], widths=[4096], n_tokens=500_000, steps=600, features_per_sae=8) else: run = flyte.run(find_features, widths=args.widths) print(run.url) # {{/docs-fragment run}} CODE4 """TopK sparse autoencoders in plain PyTorch: the model, its training loop, and its metrics. This file never imports Flyte. The pipeline imports it inside its GPU tasks. A sparse autoencoder (SAE) rewrites one activation vector of a language model as a sparse sum of learned directions, its features. A TopK SAE (Gao et al., 2024) keeps exactly the k largest encoder pre-activations per token and zeroes the rest, so the sparsity is set directly instead of being tuned through an L1 penalty: z = ReLU(TopK((x - b_dec) @ W_enc + b_enc)) x_hat = z @ W_dec + b_dec """ import math import numpy as np import torch import torch.nn.functional as F from torch import nn # {{docs-fragment model}} class TopKSAE(nn.Module): def __init__(self, d_model: int, width: int, k: int): super().__init__() self.d_model, self.width, self.k = d_model, width, k w_dec = torch.randn(width, d_model) w_dec /= w_dec.norm(dim=1, keepdim=True) self.W_dec = nn.Parameter(w_dec) # one unit-norm direction per feature self.W_enc = nn.Parameter(w_dec.T.clone()) # tied at init, trained separately self.b_enc = nn.Parameter(torch.zeros(width)) self.b_dec = nn.Parameter(torch.zeros(d_model)) def pre_acts(self, x: torch.Tensor) -> torch.Tensor: return (x - self.b_dec) @ self.W_enc + self.b_enc def encode(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """The k active features per token: their indices, their values, and every pre-activation.""" pre = self.pre_acts(x) vals, idx = pre.topk(self.k, dim=-1) return idx, F.relu(vals), pre def decode(self, idx: torch.Tensor, vals: torch.Tensor) -> torch.Tensor: # A sum of k decoder rows per token, without materializing the width-sized code. return F.embedding_bag(idx, self.W_dec, per_sample_weights=vals, mode="sum") + self.b_dec def forward(self, x: torch.Tensor) -> torch.Tensor: idx, vals, _ = self.encode(x) return self.decode(idx, vals) @torch.no_grad() def normalize_decoder(self) -> None: self.W_dec.data /= self.W_dec.data.norm(dim=1, keepdim=True).clamp_min(1e-8) # {{/docs-fragment model}} def aux_loss(sae: TopKSAE, pre: torch.Tensor, err: torch.Tensor, dead: torch.Tensor) -> torch.Tensor: """AuxK: the dead features' top pre-activations must explain what the live ones missed. This gives dead features a gradient, so fewer of them stay dead (Gao et al., section 2.4). """ n_dead = int(dead.sum()) if n_dead == 0: return pre.new_zeros(()) k_aux = min(sae.d_model // 2, n_dead) vals, idx = pre.masked_fill(~dead, -torch.inf).topk(k_aux, dim=-1) err_hat = F.embedding_bag(idx, sae.W_dec, per_sample_weights=F.relu(vals), mode="sum") return (err - err_hat).pow(2).sum(-1).mean() / err.pow(2).sum(-1).mean().clamp_min(1e-8) # {{docs-fragment train}} def train( acts: torch.Tensor, # [sequences, positions, d_model] float16, on the GPU width: int, ks: list[int], steps: int, batch_size: int = 4096, lr: float | None = None, seed: int = 0, log_every: int = 250, on_log=None, ) -> tuple[list[TopKSAE], float, list[dict]]: """Train one TopK SAE per k on the same batches. Position 0 is skipped (see ``token_index``).""" torch.manual_seed(seed) device = acts.device n_seq, ctx, d = acts.shape scale = activation_scale(acts) # Gao et al. scale the learning rate as 1/sqrt(width). lr = lr or 2e-4 * math.sqrt(16384 / width) saes = [TopKSAE(d, width, k).to(device) for k in ks] sample = gather(acts, token_index(n_seq, ctx, 32_768, device), scale) for sae in saes: sae.b_dec.data = sample.median(dim=0).values # a robust center for the decoder bias opts = [torch.optim.Adam(s.parameters(), lr=lr, betas=(0.9, 0.999)) for s in saes] decay_from = int(steps * 0.8) sched = lambda step: min(1.0, (step + 1) / 100) * min(1.0, (steps - step) / max(steps - decay_from, 1)) last_fired = [torch.zeros(width, dtype=torch.long, device=device) for _ in saes] dead_after = max(1, 1_000_000 // batch_size) # a feature is dead after 1M tokens without firing curve: list[dict] = [] for step in range(steps): x = gather(acts, token_index(n_seq, ctx, batch_size, device), scale) point = {"step": step + 1} for i, (sae, opt) in enumerate(zip(saes, opts)): for g in opt.param_groups: g["lr"] = lr * sched(step) idx, vals, pre = sae.encode(x) x_hat = sae.decode(idx, vals) err = x - x_hat nmse = err.pow(2).sum(-1).mean() / (x - x.mean(0)).pow(2).sum(-1).mean() dead = (step - last_fired[i]) > dead_after loss = nmse + aux_loss(sae, pre, err.detach(), dead) / 32 opt.zero_grad(set_to_none=True) loss.backward() opt.step() sae.normalize_decoder() last_fired[i][idx[vals > 0]] = step point[f"k{sae.k}"] = nmse.item() point[f"dead_k{sae.k}"] = float(dead.float().mean()) if step % log_every == 0 or step == steps - 1: curve.append(point) if on_log: on_log(point) return saes, scale, curve # {{/docs-fragment train}} def token_index(n_seq: int, ctx: int, n: int, device) -> tuple[torch.Tensor, torch.Tensor]: """Random (sequence, position) pairs, never position 0. The first token of every context carries a residual norm many times larger than any other (an attention sink), so SAE work on Pythia conventionally leaves it out. """ return (torch.randint(0, n_seq, (n,), device=device), torch.randint(1, ctx, (n,), device=device)) def gather(acts: torch.Tensor, index: tuple[torch.Tensor, torch.Tensor], scale: float) -> torch.Tensor: return acts[index].float() * scale def activation_scale(acts: torch.Tensor) -> float: """A constant that makes the mean squared norm of an activation equal d_model (as in Gemma Scope).""" x = acts[token_index(acts.shape[0], acts.shape[1], 65_536, acts.device)].float() return float(math.sqrt(acts.shape[-1] / x.pow(2).sum(-1).mean())) # {{docs-fragment metrics}} @torch.no_grad() def reconstruction_metrics(sae: TopKSAE, acts: torch.Tensor, scale: float, chunk: int = 128) -> dict: """Fraction of variance explained, L0, dead features, and each feature's firing rate, on held-out tokens.""" x_all = acts[:, 1:] mean = x_all.reshape(-1, x_all.shape[-1]).float().mean(0) * scale sse = sst = l0 = 0.0 fires = torch.zeros(sae.width, device=acts.device) n = 0 for s in range(0, x_all.shape[0], chunk): x = x_all[s:s + chunk].reshape(-1, x_all.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) x_hat = sae.decode(idx, vals) sse += float((x - x_hat).pow(2).sum()) sst += float((x - mean).pow(2).sum()) on = vals > 0 l0 += float(on.sum()) fires.index_add_(0, idx[on], torch.ones(int(on.sum()), device=acts.device)) n += x.shape[0] density = (fires / n).cpu().numpy() return {"fve": 1 - sse / sst, "l0": l0 / n, "dead_frac": float((density == 0).mean()), "density": density, "tokens": n} @torch.no_grad() def spliced_losses(model, tokens: torch.Tensor, layer: int, saes: list[TopKSAE], scale: float, batch: int = 64) -> dict: """Next-token loss with layer ``layer``'s output left alone, replaced by each SAE's reconstruction, or zeroed. Position 0 is never touched, the same as in training. """ block = model.gpt_neox.layers[layer] state: dict = {"replace": None} def hook(_module, _inputs, output): hidden = output[0] if isinstance(output, tuple) else output if state["replace"] is None: return output new = hidden.clone() new[:, 1:] = state["replace"](hidden[:, 1:]) return (new, *output[1:]) if isinstance(output, tuple) else new def through(sae): def f(h): x = h.reshape(-1, h.shape[-1]).float() * scale return (sae(x) / scale).reshape(h.shape).to(h.dtype) return f def loss() -> float: total = 0.0 for s in range(0, tokens.shape[0], batch): t = tokens[s:s + batch] total += float(model(input_ids=t, labels=t).loss) * t.shape[0] return total / tokens.shape[0] handle = block.register_forward_hook(hook) try: out = {"clean": loss()} state["replace"] = torch.zeros_like out["zero"] = loss() for sae in saes: state["replace"] = through(sae) out[f"k{sae.k}"] = loss() finally: handle.remove() return out def loss_recovered(clean: float, spliced: float, zero: float) -> float: """1.0 when the reconstruction is as good as the real activations, 0.0 when it is no better than zeros.""" return (zero - spliced) / (zero - clean) # {{/docs-fragment metrics}} # {{docs-fragment examples}} @torch.no_grad() def feature_examples( sae: TopKSAE, acts: torch.Tensor, tokens: np.ndarray, scale: float, decode_token, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, n_detect: int = 8, before: int = 24, after: int = 8, seed: int = 0, chunk: int = 128, ) -> list[dict]: """For a random sample of live features: contexts to explain it from, a held-out test set, and a histogram. Claude explains a feature from its ``n_top`` strongest contexts plus ``n_sampled`` contexts drawn from the rest of its clear firings. Top contexts alone hide what a feature does at moderate strength, which is most of its firings (Paulo et al., 2024). The test set for each feature mixes ``n_detect`` contexts where it fires clearly (none of them among its top contexts) with ``n_detect`` random contexts where it does not fire at all. Autointerp scores an explanation by how well it predicts which is which. """ rng = np.random.default_rng(seed) n_seq, ctx, _ = acts.shape # Pass 1: how many contexts each feature fires in. seq_hits = torch.zeros(sae.width, device=acts.device) for s in range(0, n_seq, chunk): x = acts[s:s + chunk, 1:].reshape(-1, acts.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) per_seq = torch.zeros(min(chunk, n_seq - s), sae.width, device=acts.device) rows = torch.arange(per_seq.shape[0], device=acts.device).repeat_interleave((ctx - 1) * sae.k) per_seq.index_put_((rows, idx.flatten()), (vals.flatten() > 0).float(), accumulate=True) seq_hits += (per_seq > 0).float().sum(0) # Sample uniformly among features that fire in enough contexts to fill both example sets. enough = (seq_hits >= 2 * (n_top + n_sampled + n_detect)) & (seq_hits <= n_seq - 2 * n_detect) eligible = torch.nonzero(enough).flatten().cpu().numpy() feats = np.sort(rng.choice(eligible, size=min(n_features, len(eligible)), replace=False)) # Pass 2: every activation of the sampled features, at every position. col = torch.full((sae.width,), -1, dtype=torch.long, device=acts.device) col[torch.as_tensor(feats, device=acts.device)] = torch.arange(len(feats), device=acts.device) f_acts = torch.zeros(n_seq, ctx, len(feats), dtype=torch.float16, device=acts.device) for s in range(0, n_seq, chunk): block = acts[s:s + chunk, 1:] x = block.reshape(-1, acts.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) c = col[idx] keep = (c >= 0) & (vals > 0) rows = torch.arange(x.shape[0], device=acts.device).unsqueeze(1).expand_as(idx)[keep] flat = torch.zeros(x.shape[0], len(feats), dtype=torch.float16, device=acts.device) flat[rows, c[keep]] = vals[keep].half() f_acts[s:s + block.shape[0], 1:] = flat.reshape(block.shape[0], ctx - 1, len(feats)) def window(seq: int, center: int, values: np.ndarray) -> dict: # Every excerpt has the same length, shifted inward at the context's edges, so that # length never tells the detection test which excerpts are positives. size = before + after + 1 lo = min(max(1, center - before), ctx - size) hi = lo + size return {"tokens": [decode_token(int(t)) for t in tokens[seq, lo:hi]], "acts": [round(float(v), 3) for v in values[seq, lo:hi]]} out = [] for j, f in enumerate(feats): a = f_acts[:, :, j].float() seq_max, seq_arg = a.max(dim=1) order = torch.argsort(seq_max, descending=True).cpu().numpy() seq_max, seq_arg, a_np = seq_max.cpu().numpy(), seq_arg.cpu().numpy(), a.cpu().numpy() active = order[seq_max[order] > 0] top = active[:n_top] rest = active[n_top:] # Held-out positives: contexts outside the top where the feature still fires clearly, at # least a quarter of its peak. Weaker firings are near the SAE's noise floor. clear = rest[seq_max[rest] >= 0.25 * seq_max[top[0]]] enough_clear = len(clear) >= n_sampled + n_detect pool = clear if enough_clear else rest[:4 * (n_sampled + n_detect)] picked = rng.choice(pool, size=min(n_sampled + n_detect, len(pool)), replace=False) sampled, test_on = np.sort(picked[:n_sampled]), picked[n_sampled:] test_on_set = [{**window(int(sq), int(seq_arg[sq]), a_np), "active": True} for sq in test_on] quiet = np.nonzero(seq_max == 0)[0] test_off = rng.choice(quiet, size=min(n_detect, len(quiet)), replace=False) if len(quiet) else [] test_off_set = [{**window(int(sq), int(rng.integers(before + 1, ctx - after)), a_np), "active": False} for sq in test_off] nz = a_np[a_np > 0] counts, edges = np.histogram(nz, bins=24, range=(0, float(nz.max()))) out.append({ "feature": int(f), "density": float(len(nz) / (n_seq * (ctx - 1))), "context_rate": float(len(active) / n_seq), "max_act": float(nz.max()), "hist": {"counts": counts.tolist(), "edges": [round(float(e), 3) for e in edges]}, "top": [window(int(sq), int(seq_arg[sq]), a_np) for sq in top], "sampled_clear": bool(enough_clear), # False: sampled from its next-strongest contexts instead "sampled": sorted((window(int(sq), int(seq_arg[sq]), a_np) for sq in sampled), key=lambda w: -max(w["acts"])), "test": test_on_set + test_off_set, }) return out # {{/docs-fragment examples}} def density_histogram(density: np.ndarray, lo: float = -6.0, hi: float = 0.0, step: float = 0.5) -> dict: """How many features fire at each log10 rate, with dead features counted separately.""" alive = density[density > 0] edges = np.arange(lo, hi + step, step) counts, _ = np.histogram(np.log10(alive), bins=edges) return {"edges": edges.tolist(), "counts": counts.tolist(), "dead": int((density == 0).sum())} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/sparse_autoencoders/sae.py* ## Label the features with Claude `feature_examples` samples features at random among those that fire in at least 56 contexts (enough to fill every example set below) and stay silent in at least 16, so very rare and very dense features are left out of the sample. For each one it collects what Claude explains the feature from: the 12 contexts where it fires hardest, and 8 more drawn at random from the contexts where it fires clearly, at a quarter of its peak or more. If a feature has too few clear firings, the 8 come from its next-strongest contexts instead, and the prompt says so. It also builds a held-out test set: 8 other clear firings, and 8 random contexts where the feature does not fire at all. Every excerpt is the same length, so length gives nothing away. ``` """TopK sparse autoencoders in plain PyTorch: the model, its training loop, and its metrics. This file never imports Flyte. The pipeline imports it inside its GPU tasks. A sparse autoencoder (SAE) rewrites one activation vector of a language model as a sparse sum of learned directions, its features. A TopK SAE (Gao et al., 2024) keeps exactly the k largest encoder pre-activations per token and zeroes the rest, so the sparsity is set directly instead of being tuned through an L1 penalty: z = ReLU(TopK((x - b_dec) @ W_enc + b_enc)) x_hat = z @ W_dec + b_dec """ import math import numpy as np import torch import torch.nn.functional as F from torch import nn # {{docs-fragment model}} class TopKSAE(nn.Module): def __init__(self, d_model: int, width: int, k: int): super().__init__() self.d_model, self.width, self.k = d_model, width, k w_dec = torch.randn(width, d_model) w_dec /= w_dec.norm(dim=1, keepdim=True) self.W_dec = nn.Parameter(w_dec) # one unit-norm direction per feature self.W_enc = nn.Parameter(w_dec.T.clone()) # tied at init, trained separately self.b_enc = nn.Parameter(torch.zeros(width)) self.b_dec = nn.Parameter(torch.zeros(d_model)) def pre_acts(self, x: torch.Tensor) -> torch.Tensor: return (x - self.b_dec) @ self.W_enc + self.b_enc def encode(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """The k active features per token: their indices, their values, and every pre-activation.""" pre = self.pre_acts(x) vals, idx = pre.topk(self.k, dim=-1) return idx, F.relu(vals), pre def decode(self, idx: torch.Tensor, vals: torch.Tensor) -> torch.Tensor: # A sum of k decoder rows per token, without materializing the width-sized code. return F.embedding_bag(idx, self.W_dec, per_sample_weights=vals, mode="sum") + self.b_dec def forward(self, x: torch.Tensor) -> torch.Tensor: idx, vals, _ = self.encode(x) return self.decode(idx, vals) @torch.no_grad() def normalize_decoder(self) -> None: self.W_dec.data /= self.W_dec.data.norm(dim=1, keepdim=True).clamp_min(1e-8) # {{/docs-fragment model}} def aux_loss(sae: TopKSAE, pre: torch.Tensor, err: torch.Tensor, dead: torch.Tensor) -> torch.Tensor: """AuxK: the dead features' top pre-activations must explain what the live ones missed. This gives dead features a gradient, so fewer of them stay dead (Gao et al., section 2.4). """ n_dead = int(dead.sum()) if n_dead == 0: return pre.new_zeros(()) k_aux = min(sae.d_model // 2, n_dead) vals, idx = pre.masked_fill(~dead, -torch.inf).topk(k_aux, dim=-1) err_hat = F.embedding_bag(idx, sae.W_dec, per_sample_weights=F.relu(vals), mode="sum") return (err - err_hat).pow(2).sum(-1).mean() / err.pow(2).sum(-1).mean().clamp_min(1e-8) # {{docs-fragment train}} def train( acts: torch.Tensor, # [sequences, positions, d_model] float16, on the GPU width: int, ks: list[int], steps: int, batch_size: int = 4096, lr: float | None = None, seed: int = 0, log_every: int = 250, on_log=None, ) -> tuple[list[TopKSAE], float, list[dict]]: """Train one TopK SAE per k on the same batches. Position 0 is skipped (see ``token_index``).""" torch.manual_seed(seed) device = acts.device n_seq, ctx, d = acts.shape scale = activation_scale(acts) # Gao et al. scale the learning rate as 1/sqrt(width). lr = lr or 2e-4 * math.sqrt(16384 / width) saes = [TopKSAE(d, width, k).to(device) for k in ks] sample = gather(acts, token_index(n_seq, ctx, 32_768, device), scale) for sae in saes: sae.b_dec.data = sample.median(dim=0).values # a robust center for the decoder bias opts = [torch.optim.Adam(s.parameters(), lr=lr, betas=(0.9, 0.999)) for s in saes] decay_from = int(steps * 0.8) sched = lambda step: min(1.0, (step + 1) / 100) * min(1.0, (steps - step) / max(steps - decay_from, 1)) last_fired = [torch.zeros(width, dtype=torch.long, device=device) for _ in saes] dead_after = max(1, 1_000_000 // batch_size) # a feature is dead after 1M tokens without firing curve: list[dict] = [] for step in range(steps): x = gather(acts, token_index(n_seq, ctx, batch_size, device), scale) point = {"step": step + 1} for i, (sae, opt) in enumerate(zip(saes, opts)): for g in opt.param_groups: g["lr"] = lr * sched(step) idx, vals, pre = sae.encode(x) x_hat = sae.decode(idx, vals) err = x - x_hat nmse = err.pow(2).sum(-1).mean() / (x - x.mean(0)).pow(2).sum(-1).mean() dead = (step - last_fired[i]) > dead_after loss = nmse + aux_loss(sae, pre, err.detach(), dead) / 32 opt.zero_grad(set_to_none=True) loss.backward() opt.step() sae.normalize_decoder() last_fired[i][idx[vals > 0]] = step point[f"k{sae.k}"] = nmse.item() point[f"dead_k{sae.k}"] = float(dead.float().mean()) if step % log_every == 0 or step == steps - 1: curve.append(point) if on_log: on_log(point) return saes, scale, curve # {{/docs-fragment train}} def token_index(n_seq: int, ctx: int, n: int, device) -> tuple[torch.Tensor, torch.Tensor]: """Random (sequence, position) pairs, never position 0. The first token of every context carries a residual norm many times larger than any other (an attention sink), so SAE work on Pythia conventionally leaves it out. """ return (torch.randint(0, n_seq, (n,), device=device), torch.randint(1, ctx, (n,), device=device)) def gather(acts: torch.Tensor, index: tuple[torch.Tensor, torch.Tensor], scale: float) -> torch.Tensor: return acts[index].float() * scale def activation_scale(acts: torch.Tensor) -> float: """A constant that makes the mean squared norm of an activation equal d_model (as in Gemma Scope).""" x = acts[token_index(acts.shape[0], acts.shape[1], 65_536, acts.device)].float() return float(math.sqrt(acts.shape[-1] / x.pow(2).sum(-1).mean())) # {{docs-fragment metrics}} @torch.no_grad() def reconstruction_metrics(sae: TopKSAE, acts: torch.Tensor, scale: float, chunk: int = 128) -> dict: """Fraction of variance explained, L0, dead features, and each feature's firing rate, on held-out tokens.""" x_all = acts[:, 1:] mean = x_all.reshape(-1, x_all.shape[-1]).float().mean(0) * scale sse = sst = l0 = 0.0 fires = torch.zeros(sae.width, device=acts.device) n = 0 for s in range(0, x_all.shape[0], chunk): x = x_all[s:s + chunk].reshape(-1, x_all.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) x_hat = sae.decode(idx, vals) sse += float((x - x_hat).pow(2).sum()) sst += float((x - mean).pow(2).sum()) on = vals > 0 l0 += float(on.sum()) fires.index_add_(0, idx[on], torch.ones(int(on.sum()), device=acts.device)) n += x.shape[0] density = (fires / n).cpu().numpy() return {"fve": 1 - sse / sst, "l0": l0 / n, "dead_frac": float((density == 0).mean()), "density": density, "tokens": n} @torch.no_grad() def spliced_losses(model, tokens: torch.Tensor, layer: int, saes: list[TopKSAE], scale: float, batch: int = 64) -> dict: """Next-token loss with layer ``layer``'s output left alone, replaced by each SAE's reconstruction, or zeroed. Position 0 is never touched, the same as in training. """ block = model.gpt_neox.layers[layer] state: dict = {"replace": None} def hook(_module, _inputs, output): hidden = output[0] if isinstance(output, tuple) else output if state["replace"] is None: return output new = hidden.clone() new[:, 1:] = state["replace"](hidden[:, 1:]) return (new, *output[1:]) if isinstance(output, tuple) else new def through(sae): def f(h): x = h.reshape(-1, h.shape[-1]).float() * scale return (sae(x) / scale).reshape(h.shape).to(h.dtype) return f def loss() -> float: total = 0.0 for s in range(0, tokens.shape[0], batch): t = tokens[s:s + batch] total += float(model(input_ids=t, labels=t).loss) * t.shape[0] return total / tokens.shape[0] handle = block.register_forward_hook(hook) try: out = {"clean": loss()} state["replace"] = torch.zeros_like out["zero"] = loss() for sae in saes: state["replace"] = through(sae) out[f"k{sae.k}"] = loss() finally: handle.remove() return out def loss_recovered(clean: float, spliced: float, zero: float) -> float: """1.0 when the reconstruction is as good as the real activations, 0.0 when it is no better than zeros.""" return (zero - spliced) / (zero - clean) # {{/docs-fragment metrics}} # {{docs-fragment examples}} @torch.no_grad() def feature_examples( sae: TopKSAE, acts: torch.Tensor, tokens: np.ndarray, scale: float, decode_token, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, n_detect: int = 8, before: int = 24, after: int = 8, seed: int = 0, chunk: int = 128, ) -> list[dict]: """For a random sample of live features: contexts to explain it from, a held-out test set, and a histogram. Claude explains a feature from its ``n_top`` strongest contexts plus ``n_sampled`` contexts drawn from the rest of its clear firings. Top contexts alone hide what a feature does at moderate strength, which is most of its firings (Paulo et al., 2024). The test set for each feature mixes ``n_detect`` contexts where it fires clearly (none of them among its top contexts) with ``n_detect`` random contexts where it does not fire at all. Autointerp scores an explanation by how well it predicts which is which. """ rng = np.random.default_rng(seed) n_seq, ctx, _ = acts.shape # Pass 1: how many contexts each feature fires in. seq_hits = torch.zeros(sae.width, device=acts.device) for s in range(0, n_seq, chunk): x = acts[s:s + chunk, 1:].reshape(-1, acts.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) per_seq = torch.zeros(min(chunk, n_seq - s), sae.width, device=acts.device) rows = torch.arange(per_seq.shape[0], device=acts.device).repeat_interleave((ctx - 1) * sae.k) per_seq.index_put_((rows, idx.flatten()), (vals.flatten() > 0).float(), accumulate=True) seq_hits += (per_seq > 0).float().sum(0) # Sample uniformly among features that fire in enough contexts to fill both example sets. enough = (seq_hits >= 2 * (n_top + n_sampled + n_detect)) & (seq_hits <= n_seq - 2 * n_detect) eligible = torch.nonzero(enough).flatten().cpu().numpy() feats = np.sort(rng.choice(eligible, size=min(n_features, len(eligible)), replace=False)) # Pass 2: every activation of the sampled features, at every position. col = torch.full((sae.width,), -1, dtype=torch.long, device=acts.device) col[torch.as_tensor(feats, device=acts.device)] = torch.arange(len(feats), device=acts.device) f_acts = torch.zeros(n_seq, ctx, len(feats), dtype=torch.float16, device=acts.device) for s in range(0, n_seq, chunk): block = acts[s:s + chunk, 1:] x = block.reshape(-1, acts.shape[-1]).float() * scale idx, vals, _ = sae.encode(x) c = col[idx] keep = (c >= 0) & (vals > 0) rows = torch.arange(x.shape[0], device=acts.device).unsqueeze(1).expand_as(idx)[keep] flat = torch.zeros(x.shape[0], len(feats), dtype=torch.float16, device=acts.device) flat[rows, c[keep]] = vals[keep].half() f_acts[s:s + block.shape[0], 1:] = flat.reshape(block.shape[0], ctx - 1, len(feats)) def window(seq: int, center: int, values: np.ndarray) -> dict: # Every excerpt has the same length, shifted inward at the context's edges, so that # length never tells the detection test which excerpts are positives. size = before + after + 1 lo = min(max(1, center - before), ctx - size) hi = lo + size return {"tokens": [decode_token(int(t)) for t in tokens[seq, lo:hi]], "acts": [round(float(v), 3) for v in values[seq, lo:hi]]} out = [] for j, f in enumerate(feats): a = f_acts[:, :, j].float() seq_max, seq_arg = a.max(dim=1) order = torch.argsort(seq_max, descending=True).cpu().numpy() seq_max, seq_arg, a_np = seq_max.cpu().numpy(), seq_arg.cpu().numpy(), a.cpu().numpy() active = order[seq_max[order] > 0] top = active[:n_top] rest = active[n_top:] # Held-out positives: contexts outside the top where the feature still fires clearly, at # least a quarter of its peak. Weaker firings are near the SAE's noise floor. clear = rest[seq_max[rest] >= 0.25 * seq_max[top[0]]] enough_clear = len(clear) >= n_sampled + n_detect pool = clear if enough_clear else rest[:4 * (n_sampled + n_detect)] picked = rng.choice(pool, size=min(n_sampled + n_detect, len(pool)), replace=False) sampled, test_on = np.sort(picked[:n_sampled]), picked[n_sampled:] test_on_set = [{**window(int(sq), int(seq_arg[sq]), a_np), "active": True} for sq in test_on] quiet = np.nonzero(seq_max == 0)[0] test_off = rng.choice(quiet, size=min(n_detect, len(quiet)), replace=False) if len(quiet) else [] test_off_set = [{**window(int(sq), int(rng.integers(before + 1, ctx - after)), a_np), "active": False} for sq in test_off] nz = a_np[a_np > 0] counts, edges = np.histogram(nz, bins=24, range=(0, float(nz.max()))) out.append({ "feature": int(f), "density": float(len(nz) / (n_seq * (ctx - 1))), "context_rate": float(len(active) / n_seq), "max_act": float(nz.max()), "hist": {"counts": counts.tolist(), "edges": [round(float(e), 3) for e in edges]}, "top": [window(int(sq), int(seq_arg[sq]), a_np) for sq in top], "sampled_clear": bool(enough_clear), # False: sampled from its next-strongest contexts instead "sampled": sorted((window(int(sq), int(seq_arg[sq]), a_np) for sq in sampled), key=lambda w: -max(w["acts"])), "test": test_on_set + test_off_set, }) return out # {{/docs-fragment examples}} def density_histogram(density: np.ndarray, lo: float = -6.0, hi: float = 0.0, step: float = 0.5) -> dict: """How many features fire at each log10 rate, with dead features counted separately.""" alive = density[density > 0] edges = np.arange(lo, hi + step, step) counts, _ = np.histogram(np.log10(alive), bins=edges) return {"edges": edges.tolist(), "counts": counts.tolist(), "dead": int((density == 0).sum())} CODE5 """Automated interpretability: what Claude sees when it explains a feature, and when it tests one. The method follows Bills et al. (2023) and Paulo et al. (2024). One call shows Claude a feature's top-activating contexts and a random sample of its other firings, with the activating tokens marked, and asks for a short explanation. A second call, which never sees those contexts, gets the explanation and a shuffled mix of held-out contexts: some where the feature fires, some where it does not. Claude says which ones fire. The score is the balanced accuracy, so 0.5 is chance. """ import json import random # Bump when the prompts, the schemas, the excerpt format, or the scoring change. label_features # salts its cache with this, so a change here re-labels instead of returning cached labels. VERSION = "top12-sampled8/2" # {{docs-fragment prompts}} EXPLAIN_SYSTEM = """\ You are an interpretability researcher. You study one feature of a sparse autoencoder trained on a small language model's residual stream. A feature is a direction that is active on some tokens and silent on the rest. You will see the text excerpts where the feature is most active, then a random sample of other excerpts where it fires, with every token where it fires at a tenth of its peak or more marked as <>, and the peak activation of each excerpt on a 0-10 scale. Find what the marked tokens have in common, in the token itself and in its context. Be specific: name the words, the syntax, or the topic. If it fires on a token only in some contexts, say which. Your explanation will be used to predict, for unseen excerpts, whether the feature fires anywhere in them.""" EXPLAIN_SCHEMA = { "type": "object", "properties": { "notes": {"type": "string", "description": "One or two sentences of reasoning about the pattern."}, "explanation": {"type": "string", "description": "The explanation, at most 20 words."}, }, "required": ["notes", "explanation"], "additionalProperties": False, } DETECT_SYSTEM = """\ You test an explanation of one feature of a sparse autoencoder trained on a small language model. You will get the explanation and numbered text excerpts. Some excerpts contain a token where the feature fires and the rest do not. Using only the explanation, list the numbers of the excerpts in which the feature fires.""" DETECT_SCHEMA = { "type": "object", "properties": {"active": {"type": "array", "items": {"type": "integer"}}}, "required": ["active"], "additionalProperties": False, } # {{/docs-fragment prompts}} def _clean(tok: str) -> str: return tok.replace("\n", "\\n") def marked(example: dict, peak: float) -> str: """One excerpt with every token that fires at 1/10 of the peak or more marked, then its peak on a 0-10 scale.""" pairs = zip(example["tokens"], example["acts"]) text = "".join(f"<<{_clean(t)}>>" if a >= 0.1 * peak else _clean(t) for t, a in pairs) return f"{text} [peak {round(10 * max(example['acts']) / peak)}]" def explain_prompt(feature: dict) -> str: peak = feature["max_act"] top = "\n".join(f"{i + 1}. {marked(ex, peak)}" for i, ex in enumerate(feature["top"])) n = len(feature["top"]) rest = "\n".join(f"{n + i + 1}. {marked(ex, peak)}" for i, ex in enumerate(feature["sampled"])) if feature.get("sampled_clear", True): which = "A random sample of the other excerpts where it fires clearly (at least a quarter of its peak)" else: # too few clear firings: feature_examples fell back to the next-strongest excerpts which = "A random sample of its next-strongest excerpts, some of them weak firings" return (f"The excerpts where one feature fires most strongly:\n\n{top}\n\n" f"{which}:\n\n{rest}\n\n" "Explain the feature. Cover what it does at moderate strength too, not only at its peak.") def detect_set(feature: dict, seed: int) -> list[dict]: """The feature's held-out excerpts in a fixed random order.""" test = list(feature["test"]) random.Random(seed).shuffle(test) return test def detect_prompt(explanation: str, test: list[dict]) -> str: lines = "\n".join(f"{i + 1}. {''.join(_clean(t) for t in ex['tokens'])}" for i, ex in enumerate(test)) return f"Explanation: {explanation}\n\nExcerpts:\n\n{lines}\n\nWhich excerpts contain a token where the feature fires?" # {{docs-fragment score}} def detection_score(answer_json: str, test: list[dict]) -> float: """Balanced accuracy of Claude's predictions against where the feature really fired.""" predicted = {int(i) - 1 for i in json.loads(answer_json)["active"]} on = [i for i, ex in enumerate(test) if ex["active"]] off = [i for i, ex in enumerate(test) if not ex["active"]] hit = sum(i in predicted for i in on) / max(len(on), 1) reject = sum(i not in predicted for i in off) / max(len(off), 1) return (hit + reject) / 2 # {{/docs-fragment score}} CODE6 """Automated interpretability: what Claude sees when it explains a feature, and when it tests one. The method follows Bills et al. (2023) and Paulo et al. (2024). One call shows Claude a feature's top-activating contexts and a random sample of its other firings, with the activating tokens marked, and asks for a short explanation. A second call, which never sees those contexts, gets the explanation and a shuffled mix of held-out contexts: some where the feature fires, some where it does not. Claude says which ones fire. The score is the balanced accuracy, so 0.5 is chance. """ import json import random # Bump when the prompts, the schemas, the excerpt format, or the scoring change. label_features # salts its cache with this, so a change here re-labels instead of returning cached labels. VERSION = "top12-sampled8/2" # {{docs-fragment prompts}} EXPLAIN_SYSTEM = """\ You are an interpretability researcher. You study one feature of a sparse autoencoder trained on a small language model's residual stream. A feature is a direction that is active on some tokens and silent on the rest. You will see the text excerpts where the feature is most active, then a random sample of other excerpts where it fires, with every token where it fires at a tenth of its peak or more marked as <>, and the peak activation of each excerpt on a 0-10 scale. Find what the marked tokens have in common, in the token itself and in its context. Be specific: name the words, the syntax, or the topic. If it fires on a token only in some contexts, say which. Your explanation will be used to predict, for unseen excerpts, whether the feature fires anywhere in them.""" EXPLAIN_SCHEMA = { "type": "object", "properties": { "notes": {"type": "string", "description": "One or two sentences of reasoning about the pattern."}, "explanation": {"type": "string", "description": "The explanation, at most 20 words."}, }, "required": ["notes", "explanation"], "additionalProperties": False, } DETECT_SYSTEM = """\ You test an explanation of one feature of a sparse autoencoder trained on a small language model. You will get the explanation and numbered text excerpts. Some excerpts contain a token where the feature fires and the rest do not. Using only the explanation, list the numbers of the excerpts in which the feature fires.""" DETECT_SCHEMA = { "type": "object", "properties": {"active": {"type": "array", "items": {"type": "integer"}}}, "required": ["active"], "additionalProperties": False, } # {{/docs-fragment prompts}} def _clean(tok: str) -> str: return tok.replace("\n", "\\n") def marked(example: dict, peak: float) -> str: """One excerpt with every token that fires at 1/10 of the peak or more marked, then its peak on a 0-10 scale.""" pairs = zip(example["tokens"], example["acts"]) text = "".join(f"<<{_clean(t)}>>" if a >= 0.1 * peak else _clean(t) for t, a in pairs) return f"{text} [peak {round(10 * max(example['acts']) / peak)}]" def explain_prompt(feature: dict) -> str: peak = feature["max_act"] top = "\n".join(f"{i + 1}. {marked(ex, peak)}" for i, ex in enumerate(feature["top"])) n = len(feature["top"]) rest = "\n".join(f"{n + i + 1}. {marked(ex, peak)}" for i, ex in enumerate(feature["sampled"])) if feature.get("sampled_clear", True): which = "A random sample of the other excerpts where it fires clearly (at least a quarter of its peak)" else: # too few clear firings: feature_examples fell back to the next-strongest excerpts which = "A random sample of its next-strongest excerpts, some of them weak firings" return (f"The excerpts where one feature fires most strongly:\n\n{top}\n\n" f"{which}:\n\n{rest}\n\n" "Explain the feature. Cover what it does at moderate strength too, not only at its peak.") def detect_set(feature: dict, seed: int) -> list[dict]: """The feature's held-out excerpts in a fixed random order.""" test = list(feature["test"]) random.Random(seed).shuffle(test) return test def detect_prompt(explanation: str, test: list[dict]) -> str: lines = "\n".join(f"{i + 1}. {''.join(_clean(t) for t in ex['tokens'])}" for i, ex in enumerate(test)) return f"Explanation: {explanation}\n\nExcerpts:\n\n{lines}\n\nWhich excerpts contain a token where the feature fires?" # {{docs-fragment score}} def detection_score(answer_json: str, test: list[dict]) -> float: """Balanced accuracy of Claude's predictions against where the feature really fired.""" predicted = {int(i) - 1 for i in json.loads(answer_json)["active"]} on = [i for i, ex in enumerate(test) if ex["active"]] off = [i for i, ex in enumerate(test) if not ex["active"]] hit = sum(i in predicted for i in on) / max(len(on), 1) reject = sum(i not in predicted for i in off) / max(len(off), 1) return (hit + reject) / 2 # {{/docs-fragment score}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/sparse_autoencoders/autointerp.py* An answer can still fail to finish: Claude may refuse, or run out of `max_tokens`, which also counts any thinking. `ask_claude` checks `stop_reason` before it reads the answer, and `label_features` records a feature whose calls fail as unlabeled, so one bad answer never fails the task. The report counts unlabeled features per SAE. Each call is a `flyte.trace`. Its input and output are recorded in the run, so if the task fails partway through and retries, the calls that already finished replay from the record instead of going back to the API. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "find_features" # params = "layers=[3] widths=[4096] n_tokens=500000 steps=600 features_per_sae=8" # /// """Find interpretable features in a language model with sparse autoencoders, and label them with Claude. harvest_activations (GPU, cached) Pythia-70m over FineWeb: residual stream at several layers -> Dir per layer -> N x train_sae (GPU each) one (layer, width) per task: TopK SAEs at k = 16, 32, 64, then variance explained, L0, dead features, and loss with the SAE spliced in -> M x label_features (CPU) Claude explains sampled features and is scored on held-out contexts -> report (feature browser) -> publish the most interpretable SAE as an artifact The harvest is cached on its inputs. Re-running with another width, k, or step budget reuses the activations, and every (layer, width) that was already trained, and only trains what is new. python find_features.py # 3 layers x 2 widths, 8M tokens, about 30 minutes python find_features.py --smoke # 1 layer x 1 width, 0.5M tokens python find_features.py --widths 4096 16384 32768 # reuses the harvest and the first two widths """ import argparse import asyncio import json import os import tempfile import time from dataclasses import dataclass, field from pathlib import Path import autointerp import flyte import flyte.artifacts as artifacts import flyte.report import reports from flyte.io import Dir, File MODEL = "EleutherAI/pythia-70m-deduped" CLAUDE = "claude-opus-5-5" # The name of the secret that holds your Anthropic API key. Set ANTHROPIC_SECRET when you # launch to use a secret with another name. ANTHROPIC_SECRET = os.getenv("ANTHROPIC_SECRET", "anthropic-api-key") # Bump when sae.py changes (the SAE, its training, its metrics, or feature sampling). train_sae # salts its cache with this; cache="auto" alone hashes only the task's own body. SAE_VERSION = "topk-auxk/2" # Set SAE_DEVICE=cpu to run a tiny version on a laptop with flyte's local mode. DEVICE = os.getenv("SAE_DEVICE", "cuda") # {{docs-fragment envs}} image = flyte.Image.from_debian_base(name="sae-features").with_pip_packages( "torch==2.9.1", "transformers==4.57.3", "datasets==4.4.2", "numpy<3", "anthropic==2.6.0", ) # One GPU per task: the harvest, and every SAE trainer. sae.py is imported inside the tasks. gpu_env = flyte.TaskEnvironment( name="sae-gpu", image=image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L4:1", disk="80Gi"), cache="auto", include=["sae.py"], ) # Autointerp is API calls, so CPU only. Only this environment holds the API key. interp_env = flyte.TaskEnvironment( name="sae-autointerp", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), secrets=[flyte.Secret(key=ANTHROPIC_SECRET, as_env_var="ANTHROPIC_API_KEY")], cache="auto", ) driver_env = flyte.TaskEnvironment( name="sae-driver", image=image, resources=flyte.Resources(cpu=2, memory="8Gi"), # The driver declares label_features when it calls it, so it needs the same secret name. env_vars={"ANTHROPIC_SECRET": ANTHROPIC_SECRET}, depends_on=[gpu_env, interp_env], ) # {{/docs-fragment envs}} @dataclass class Harvest: model: str dataset: str layers: list[int] ctx_len: int d_model: int n_seqs: int acts: list[Dir] # one per layer: shard_*.npy, float16 [sequences, ctx_len, d_model] tokens: File # int32 [sequences, ctx_len] @dataclass class SAEStats: layer: int width: int k: int fve: float l0: float dead_frac: float ce_clean: float ce_sae: float ce_zero: float loss_recovered: float density_hist: dict = field(default_factory=dict) @dataclass class Trained: layer: int width: int ks: list[int] stats: list[SAEStats] weights: list[File] # one per k curve: list[dict] train_s: float examples: File | None = None # sampled features with their contexts, for the k that gets labeled label_k: int = 0 # {{docs-fragment harvest}} @gpu_env.task async def harvest_activations( layers: list[int], n_tokens: int = 8_000_000, ctx_len: int = 128, dataset: str = "HuggingFaceFW/fineweb:sample-10BT", shard_seqs: int = 4096, ) -> Harvest: """Run Pythia over FineWeb and save the residual stream after each layer in ``layers``. Each context is the first ``ctx_len`` tokens of one document. Activations are float16 shards, one directory per layer, so a trainer downloads only the layer it needs. """ import numpy as np import torch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL).to(DEVICE).eval() name, _, config = dataset.partition(":") stream = load_dataset(name, name=config or None, split="train", streaming=True) n_seqs = n_tokens // ctx_len rows: list[list[int]] = [] texts: list[str] = [] for doc in stream: texts.append(doc["text"]) if len(texts) == 1000: enc = tok(texts, truncation=True, max_length=ctx_len)["input_ids"] rows += [ids for ids in enc if len(ids) == ctx_len] texts = [] if len(rows) >= n_seqs: break tokens = np.array(rows[:n_seqs], dtype=np.int32) print(f"{len(tokens):,} contexts of {ctx_len} tokens from {dataset}") captured: dict[int, torch.Tensor] = {} for layer in layers: model.gpt_neox.layers[layer].register_forward_hook( lambda _m, _i, out, layer=layer: captured.__setitem__(layer, out[0] if isinstance(out, tuple) else out)) root = Path(tempfile.mkdtemp()) for layer in layers: (root / f"layer_{layer}").mkdir() d_model = model.config.hidden_size with torch.no_grad(): for shard, s in enumerate(range(0, len(tokens), shard_seqs)): chunk = tokens[s:s + shard_seqs] out = {layer: np.empty((len(chunk), ctx_len, d_model), dtype=np.float16) for layer in layers} for b in range(0, len(chunk), 256): model(input_ids=torch.as_tensor(chunk[b:b + 256], dtype=torch.long, device=DEVICE)) for layer in layers: out[layer][b:b + 256] = captured[layer].clamp(-6e4, 6e4).half().cpu().numpy() for layer in layers: np.save(root / f"layer_{layer}" / f"shard_{shard:03d}.npy", out[layer]) np.save(root / "tokens.npy", tokens) print(f"saved {len(layers)} layers x {len(tokens) * ctx_len:,} tokens") acts = await asyncio.gather(*[Dir.from_local(str(root / f"layer_{layer}")) for layer in layers]) return Harvest(model=MODEL, dataset=dataset, layers=layers, ctx_len=ctx_len, d_model=d_model, n_seqs=len(tokens), acts=list(acts), tokens=await File.from_local(str(root / "tokens.npy"))) # {{/docs-fragment harvest}} async def load_layer(harvest: Harvest, layer: int): """Download one layer's shards and put them on the GPU, with the token ids.""" import numpy as np import torch local = Path(await harvest.acts[harvest.layers.index(layer)].download()) shards = sorted(local.rglob("shard_*.npy")) acts = torch.cat([torch.from_numpy(np.load(p)).to(DEVICE) for p in shards]) tokens = np.load(await harvest.tokens.download()) return acts, tokens # {{docs-fragment train}} @gpu_env.task(report=True, cache=flyte.Cache("auto", salt=SAE_VERSION)) async def train_sae( harvest: Harvest, layer: int, width: int, ks: list[int], steps: int = 8000, batch_size: int = 4096, label_k: int = 32, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, held_out: float = 0.05, seed: int = 0, ) -> Trained: """Train one TopK SAE per k on one layer, evaluate each on held-out text, and sample features to label.""" import sae as S import torch from transformers import AutoModelForCausalLM, AutoTokenizer torch.backends.cuda.matmul.allow_tf32 = True acts, tokens = await load_layer(harvest, layer) n_train = int(len(acts) * (1 - held_out)) print(f"layer {layer}: {n_train:,} training and {len(acts) - n_train:,} held-out contexts, width {width}, k {ks}") started = time.time() curve_so_far: list[dict] = [] def on_log(point: dict) -> None: # stream the training curves into this task's report curve_so_far.append(point) flyte.report.replace(reports.training(layer, width, ks, steps, curve_so_far, time.time() - started)) flyte.report.flush() # Training runs in a worker thread, so the report can stream from the callback. saes, scale, curve = await asyncio.to_thread(S.train, acts[:n_train], width, ks, steps, batch_size, seed=seed, on_log=on_log) train_s = time.time() - started print(f"trained {len(ks)} SAEs for {steps} steps in {train_s / 60:.1f} min") # Evaluate on held-out contexts: reconstruction, sparsity, and what the model loses with the SAE in place. model = AutoModelForCausalLM.from_pretrained(harvest.model).to(DEVICE).eval() eval_tokens = torch.as_tensor(tokens[n_train:][:512], dtype=torch.long, device=DEVICE) ce = S.spliced_losses(model, eval_tokens, layer, saes, scale) stats = [] for sae in saes: m = S.reconstruction_metrics(sae, acts[n_train:], scale) st = SAEStats(layer=layer, width=width, k=sae.k, fve=m["fve"], l0=m["l0"], dead_frac=m["dead_frac"], ce_clean=ce["clean"], ce_sae=ce[f"k{sae.k}"], ce_zero=ce["zero"], loss_recovered=S.loss_recovered(ce["clean"], ce[f"k{sae.k}"], ce["zero"]), density_hist=S.density_histogram(m["density"])) print(f" k={sae.k}: FVE {st.fve:.3f}, L0 {st.l0:.1f}, dead {st.dead_frac:.1%}, " f"loss {st.ce_clean:.3f} -> {st.ce_sae:.3f} (zero {st.ce_zero:.3f}), recovered {st.loss_recovered:.1%}") stats.append(st) out = Path(tempfile.mkdtemp()) weights = [] for sae in saes: path = out / f"sae_L{layer}_w{width}_k{sae.k}.pt" torch.save({"state_dict": sae.state_dict(), "scale": scale, "layer": layer, "width": width, "k": sae.k, "d_model": sae.d_model, "model": harvest.model, "hook": f"gpt_neox.layers.{layer} output"}, path) weights.append(await File.from_local(str(path))) examples = None if n_features and label_k in ks: tok = AutoTokenizer.from_pretrained(harvest.model) feats = S.feature_examples(saes[ks.index(label_k)], acts, tokens, scale, lambda t: tok.decode([t]), n_features=n_features, n_top=n_top, n_sampled=n_sampled, seed=seed + layer) path = out / "examples.json" path.write_text(json.dumps(feats)) examples = await File.from_local(str(path)) print(f" sampled {len(feats)} features for autointerp") return Trained(layer=layer, width=width, ks=ks, stats=stats, weights=weights, curve=curve, train_s=round(train_s, 1), examples=examples, label_k=label_k if examples else 0) # {{/docs-fragment train}} # {{docs-fragment claude}} class Unanswered(Exception): """Claude gave no complete JSON answer: a refusal, or output cut off at max_tokens.""" async def ask_claude(system: str, prompt: str, schema: dict, max_tokens: int = 4096) -> str: import anthropic client = anthropic.AsyncAnthropic(max_retries=8) message = await client.messages.create( model=CLAUDE, max_tokens=max_tokens, system=system, output_config={"effort": "low", "format": {"type": "json_schema", "schema": schema}}, messages=[{"role": "user", "content": prompt}], ) # Any thinking counts toward max_tokens, so check that the answer finished before reading it. if message.stop_reason != "end_turn": raise Unanswered(f"stop_reason={message.stop_reason}") text = next((b.text for b in message.content if b.type == "text"), None) if text is None: raise Unanswered("no text block") return text @flyte.trace async def explain_feature(layer: int, feature: int, prompt: str) -> str: """Claude's explanation of one feature. Traced, so a retried task replays it instead of paying again.""" return await ask_claude(autointerp.EXPLAIN_SYSTEM, prompt, autointerp.EXPLAIN_SCHEMA) @flyte.trace async def detect_feature(layer: int, feature: int, prompt: str) -> str: """Claude's guess of which held-out excerpts the explanation predicts. Traced, like the explanation.""" return await ask_claude(autointerp.DETECT_SYSTEM, prompt, autointerp.DETECT_SCHEMA) # {{/docs-fragment claude}} # {{docs-fragment label}} @interp_env.task(retries=1, cache=flyte.Cache("auto", salt=autointerp.VERSION)) async def label_features(layer: int, width: int, k: int, examples: File, concurrency: int = 8) -> str: """Explain each sampled feature, then score every explanation on the feature's held-out contexts. Each feature is also scored with another feature's explanation. That control shows what the test gives an explanation that is fluent but wrong. A feature whose calls fail is recorded as unlabeled, so one bad answer never fails the whole task. """ with open(await examples.download()) as f: features = json.load(f) gate = asyncio.Semaphore(concurrency) unlabeled: list[dict] = [] async def explain(feat: dict) -> dict | None: try: async with gate: answer = json.loads(await explain_feature(layer, feat["feature"], autointerp.explain_prompt(feat))) return {**feat, **answer} except Exception as exc: # Unanswered, malformed JSON, or an API error that outlived the retries unlabeled.append({"feature": feat["feature"], "error": f"explain: {exc}"}) return None labeled = [f for f in await asyncio.gather(*[explain(f) for f in features]) if f is not None] shuffled = [labeled[(i + 1) % len(labeled)]["explanation"] for i in range(len(labeled))] async def score(feat: dict, explanation: str) -> float | None: test = autointerp.detect_set(feat, seed=feat["feature"]) try: async with gate: answer = await detect_feature(layer, feat["feature"], autointerp.detect_prompt(explanation, test)) return autointerp.detection_score(answer, test) except Exception as exc: unlabeled.append({"feature": feat["feature"], "error": f"detect: {exc}"}) return None real = await asyncio.gather(*[score(f, f["explanation"]) for f in labeled]) control = await asyncio.gather(*[score(f, e) for f, e in zip(labeled, shuffled)]) scored = [] for feat, s, c in zip(labeled, real, control): if s is None or c is None: continue feat.update(score=s, control=c) scored.append(feat) print(f" #{feat['feature']}: {s:.2f} (control {c:.2f}) {feat['explanation']}") if scored: print(f"layer {layer}: mean detection {sum(f['score'] for f in scored) / len(scored):.2f}, " f"mismatched control {sum(f['control'] for f in scored) / len(scored):.2f}") unlabeled = list({u["feature"]: u for u in unlabeled}.values()) # one entry per feature for u in unlabeled: print(f" #{u['feature']} unlabeled: {u['error']}") return json.dumps({"layer": layer, "width": width, "k": k, "features": scored, "unlabeled": unlabeled}) # {{/docs-fragment label}} # {{docs-fragment publish}} async def publish(best: Trained, stats: SAEStats, labeled: dict, run_name: str) -> File: card = await artifacts.Card.create_from.aio(content=reports.card(best, stats, labeled, run_name), format="html", card_type="model") scores = [f["score"] for f in labeled["features"]] metadata = artifacts.Metadata.create_model_metadata( name="pythia-70m-topk-sae", description=(f"TopK SAE on Pythia-70m-deduped layer {stats.layer}: {stats.width} features, k={stats.k}, " f"{stats.fve:.0%} variance explained, {stats.loss_recovered:.0%} loss recovered"), framework="PyTorch", model_type="TopK sparse autoencoder", architecture=f"d_model 512 -> {stats.width} -> 512, TopK k={stats.k}", task="interpretability", modality=("text",), serial_format="pt", card=card, attrs={"layer": str(stats.layer), "width": str(stats.width), "k": str(stats.k), "fve": f"{stats.fve:.4f}", "loss_recovered": f"{stats.loss_recovered:.4f}", "dead_frac": f"{stats.dead_frac:.4f}", "detection": f"{sum(scores) / len(scores):.3f}"}, ) return artifacts.new(best.weights[best.ks.index(stats.k)], metadata) # {{/docs-fragment publish}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def find_features( layers: list[int] = [1, 3, 5], widths: list[int] = [4096, 16384], ks: list[int] = [16, 32, 64], n_tokens: int = 8_000_000, steps: int = 8000, label_k: int = 32, label_width: int = 16384, features_per_sae: int = 40, ) -> File: """Harvest activations, train an SAE grid in parallel, label features with Claude, and publish the best SAE.""" if label_width not in widths: label_width = max(widths) started = time.time() await flyte.report.replace.aio(reports.page_start(layers, widths, ks, n_tokens), do_flush=True) harvest = await harvest_activations(layers=layers, n_tokens=n_tokens) trained: list[Trained] = await asyncio.gather(*[ train_sae(harvest, layer, width, ks, steps=steps, label_k=label_k, n_features=features_per_sae if width == label_width else 0) for layer in layers for width in widths ]) await flyte.report.replace.aio(reports.overview(trained, [], harvest, time.time() - started), do_flush=True) labeled = [json.loads(s) for s in await asyncio.gather(*[ label_features(t.layer, t.width, t.label_k, t.examples) for t in trained if t.examples is not None ])] await flyte.report.replace.aio(reports.overview(trained, labeled, harvest, time.time() - started)) flyte.report.get_tab("Feature browser").replace(reports.browser(labeled)) await flyte.report.flush.aio() # The SAE whose features Claude explained best, by mean detection score. mean = lambda lab: sum(f["score"] for f in lab["features"]) / len(lab["features"]) best_labels = max((lab for lab in labeled if lab["features"]), key=mean) best = next(t for t in trained if (t.layer, t.width) == (best_labels["layer"], best_labels["width"])) stats = next(s for s in best.stats if s.k == best_labels["k"]) return await publish(best, stats, best_labels, flyte.ctx().action.run_name) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--smoke", action="store_true", help="1 layer, 1 width, 0.5M tokens, 8 features") parser.add_argument("--widths", type=int, nargs="+", default=[4096, 16384]) args = parser.parse_args() flyte.init_from_config() if args.smoke: run = flyte.run(find_features, layers=[3], widths=[4096], n_tokens=500_000, steps=600, features_per_sae=8) else: run = flyte.run(find_features, widths=args.widths) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/sparse_autoencoders/find_features.py* `label_features` runs every explanation, then scores each one twice: once on its own feature's test set, and once with another feature's explanation. The second score is a control. A good explanation should beat a fluent but wrong one by a wide margin. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "find_features" # params = "layers=[3] widths=[4096] n_tokens=500000 steps=600 features_per_sae=8" # /// """Find interpretable features in a language model with sparse autoencoders, and label them with Claude. harvest_activations (GPU, cached) Pythia-70m over FineWeb: residual stream at several layers -> Dir per layer -> N x train_sae (GPU each) one (layer, width) per task: TopK SAEs at k = 16, 32, 64, then variance explained, L0, dead features, and loss with the SAE spliced in -> M x label_features (CPU) Claude explains sampled features and is scored on held-out contexts -> report (feature browser) -> publish the most interpretable SAE as an artifact The harvest is cached on its inputs. Re-running with another width, k, or step budget reuses the activations, and every (layer, width) that was already trained, and only trains what is new. python find_features.py # 3 layers x 2 widths, 8M tokens, about 30 minutes python find_features.py --smoke # 1 layer x 1 width, 0.5M tokens python find_features.py --widths 4096 16384 32768 # reuses the harvest and the first two widths """ import argparse import asyncio import json import os import tempfile import time from dataclasses import dataclass, field from pathlib import Path import autointerp import flyte import flyte.artifacts as artifacts import flyte.report import reports from flyte.io import Dir, File MODEL = "EleutherAI/pythia-70m-deduped" CLAUDE = "claude-opus-5-5" # The name of the secret that holds your Anthropic API key. Set ANTHROPIC_SECRET when you # launch to use a secret with another name. ANTHROPIC_SECRET = os.getenv("ANTHROPIC_SECRET", "anthropic-api-key") # Bump when sae.py changes (the SAE, its training, its metrics, or feature sampling). train_sae # salts its cache with this; cache="auto" alone hashes only the task's own body. SAE_VERSION = "topk-auxk/2" # Set SAE_DEVICE=cpu to run a tiny version on a laptop with flyte's local mode. DEVICE = os.getenv("SAE_DEVICE", "cuda") # {{docs-fragment envs}} image = flyte.Image.from_debian_base(name="sae-features").with_pip_packages( "torch==2.9.1", "transformers==4.57.3", "datasets==4.4.2", "numpy<3", "anthropic==2.6.0", ) # One GPU per task: the harvest, and every SAE trainer. sae.py is imported inside the tasks. gpu_env = flyte.TaskEnvironment( name="sae-gpu", image=image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L4:1", disk="80Gi"), cache="auto", include=["sae.py"], ) # Autointerp is API calls, so CPU only. Only this environment holds the API key. interp_env = flyte.TaskEnvironment( name="sae-autointerp", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), secrets=[flyte.Secret(key=ANTHROPIC_SECRET, as_env_var="ANTHROPIC_API_KEY")], cache="auto", ) driver_env = flyte.TaskEnvironment( name="sae-driver", image=image, resources=flyte.Resources(cpu=2, memory="8Gi"), # The driver declares label_features when it calls it, so it needs the same secret name. env_vars={"ANTHROPIC_SECRET": ANTHROPIC_SECRET}, depends_on=[gpu_env, interp_env], ) # {{/docs-fragment envs}} @dataclass class Harvest: model: str dataset: str layers: list[int] ctx_len: int d_model: int n_seqs: int acts: list[Dir] # one per layer: shard_*.npy, float16 [sequences, ctx_len, d_model] tokens: File # int32 [sequences, ctx_len] @dataclass class SAEStats: layer: int width: int k: int fve: float l0: float dead_frac: float ce_clean: float ce_sae: float ce_zero: float loss_recovered: float density_hist: dict = field(default_factory=dict) @dataclass class Trained: layer: int width: int ks: list[int] stats: list[SAEStats] weights: list[File] # one per k curve: list[dict] train_s: float examples: File | None = None # sampled features with their contexts, for the k that gets labeled label_k: int = 0 # {{docs-fragment harvest}} @gpu_env.task async def harvest_activations( layers: list[int], n_tokens: int = 8_000_000, ctx_len: int = 128, dataset: str = "HuggingFaceFW/fineweb:sample-10BT", shard_seqs: int = 4096, ) -> Harvest: """Run Pythia over FineWeb and save the residual stream after each layer in ``layers``. Each context is the first ``ctx_len`` tokens of one document. Activations are float16 shards, one directory per layer, so a trainer downloads only the layer it needs. """ import numpy as np import torch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL).to(DEVICE).eval() name, _, config = dataset.partition(":") stream = load_dataset(name, name=config or None, split="train", streaming=True) n_seqs = n_tokens // ctx_len rows: list[list[int]] = [] texts: list[str] = [] for doc in stream: texts.append(doc["text"]) if len(texts) == 1000: enc = tok(texts, truncation=True, max_length=ctx_len)["input_ids"] rows += [ids for ids in enc if len(ids) == ctx_len] texts = [] if len(rows) >= n_seqs: break tokens = np.array(rows[:n_seqs], dtype=np.int32) print(f"{len(tokens):,} contexts of {ctx_len} tokens from {dataset}") captured: dict[int, torch.Tensor] = {} for layer in layers: model.gpt_neox.layers[layer].register_forward_hook( lambda _m, _i, out, layer=layer: captured.__setitem__(layer, out[0] if isinstance(out, tuple) else out)) root = Path(tempfile.mkdtemp()) for layer in layers: (root / f"layer_{layer}").mkdir() d_model = model.config.hidden_size with torch.no_grad(): for shard, s in enumerate(range(0, len(tokens), shard_seqs)): chunk = tokens[s:s + shard_seqs] out = {layer: np.empty((len(chunk), ctx_len, d_model), dtype=np.float16) for layer in layers} for b in range(0, len(chunk), 256): model(input_ids=torch.as_tensor(chunk[b:b + 256], dtype=torch.long, device=DEVICE)) for layer in layers: out[layer][b:b + 256] = captured[layer].clamp(-6e4, 6e4).half().cpu().numpy() for layer in layers: np.save(root / f"layer_{layer}" / f"shard_{shard:03d}.npy", out[layer]) np.save(root / "tokens.npy", tokens) print(f"saved {len(layers)} layers x {len(tokens) * ctx_len:,} tokens") acts = await asyncio.gather(*[Dir.from_local(str(root / f"layer_{layer}")) for layer in layers]) return Harvest(model=MODEL, dataset=dataset, layers=layers, ctx_len=ctx_len, d_model=d_model, n_seqs=len(tokens), acts=list(acts), tokens=await File.from_local(str(root / "tokens.npy"))) # {{/docs-fragment harvest}} async def load_layer(harvest: Harvest, layer: int): """Download one layer's shards and put them on the GPU, with the token ids.""" import numpy as np import torch local = Path(await harvest.acts[harvest.layers.index(layer)].download()) shards = sorted(local.rglob("shard_*.npy")) acts = torch.cat([torch.from_numpy(np.load(p)).to(DEVICE) for p in shards]) tokens = np.load(await harvest.tokens.download()) return acts, tokens # {{docs-fragment train}} @gpu_env.task(report=True, cache=flyte.Cache("auto", salt=SAE_VERSION)) async def train_sae( harvest: Harvest, layer: int, width: int, ks: list[int], steps: int = 8000, batch_size: int = 4096, label_k: int = 32, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, held_out: float = 0.05, seed: int = 0, ) -> Trained: """Train one TopK SAE per k on one layer, evaluate each on held-out text, and sample features to label.""" import sae as S import torch from transformers import AutoModelForCausalLM, AutoTokenizer torch.backends.cuda.matmul.allow_tf32 = True acts, tokens = await load_layer(harvest, layer) n_train = int(len(acts) * (1 - held_out)) print(f"layer {layer}: {n_train:,} training and {len(acts) - n_train:,} held-out contexts, width {width}, k {ks}") started = time.time() curve_so_far: list[dict] = [] def on_log(point: dict) -> None: # stream the training curves into this task's report curve_so_far.append(point) flyte.report.replace(reports.training(layer, width, ks, steps, curve_so_far, time.time() - started)) flyte.report.flush() # Training runs in a worker thread, so the report can stream from the callback. saes, scale, curve = await asyncio.to_thread(S.train, acts[:n_train], width, ks, steps, batch_size, seed=seed, on_log=on_log) train_s = time.time() - started print(f"trained {len(ks)} SAEs for {steps} steps in {train_s / 60:.1f} min") # Evaluate on held-out contexts: reconstruction, sparsity, and what the model loses with the SAE in place. model = AutoModelForCausalLM.from_pretrained(harvest.model).to(DEVICE).eval() eval_tokens = torch.as_tensor(tokens[n_train:][:512], dtype=torch.long, device=DEVICE) ce = S.spliced_losses(model, eval_tokens, layer, saes, scale) stats = [] for sae in saes: m = S.reconstruction_metrics(sae, acts[n_train:], scale) st = SAEStats(layer=layer, width=width, k=sae.k, fve=m["fve"], l0=m["l0"], dead_frac=m["dead_frac"], ce_clean=ce["clean"], ce_sae=ce[f"k{sae.k}"], ce_zero=ce["zero"], loss_recovered=S.loss_recovered(ce["clean"], ce[f"k{sae.k}"], ce["zero"]), density_hist=S.density_histogram(m["density"])) print(f" k={sae.k}: FVE {st.fve:.3f}, L0 {st.l0:.1f}, dead {st.dead_frac:.1%}, " f"loss {st.ce_clean:.3f} -> {st.ce_sae:.3f} (zero {st.ce_zero:.3f}), recovered {st.loss_recovered:.1%}") stats.append(st) out = Path(tempfile.mkdtemp()) weights = [] for sae in saes: path = out / f"sae_L{layer}_w{width}_k{sae.k}.pt" torch.save({"state_dict": sae.state_dict(), "scale": scale, "layer": layer, "width": width, "k": sae.k, "d_model": sae.d_model, "model": harvest.model, "hook": f"gpt_neox.layers.{layer} output"}, path) weights.append(await File.from_local(str(path))) examples = None if n_features and label_k in ks: tok = AutoTokenizer.from_pretrained(harvest.model) feats = S.feature_examples(saes[ks.index(label_k)], acts, tokens, scale, lambda t: tok.decode([t]), n_features=n_features, n_top=n_top, n_sampled=n_sampled, seed=seed + layer) path = out / "examples.json" path.write_text(json.dumps(feats)) examples = await File.from_local(str(path)) print(f" sampled {len(feats)} features for autointerp") return Trained(layer=layer, width=width, ks=ks, stats=stats, weights=weights, curve=curve, train_s=round(train_s, 1), examples=examples, label_k=label_k if examples else 0) # {{/docs-fragment train}} # {{docs-fragment claude}} class Unanswered(Exception): """Claude gave no complete JSON answer: a refusal, or output cut off at max_tokens.""" async def ask_claude(system: str, prompt: str, schema: dict, max_tokens: int = 4096) -> str: import anthropic client = anthropic.AsyncAnthropic(max_retries=8) message = await client.messages.create( model=CLAUDE, max_tokens=max_tokens, system=system, output_config={"effort": "low", "format": {"type": "json_schema", "schema": schema}}, messages=[{"role": "user", "content": prompt}], ) # Any thinking counts toward max_tokens, so check that the answer finished before reading it. if message.stop_reason != "end_turn": raise Unanswered(f"stop_reason={message.stop_reason}") text = next((b.text for b in message.content if b.type == "text"), None) if text is None: raise Unanswered("no text block") return text @flyte.trace async def explain_feature(layer: int, feature: int, prompt: str) -> str: """Claude's explanation of one feature. Traced, so a retried task replays it instead of paying again.""" return await ask_claude(autointerp.EXPLAIN_SYSTEM, prompt, autointerp.EXPLAIN_SCHEMA) @flyte.trace async def detect_feature(layer: int, feature: int, prompt: str) -> str: """Claude's guess of which held-out excerpts the explanation predicts. Traced, like the explanation.""" return await ask_claude(autointerp.DETECT_SYSTEM, prompt, autointerp.DETECT_SCHEMA) # {{/docs-fragment claude}} # {{docs-fragment label}} @interp_env.task(retries=1, cache=flyte.Cache("auto", salt=autointerp.VERSION)) async def label_features(layer: int, width: int, k: int, examples: File, concurrency: int = 8) -> str: """Explain each sampled feature, then score every explanation on the feature's held-out contexts. Each feature is also scored with another feature's explanation. That control shows what the test gives an explanation that is fluent but wrong. A feature whose calls fail is recorded as unlabeled, so one bad answer never fails the whole task. """ with open(await examples.download()) as f: features = json.load(f) gate = asyncio.Semaphore(concurrency) unlabeled: list[dict] = [] async def explain(feat: dict) -> dict | None: try: async with gate: answer = json.loads(await explain_feature(layer, feat["feature"], autointerp.explain_prompt(feat))) return {**feat, **answer} except Exception as exc: # Unanswered, malformed JSON, or an API error that outlived the retries unlabeled.append({"feature": feat["feature"], "error": f"explain: {exc}"}) return None labeled = [f for f in await asyncio.gather(*[explain(f) for f in features]) if f is not None] shuffled = [labeled[(i + 1) % len(labeled)]["explanation"] for i in range(len(labeled))] async def score(feat: dict, explanation: str) -> float | None: test = autointerp.detect_set(feat, seed=feat["feature"]) try: async with gate: answer = await detect_feature(layer, feat["feature"], autointerp.detect_prompt(explanation, test)) return autointerp.detection_score(answer, test) except Exception as exc: unlabeled.append({"feature": feat["feature"], "error": f"detect: {exc}"}) return None real = await asyncio.gather(*[score(f, f["explanation"]) for f in labeled]) control = await asyncio.gather(*[score(f, e) for f, e in zip(labeled, shuffled)]) scored = [] for feat, s, c in zip(labeled, real, control): if s is None or c is None: continue feat.update(score=s, control=c) scored.append(feat) print(f" #{feat['feature']}: {s:.2f} (control {c:.2f}) {feat['explanation']}") if scored: print(f"layer {layer}: mean detection {sum(f['score'] for f in scored) / len(scored):.2f}, " f"mismatched control {sum(f['control'] for f in scored) / len(scored):.2f}") unlabeled = list({u["feature"]: u for u in unlabeled}.values()) # one entry per feature for u in unlabeled: print(f" #{u['feature']} unlabeled: {u['error']}") return json.dumps({"layer": layer, "width": width, "k": k, "features": scored, "unlabeled": unlabeled}) # {{/docs-fragment label}} # {{docs-fragment publish}} async def publish(best: Trained, stats: SAEStats, labeled: dict, run_name: str) -> File: card = await artifacts.Card.create_from.aio(content=reports.card(best, stats, labeled, run_name), format="html", card_type="model") scores = [f["score"] for f in labeled["features"]] metadata = artifacts.Metadata.create_model_metadata( name="pythia-70m-topk-sae", description=(f"TopK SAE on Pythia-70m-deduped layer {stats.layer}: {stats.width} features, k={stats.k}, " f"{stats.fve:.0%} variance explained, {stats.loss_recovered:.0%} loss recovered"), framework="PyTorch", model_type="TopK sparse autoencoder", architecture=f"d_model 512 -> {stats.width} -> 512, TopK k={stats.k}", task="interpretability", modality=("text",), serial_format="pt", card=card, attrs={"layer": str(stats.layer), "width": str(stats.width), "k": str(stats.k), "fve": f"{stats.fve:.4f}", "loss_recovered": f"{stats.loss_recovered:.4f}", "dead_frac": f"{stats.dead_frac:.4f}", "detection": f"{sum(scores) / len(scores):.3f}"}, ) return artifacts.new(best.weights[best.ks.index(stats.k)], metadata) # {{/docs-fragment publish}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def find_features( layers: list[int] = [1, 3, 5], widths: list[int] = [4096, 16384], ks: list[int] = [16, 32, 64], n_tokens: int = 8_000_000, steps: int = 8000, label_k: int = 32, label_width: int = 16384, features_per_sae: int = 40, ) -> File: """Harvest activations, train an SAE grid in parallel, label features with Claude, and publish the best SAE.""" if label_width not in widths: label_width = max(widths) started = time.time() await flyte.report.replace.aio(reports.page_start(layers, widths, ks, n_tokens), do_flush=True) harvest = await harvest_activations(layers=layers, n_tokens=n_tokens) trained: list[Trained] = await asyncio.gather(*[ train_sae(harvest, layer, width, ks, steps=steps, label_k=label_k, n_features=features_per_sae if width == label_width else 0) for layer in layers for width in widths ]) await flyte.report.replace.aio(reports.overview(trained, [], harvest, time.time() - started), do_flush=True) labeled = [json.loads(s) for s in await asyncio.gather(*[ label_features(t.layer, t.width, t.label_k, t.examples) for t in trained if t.examples is not None ])] await flyte.report.replace.aio(reports.overview(trained, labeled, harvest, time.time() - started)) flyte.report.get_tab("Feature browser").replace(reports.browser(labeled)) await flyte.report.flush.aio() # The SAE whose features Claude explained best, by mean detection score. mean = lambda lab: sum(f["score"] for f in lab["features"]) / len(lab["features"]) best_labels = max((lab for lab in labeled if lab["features"]), key=mean) best = next(t for t in trained if (t.layer, t.width) == (best_labels["layer"], best_labels["width"])) stats = next(s for s in best.stats if s.k == best_labels["k"]) return await publish(best, stats, best_labels, flyte.ctx().action.run_name) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--smoke", action="store_true", help="1 layer, 1 width, 0.5M tokens, 8 features") parser.add_argument("--widths", type=int, nargs="+", default=[4096, 16384]) args = parser.parse_args() flyte.init_from_config() if args.smoke: run = flyte.run(find_features, layers=[3], widths=[4096], n_tokens=500_000, steps=600, features_per_sae=8) else: run = flyte.run(find_features, widths=args.widths) print(run.url) # {{/docs-fragment run}} CODE7 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "find_features" # params = "layers=[3] widths=[4096] n_tokens=500000 steps=600 features_per_sae=8" # /// """Find interpretable features in a language model with sparse autoencoders, and label them with Claude. harvest_activations (GPU, cached) Pythia-70m over FineWeb: residual stream at several layers -> Dir per layer -> N x train_sae (GPU each) one (layer, width) per task: TopK SAEs at k = 16, 32, 64, then variance explained, L0, dead features, and loss with the SAE spliced in -> M x label_features (CPU) Claude explains sampled features and is scored on held-out contexts -> report (feature browser) -> publish the most interpretable SAE as an artifact The harvest is cached on its inputs. Re-running with another width, k, or step budget reuses the activations, and every (layer, width) that was already trained, and only trains what is new. python find_features.py # 3 layers x 2 widths, 8M tokens, about 30 minutes python find_features.py --smoke # 1 layer x 1 width, 0.5M tokens python find_features.py --widths 4096 16384 32768 # reuses the harvest and the first two widths """ import argparse import asyncio import json import os import tempfile import time from dataclasses import dataclass, field from pathlib import Path import autointerp import flyte import flyte.artifacts as artifacts import flyte.report import reports from flyte.io import Dir, File MODEL = "EleutherAI/pythia-70m-deduped" CLAUDE = "claude-opus-5-5" # The name of the secret that holds your Anthropic API key. Set ANTHROPIC_SECRET when you # launch to use a secret with another name. ANTHROPIC_SECRET = os.getenv("ANTHROPIC_SECRET", "anthropic-api-key") # Bump when sae.py changes (the SAE, its training, its metrics, or feature sampling). train_sae # salts its cache with this; cache="auto" alone hashes only the task's own body. SAE_VERSION = "topk-auxk/2" # Set SAE_DEVICE=cpu to run a tiny version on a laptop with flyte's local mode. DEVICE = os.getenv("SAE_DEVICE", "cuda") # {{docs-fragment envs}} image = flyte.Image.from_debian_base(name="sae-features").with_pip_packages( "torch==2.9.1", "transformers==4.57.3", "datasets==4.4.2", "numpy<3", "anthropic==2.6.0", ) # One GPU per task: the harvest, and every SAE trainer. sae.py is imported inside the tasks. gpu_env = flyte.TaskEnvironment( name="sae-gpu", image=image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L4:1", disk="80Gi"), cache="auto", include=["sae.py"], ) # Autointerp is API calls, so CPU only. Only this environment holds the API key. interp_env = flyte.TaskEnvironment( name="sae-autointerp", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), secrets=[flyte.Secret(key=ANTHROPIC_SECRET, as_env_var="ANTHROPIC_API_KEY")], cache="auto", ) driver_env = flyte.TaskEnvironment( name="sae-driver", image=image, resources=flyte.Resources(cpu=2, memory="8Gi"), # The driver declares label_features when it calls it, so it needs the same secret name. env_vars={"ANTHROPIC_SECRET": ANTHROPIC_SECRET}, depends_on=[gpu_env, interp_env], ) # {{/docs-fragment envs}} @dataclass class Harvest: model: str dataset: str layers: list[int] ctx_len: int d_model: int n_seqs: int acts: list[Dir] # one per layer: shard_*.npy, float16 [sequences, ctx_len, d_model] tokens: File # int32 [sequences, ctx_len] @dataclass class SAEStats: layer: int width: int k: int fve: float l0: float dead_frac: float ce_clean: float ce_sae: float ce_zero: float loss_recovered: float density_hist: dict = field(default_factory=dict) @dataclass class Trained: layer: int width: int ks: list[int] stats: list[SAEStats] weights: list[File] # one per k curve: list[dict] train_s: float examples: File | None = None # sampled features with their contexts, for the k that gets labeled label_k: int = 0 # {{docs-fragment harvest}} @gpu_env.task async def harvest_activations( layers: list[int], n_tokens: int = 8_000_000, ctx_len: int = 128, dataset: str = "HuggingFaceFW/fineweb:sample-10BT", shard_seqs: int = 4096, ) -> Harvest: """Run Pythia over FineWeb and save the residual stream after each layer in ``layers``. Each context is the first ``ctx_len`` tokens of one document. Activations are float16 shards, one directory per layer, so a trainer downloads only the layer it needs. """ import numpy as np import torch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL).to(DEVICE).eval() name, _, config = dataset.partition(":") stream = load_dataset(name, name=config or None, split="train", streaming=True) n_seqs = n_tokens // ctx_len rows: list[list[int]] = [] texts: list[str] = [] for doc in stream: texts.append(doc["text"]) if len(texts) == 1000: enc = tok(texts, truncation=True, max_length=ctx_len)["input_ids"] rows += [ids for ids in enc if len(ids) == ctx_len] texts = [] if len(rows) >= n_seqs: break tokens = np.array(rows[:n_seqs], dtype=np.int32) print(f"{len(tokens):,} contexts of {ctx_len} tokens from {dataset}") captured: dict[int, torch.Tensor] = {} for layer in layers: model.gpt_neox.layers[layer].register_forward_hook( lambda _m, _i, out, layer=layer: captured.__setitem__(layer, out[0] if isinstance(out, tuple) else out)) root = Path(tempfile.mkdtemp()) for layer in layers: (root / f"layer_{layer}").mkdir() d_model = model.config.hidden_size with torch.no_grad(): for shard, s in enumerate(range(0, len(tokens), shard_seqs)): chunk = tokens[s:s + shard_seqs] out = {layer: np.empty((len(chunk), ctx_len, d_model), dtype=np.float16) for layer in layers} for b in range(0, len(chunk), 256): model(input_ids=torch.as_tensor(chunk[b:b + 256], dtype=torch.long, device=DEVICE)) for layer in layers: out[layer][b:b + 256] = captured[layer].clamp(-6e4, 6e4).half().cpu().numpy() for layer in layers: np.save(root / f"layer_{layer}" / f"shard_{shard:03d}.npy", out[layer]) np.save(root / "tokens.npy", tokens) print(f"saved {len(layers)} layers x {len(tokens) * ctx_len:,} tokens") acts = await asyncio.gather(*[Dir.from_local(str(root / f"layer_{layer}")) for layer in layers]) return Harvest(model=MODEL, dataset=dataset, layers=layers, ctx_len=ctx_len, d_model=d_model, n_seqs=len(tokens), acts=list(acts), tokens=await File.from_local(str(root / "tokens.npy"))) # {{/docs-fragment harvest}} async def load_layer(harvest: Harvest, layer: int): """Download one layer's shards and put them on the GPU, with the token ids.""" import numpy as np import torch local = Path(await harvest.acts[harvest.layers.index(layer)].download()) shards = sorted(local.rglob("shard_*.npy")) acts = torch.cat([torch.from_numpy(np.load(p)).to(DEVICE) for p in shards]) tokens = np.load(await harvest.tokens.download()) return acts, tokens # {{docs-fragment train}} @gpu_env.task(report=True, cache=flyte.Cache("auto", salt=SAE_VERSION)) async def train_sae( harvest: Harvest, layer: int, width: int, ks: list[int], steps: int = 8000, batch_size: int = 4096, label_k: int = 32, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, held_out: float = 0.05, seed: int = 0, ) -> Trained: """Train one TopK SAE per k on one layer, evaluate each on held-out text, and sample features to label.""" import sae as S import torch from transformers import AutoModelForCausalLM, AutoTokenizer torch.backends.cuda.matmul.allow_tf32 = True acts, tokens = await load_layer(harvest, layer) n_train = int(len(acts) * (1 - held_out)) print(f"layer {layer}: {n_train:,} training and {len(acts) - n_train:,} held-out contexts, width {width}, k {ks}") started = time.time() curve_so_far: list[dict] = [] def on_log(point: dict) -> None: # stream the training curves into this task's report curve_so_far.append(point) flyte.report.replace(reports.training(layer, width, ks, steps, curve_so_far, time.time() - started)) flyte.report.flush() # Training runs in a worker thread, so the report can stream from the callback. saes, scale, curve = await asyncio.to_thread(S.train, acts[:n_train], width, ks, steps, batch_size, seed=seed, on_log=on_log) train_s = time.time() - started print(f"trained {len(ks)} SAEs for {steps} steps in {train_s / 60:.1f} min") # Evaluate on held-out contexts: reconstruction, sparsity, and what the model loses with the SAE in place. model = AutoModelForCausalLM.from_pretrained(harvest.model).to(DEVICE).eval() eval_tokens = torch.as_tensor(tokens[n_train:][:512], dtype=torch.long, device=DEVICE) ce = S.spliced_losses(model, eval_tokens, layer, saes, scale) stats = [] for sae in saes: m = S.reconstruction_metrics(sae, acts[n_train:], scale) st = SAEStats(layer=layer, width=width, k=sae.k, fve=m["fve"], l0=m["l0"], dead_frac=m["dead_frac"], ce_clean=ce["clean"], ce_sae=ce[f"k{sae.k}"], ce_zero=ce["zero"], loss_recovered=S.loss_recovered(ce["clean"], ce[f"k{sae.k}"], ce["zero"]), density_hist=S.density_histogram(m["density"])) print(f" k={sae.k}: FVE {st.fve:.3f}, L0 {st.l0:.1f}, dead {st.dead_frac:.1%}, " f"loss {st.ce_clean:.3f} -> {st.ce_sae:.3f} (zero {st.ce_zero:.3f}), recovered {st.loss_recovered:.1%}") stats.append(st) out = Path(tempfile.mkdtemp()) weights = [] for sae in saes: path = out / f"sae_L{layer}_w{width}_k{sae.k}.pt" torch.save({"state_dict": sae.state_dict(), "scale": scale, "layer": layer, "width": width, "k": sae.k, "d_model": sae.d_model, "model": harvest.model, "hook": f"gpt_neox.layers.{layer} output"}, path) weights.append(await File.from_local(str(path))) examples = None if n_features and label_k in ks: tok = AutoTokenizer.from_pretrained(harvest.model) feats = S.feature_examples(saes[ks.index(label_k)], acts, tokens, scale, lambda t: tok.decode([t]), n_features=n_features, n_top=n_top, n_sampled=n_sampled, seed=seed + layer) path = out / "examples.json" path.write_text(json.dumps(feats)) examples = await File.from_local(str(path)) print(f" sampled {len(feats)} features for autointerp") return Trained(layer=layer, width=width, ks=ks, stats=stats, weights=weights, curve=curve, train_s=round(train_s, 1), examples=examples, label_k=label_k if examples else 0) # {{/docs-fragment train}} # {{docs-fragment claude}} class Unanswered(Exception): """Claude gave no complete JSON answer: a refusal, or output cut off at max_tokens.""" async def ask_claude(system: str, prompt: str, schema: dict, max_tokens: int = 4096) -> str: import anthropic client = anthropic.AsyncAnthropic(max_retries=8) message = await client.messages.create( model=CLAUDE, max_tokens=max_tokens, system=system, output_config={"effort": "low", "format": {"type": "json_schema", "schema": schema}}, messages=[{"role": "user", "content": prompt}], ) # Any thinking counts toward max_tokens, so check that the answer finished before reading it. if message.stop_reason != "end_turn": raise Unanswered(f"stop_reason={message.stop_reason}") text = next((b.text for b in message.content if b.type == "text"), None) if text is None: raise Unanswered("no text block") return text @flyte.trace async def explain_feature(layer: int, feature: int, prompt: str) -> str: """Claude's explanation of one feature. Traced, so a retried task replays it instead of paying again.""" return await ask_claude(autointerp.EXPLAIN_SYSTEM, prompt, autointerp.EXPLAIN_SCHEMA) @flyte.trace async def detect_feature(layer: int, feature: int, prompt: str) -> str: """Claude's guess of which held-out excerpts the explanation predicts. Traced, like the explanation.""" return await ask_claude(autointerp.DETECT_SYSTEM, prompt, autointerp.DETECT_SCHEMA) # {{/docs-fragment claude}} # {{docs-fragment label}} @interp_env.task(retries=1, cache=flyte.Cache("auto", salt=autointerp.VERSION)) async def label_features(layer: int, width: int, k: int, examples: File, concurrency: int = 8) -> str: """Explain each sampled feature, then score every explanation on the feature's held-out contexts. Each feature is also scored with another feature's explanation. That control shows what the test gives an explanation that is fluent but wrong. A feature whose calls fail is recorded as unlabeled, so one bad answer never fails the whole task. """ with open(await examples.download()) as f: features = json.load(f) gate = asyncio.Semaphore(concurrency) unlabeled: list[dict] = [] async def explain(feat: dict) -> dict | None: try: async with gate: answer = json.loads(await explain_feature(layer, feat["feature"], autointerp.explain_prompt(feat))) return {**feat, **answer} except Exception as exc: # Unanswered, malformed JSON, or an API error that outlived the retries unlabeled.append({"feature": feat["feature"], "error": f"explain: {exc}"}) return None labeled = [f for f in await asyncio.gather(*[explain(f) for f in features]) if f is not None] shuffled = [labeled[(i + 1) % len(labeled)]["explanation"] for i in range(len(labeled))] async def score(feat: dict, explanation: str) -> float | None: test = autointerp.detect_set(feat, seed=feat["feature"]) try: async with gate: answer = await detect_feature(layer, feat["feature"], autointerp.detect_prompt(explanation, test)) return autointerp.detection_score(answer, test) except Exception as exc: unlabeled.append({"feature": feat["feature"], "error": f"detect: {exc}"}) return None real = await asyncio.gather(*[score(f, f["explanation"]) for f in labeled]) control = await asyncio.gather(*[score(f, e) for f, e in zip(labeled, shuffled)]) scored = [] for feat, s, c in zip(labeled, real, control): if s is None or c is None: continue feat.update(score=s, control=c) scored.append(feat) print(f" #{feat['feature']}: {s:.2f} (control {c:.2f}) {feat['explanation']}") if scored: print(f"layer {layer}: mean detection {sum(f['score'] for f in scored) / len(scored):.2f}, " f"mismatched control {sum(f['control'] for f in scored) / len(scored):.2f}") unlabeled = list({u["feature"]: u for u in unlabeled}.values()) # one entry per feature for u in unlabeled: print(f" #{u['feature']} unlabeled: {u['error']}") return json.dumps({"layer": layer, "width": width, "k": k, "features": scored, "unlabeled": unlabeled}) # {{/docs-fragment label}} # {{docs-fragment publish}} async def publish(best: Trained, stats: SAEStats, labeled: dict, run_name: str) -> File: card = await artifacts.Card.create_from.aio(content=reports.card(best, stats, labeled, run_name), format="html", card_type="model") scores = [f["score"] for f in labeled["features"]] metadata = artifacts.Metadata.create_model_metadata( name="pythia-70m-topk-sae", description=(f"TopK SAE on Pythia-70m-deduped layer {stats.layer}: {stats.width} features, k={stats.k}, " f"{stats.fve:.0%} variance explained, {stats.loss_recovered:.0%} loss recovered"), framework="PyTorch", model_type="TopK sparse autoencoder", architecture=f"d_model 512 -> {stats.width} -> 512, TopK k={stats.k}", task="interpretability", modality=("text",), serial_format="pt", card=card, attrs={"layer": str(stats.layer), "width": str(stats.width), "k": str(stats.k), "fve": f"{stats.fve:.4f}", "loss_recovered": f"{stats.loss_recovered:.4f}", "dead_frac": f"{stats.dead_frac:.4f}", "detection": f"{sum(scores) / len(scores):.3f}"}, ) return artifacts.new(best.weights[best.ks.index(stats.k)], metadata) # {{/docs-fragment publish}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def find_features( layers: list[int] = [1, 3, 5], widths: list[int] = [4096, 16384], ks: list[int] = [16, 32, 64], n_tokens: int = 8_000_000, steps: int = 8000, label_k: int = 32, label_width: int = 16384, features_per_sae: int = 40, ) -> File: """Harvest activations, train an SAE grid in parallel, label features with Claude, and publish the best SAE.""" if label_width not in widths: label_width = max(widths) started = time.time() await flyte.report.replace.aio(reports.page_start(layers, widths, ks, n_tokens), do_flush=True) harvest = await harvest_activations(layers=layers, n_tokens=n_tokens) trained: list[Trained] = await asyncio.gather(*[ train_sae(harvest, layer, width, ks, steps=steps, label_k=label_k, n_features=features_per_sae if width == label_width else 0) for layer in layers for width in widths ]) await flyte.report.replace.aio(reports.overview(trained, [], harvest, time.time() - started), do_flush=True) labeled = [json.loads(s) for s in await asyncio.gather(*[ label_features(t.layer, t.width, t.label_k, t.examples) for t in trained if t.examples is not None ])] await flyte.report.replace.aio(reports.overview(trained, labeled, harvest, time.time() - started)) flyte.report.get_tab("Feature browser").replace(reports.browser(labeled)) await flyte.report.flush.aio() # The SAE whose features Claude explained best, by mean detection score. mean = lambda lab: sum(f["score"] for f in lab["features"]) / len(lab["features"]) best_labels = max((lab for lab in labeled if lab["features"]), key=mean) best = next(t for t in trained if (t.layer, t.width) == (best_labels["layer"], best_labels["width"])) stats = next(s for s in best.stats if s.k == best_labels["k"]) return await publish(best, stats, best_labels, flyte.ctx().action.run_name) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--smoke", action="store_true", help="1 layer, 1 width, 0.5M tokens, 8 features") parser.add_argument("--widths", type=int, nargs="+", default=[4096, 16384]) args = parser.parse_args() flyte.init_from_config() if args.smoke: run = flyte.run(find_features, layers=[3], widths=[4096], n_tokens=500_000, steps=600, features_per_sae=8) else: run = flyte.run(find_features, widths=args.widths) print(run.url) # {{/docs-fragment run}} CODE8 """Reports for the SAE run: training curves, the metrics overview, the feature browser, and the card.""" import html import viz SCORE_GOOD, SCORE_OK = 0.85, 0.7 def _pct(v: float, digits: int = 0) -> str: return f"{100 * v:.{digits}f}%" def _score(s: float) -> str: s = round(s, 2) kind = "good" if s >= SCORE_GOOD else "warning" if s >= SCORE_OK else "critical" return viz.status(kind, f"{s:.2f}") def page_start(layers: list[int], widths: list[int], ks: list[int], n_tokens: int) -> str: return viz.page( "Sparse autoencoders on Pythia-70m", f"Harvesting {viz.compact(n_tokens)} tokens of residual stream at layers {', '.join(map(str, layers))}, " f"then training {len(layers) * len(widths)} GPU tasks of TopK SAEs (widths {', '.join(map(str, widths))}, " f"k = {', '.join(map(str, ks))}). Each trainer's live curves are in its own report.", ) # {{docs-fragment training}} def training(layer: int, width: int, ks: list[int], steps: int, curve: list[dict], elapsed: float) -> str: """The live report of one trainer: normalized MSE and dead fraction for every k.""" xs = [p["step"] for p in curve] last = curve[-1] return viz.page( f"Training TopK SAEs: layer {layer}, {width:,} features", f"One SAE per k on the same batches. Step {last['step']:,} of {steps:,}, {elapsed / 60:.1f} min.", viz.tiles([(f"Normalized MSE, k={k}", f"{last[f'k{k}']:.3f}", f"dead {_pct(last[f'dead_k{k}'], 1)}") for k in ks]), viz.row( viz.panel("Normalized MSE (lower is better)", viz.line_chart( [viz.Series(f"k={k}", [p[f"k{k}"] for p in curve], i + 1, xs=xs) for i, k in enumerate(ks)], width=420, height=200, x_label="step", y_fmt=lambda v: f"{v:.2f}")), viz.panel("Dead features (no firing in the last 1M tokens)", viz.line_chart( [viz.Series(f"k={k}", [p[f"dead_k{k}"] for p in curve], i + 1, xs=xs) for i, k in enumerate(ks)], width=420, height=200, x_label="step", y_fmt=lambda v: _pct(v, 1))), ), ) # {{/docs-fragment training}} def _metrics_table(trained: list) -> str: rows = [] for t in sorted(trained, key=lambda t: (t.layer, t.width)): for s in t.stats: rows.append([ f"{s.layer}", f"{s.width:,}", s.k, f"{s.fve:.3f}", f"{s.l0:.1f}", _pct(s.dead_frac, 1), f"{s.ce_clean:.3f}", f"{s.ce_sae:.3f}", f"{s.ce_zero:.2f}", f"{_pct(s.loss_recovered, 1)}", ]) return viz.table(["layer", "width", "k", "variance explained", "L0", "dead", "loss clean", "loss with SAE", "loss zero-ablated", "loss recovered"], rows) def _frontier(trained: list, key: str, label: str, fmt) -> str: series = [] for i, t in enumerate(sorted(trained, key=lambda t: (t.layer, t.width))): pts = sorted(t.stats, key=lambda s: s.l0) series.append(viz.Series(f"L{t.layer} ยท {t.width:,}", [getattr(s, key) for s in pts], i + 1, xs=[s.l0 for s in pts])) return viz.panel(label, viz.line_chart(series, width=440, height=230, x_label="L0", y_fmt=fmt, x_fmt=lambda v: f"{v:.0f}")) def _density(trained: list, k: int) -> str: """The classic feature-density histogram: how often each feature fires, on a log scale.""" panels = [] for t in sorted(trained, key=lambda t: (t.layer, t.width)): s = next((s for s in t.stats if s.k == k), t.stats[0]) h = s.density_hist cats = ["dead"] + [f"{e:g}" for e in h["edges"][:-1]] vals = [h["dead"]] + h["counts"] panels.append(viz.panel(f"Layer {t.layer}, {t.width:,} features, k={s.k}", viz.stacked_columns( cats, [viz.Series("features", vals, 1)], width=420, height=170), "x: log10 of the share of tokens a feature fires on; the first column is dead features.")) return viz.row(*panels) def _autointerp_table(labeled: list[dict]) -> str: rows = [] for lab in sorted(labeled, key=lambda x: x["layer"]): sc = [f["score"] for f in lab["features"]] ct = [f["control"] for f in lab["features"]] n = max(len(sc), 1) rows.append([f"{lab['layer']}", f"{lab['width']:,}", lab["k"], len(sc), len(lab.get("unlabeled", [])), _score(sum(sc) / n) if sc else "โ€”", f"{sum(ct) / n:.2f}" if ct else "โ€”", f"{sum(s >= SCORE_GOOD for s in sc)} of {len(sc)}"]) return viz.table(["layer", "width", "k", "features labeled", "unlabeled", "detection score", "mismatched explanation", f"score โ‰ฅ {SCORE_GOOD}"], rows) # {{docs-fragment overview}} def overview(trained: list, labeled: list[dict], harvest, elapsed: float) -> str: best = max((s for t in trained for s in t.stats), key=lambda s: s.loss_recovered) scores = [f["score"] for lab in labeled for f in lab["features"]] controls = [f["control"] for lab in labeled for f in lab["features"]] label_k = next((lab["k"] for lab in labeled), trained[0].ks[len(trained[0].ks) // 2]) tiles = viz.tiles([ ("Best loss recovered", _pct(best.loss_recovered, 1), f"layer {best.layer}, {best.width:,} features, k={best.k}"), ("SAEs trained", str(sum(len(t.stats) for t in trained)), f"{len(trained)} GPU tasks"), ("Features labeled by Claude", str(len(scores)) if scores else "pending"), ("Mean detection score", f"{sum(scores) / len(scores):.2f}" if scores else "pending", f"mismatched explanations: {sum(controls) / len(controls):.2f}; chance: 0.50" if controls else ""), ("Wall clock", f"{elapsed / 60:.0f} min"), ], hero=True) blocks = [ tiles, viz.panel("Every SAE on held-out text", _metrics_table(trained), "Variance explained and L0 on held-out tokens. Loss recovered = (zero-ablated โˆ’ with SAE) / " "(zero-ablated โˆ’ clean), from next-token loss with the layer's output replaced."), viz.row( _frontier(trained, "fve", "Sparsity vs reconstruction: variance explained", lambda v: f"{v:.2f}"), _frontier(trained, "loss_recovered", "Sparsity vs downstream loss: loss recovered", lambda v: _pct(v)), ), ] if labeled: blocks.append(viz.panel("Autointerp: can Claude predict where a feature fires from its explanation?", _autointerp_table(labeled), "Balanced accuracy on held-out contexts, half activating and half not. " "The control scores each feature with another feature's explanation. " "Open the Feature browser tab for every feature.")) blocks.append(_density(trained, label_k)) blocks.append(viz.panel("Data", viz.table(["model", "dataset", "contexts", "tokens", "layers"], [[ f"{viz.esc(harvest.model)}", f"{viz.esc(harvest.dataset)}", f"{harvest.n_seqs:,}", viz.compact(harvest.n_seqs * harvest.ctx_len), ", ".join(map(str, harvest.layers))]]))) return viz.page("Sparse autoencoders on Pythia-70m", "TopK SAEs on the residual stream, one GPU task per (layer, width), features labeled and " "scored by Claude.", *blocks) # {{/docs-fragment overview}} # โ”€โ”€ feature browser โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ BROWSER_STYLE = """ """ def _token(t: str, a: float, peak: float) -> str: text = html.escape(t.replace("\n", "โ†ต")) if a <= 0: return text pct = max(12, round(85 * a / peak)) return (f"{text}") def context_html(ex: dict, peak: float) -> str: return "
" + "".join(_token(t, a, peak) for t, a in zip(ex["tokens"], ex["acts"])) + "
" def _hist(h: dict, width: int = 190, height: int = 60) -> str: counts = h["counts"] top = max(counts) or 1 bw = width / len(counts) bars = "".join( f"{h['edges'][i]:.2f}โ€“{h['edges'][i + 1]:.2f}: " f"{c:,} tokens" for i, c in enumerate(counts)) axis = (f"0" f"{h['edges'][-1]:.1f}") return f"{bars}{axis}" def feature_html(f: dict, layer: int, width: int, k: int, n_contexts: int = 10) -> str: peak = f["max_act"] ctxs = "".join(context_html(ex, peak) for ex in f["top"][:n_contexts]) more = "".join(context_html(ex, peak) for ex in f["top"][n_contexts:] + f.get("sampled", [])) held = "".join(context_html(ex, peak) for ex in f["test"] if ex["active"]) return ( "
" f"{viz.esc(f['explanation'])}" f"detection {_score(f['score'])} ยท mismatched {f['control']:.2f}" f"layer {layer} ยท {width:,} features ยท k={k} ยท feature #{f['feature']}" f"fires on {_pct(f['density'], 2)} of tokens, {_pct(f['context_rate'], 1)} of contexts" "
" f"

{viz.esc(f['notes'])}

" f"
{ctxs}" + (f"
{len(f['top']) - n_contexts} more top contexts, then a random sample of the rest{more}
" if more else "") + (f"
held-out contexts where it fires (from the detection test){held}
" if held else "") + f"
activation histogram (nonzero)
{_hist(f['hist'])}
" ) # {{docs-fragment browser}} def browser(labeled: list[dict]) -> str: """Every labeled feature, most convincing first: highest detection score, then the widest margin over the control.""" feats = [(f, lab) for lab in labeled for f in lab["features"]] feats.sort(key=lambda p: (-p[0]["score"], -(p[0]["score"] - p[0]["control"]), -p[0]["context_rate"])) good = sum(f["score"] >= SCORE_GOOD for f, _ in feats) return viz.page( "Feature browser", f"{len(feats)} features sampled at random from the live features of each SAE, sorted by how well Claude's " f"explanation predicts held-out contexts. {good} score at least {SCORE_GOOD}. Highlight strength is the " "feature's activation; hover a token for its value.", BROWSER_STYLE, "".join(feature_html(f, lab["layer"], lab["width"], lab["k"]) for f, lab in feats), ) # {{/docs-fragment browser}} def card(best, stats, labeled: dict, run_name: str) -> str: feats = sorted(labeled["features"], key=lambda f: -f["score"]) scores = [f["score"] for f in feats] return viz.card( f"TopK SAE: Pythia-70m-deduped, layer {stats.layer}", f"Trained in run {viz.esc(run_name)} on the residual stream after layer {stats.layer}. " f"{stats.width:,} features, k={stats.k}.", ["PyTorch", "TopK SAE", "Pythia-70m-deduped", f"layer {stats.layer}", f"{stats.width:,} features", ".pt"], BROWSER_STYLE, viz.tiles([ ("Loss recovered", _pct(stats.loss_recovered, 1), f"loss {stats.ce_clean:.3f} โ†’ {stats.ce_sae:.3f}"), ("Variance explained", f"{stats.fve:.3f}", f"L0 {stats.l0:.0f}"), ("Dead features", _pct(stats.dead_frac, 1), "on held-out tokens"), ("Detection score", f"{sum(scores) / len(scores):.2f}", f"{len(scores)} features labeled by Claude"), ], hero=True), viz.panel("Its five most interpretable sampled features", "".join(feature_html(f, stats.layer, stats.width, stats.k, n_contexts=4) for f in feats[:5])), viz.panel("Load it", viz.code( "import torch\n" "from flyte.io import File\n" "from flyte.remote import Artifact\n" 'sae_file = Artifact.get("pythia-70m-topk-sae").to_python(File)\n' "ckpt = torch.load(sae_file.download_sync())\n" '# {"state_dict", "scale", "layer", "width", "k", "hook"}: TopKSAE in sae.py; multiply\n' "# activations by scale before encoding and divide reconstructions by it after.")), ) CODE9 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "find_features" # params = "layers=[3] widths=[4096] n_tokens=500000 steps=600 features_per_sae=8" # /// """Find interpretable features in a language model with sparse autoencoders, and label them with Claude. harvest_activations (GPU, cached) Pythia-70m over FineWeb: residual stream at several layers -> Dir per layer -> N x train_sae (GPU each) one (layer, width) per task: TopK SAEs at k = 16, 32, 64, then variance explained, L0, dead features, and loss with the SAE spliced in -> M x label_features (CPU) Claude explains sampled features and is scored on held-out contexts -> report (feature browser) -> publish the most interpretable SAE as an artifact The harvest is cached on its inputs. Re-running with another width, k, or step budget reuses the activations, and every (layer, width) that was already trained, and only trains what is new. python find_features.py # 3 layers x 2 widths, 8M tokens, about 30 minutes python find_features.py --smoke # 1 layer x 1 width, 0.5M tokens python find_features.py --widths 4096 16384 32768 # reuses the harvest and the first two widths """ import argparse import asyncio import json import os import tempfile import time from dataclasses import dataclass, field from pathlib import Path import autointerp import flyte import flyte.artifacts as artifacts import flyte.report import reports from flyte.io import Dir, File MODEL = "EleutherAI/pythia-70m-deduped" CLAUDE = "claude-opus-5-5" # The name of the secret that holds your Anthropic API key. Set ANTHROPIC_SECRET when you # launch to use a secret with another name. ANTHROPIC_SECRET = os.getenv("ANTHROPIC_SECRET", "anthropic-api-key") # Bump when sae.py changes (the SAE, its training, its metrics, or feature sampling). train_sae # salts its cache with this; cache="auto" alone hashes only the task's own body. SAE_VERSION = "topk-auxk/2" # Set SAE_DEVICE=cpu to run a tiny version on a laptop with flyte's local mode. DEVICE = os.getenv("SAE_DEVICE", "cuda") # {{docs-fragment envs}} image = flyte.Image.from_debian_base(name="sae-features").with_pip_packages( "torch==2.9.1", "transformers==4.57.3", "datasets==4.4.2", "numpy<3", "anthropic==2.6.0", ) # One GPU per task: the harvest, and every SAE trainer. sae.py is imported inside the tasks. gpu_env = flyte.TaskEnvironment( name="sae-gpu", image=image, resources=flyte.Resources(cpu=6, memory="40Gi", gpu="L4:1", disk="80Gi"), cache="auto", include=["sae.py"], ) # Autointerp is API calls, so CPU only. Only this environment holds the API key. interp_env = flyte.TaskEnvironment( name="sae-autointerp", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), secrets=[flyte.Secret(key=ANTHROPIC_SECRET, as_env_var="ANTHROPIC_API_KEY")], cache="auto", ) driver_env = flyte.TaskEnvironment( name="sae-driver", image=image, resources=flyte.Resources(cpu=2, memory="8Gi"), # The driver declares label_features when it calls it, so it needs the same secret name. env_vars={"ANTHROPIC_SECRET": ANTHROPIC_SECRET}, depends_on=[gpu_env, interp_env], ) # {{/docs-fragment envs}} @dataclass class Harvest: model: str dataset: str layers: list[int] ctx_len: int d_model: int n_seqs: int acts: list[Dir] # one per layer: shard_*.npy, float16 [sequences, ctx_len, d_model] tokens: File # int32 [sequences, ctx_len] @dataclass class SAEStats: layer: int width: int k: int fve: float l0: float dead_frac: float ce_clean: float ce_sae: float ce_zero: float loss_recovered: float density_hist: dict = field(default_factory=dict) @dataclass class Trained: layer: int width: int ks: list[int] stats: list[SAEStats] weights: list[File] # one per k curve: list[dict] train_s: float examples: File | None = None # sampled features with their contexts, for the k that gets labeled label_k: int = 0 # {{docs-fragment harvest}} @gpu_env.task async def harvest_activations( layers: list[int], n_tokens: int = 8_000_000, ctx_len: int = 128, dataset: str = "HuggingFaceFW/fineweb:sample-10BT", shard_seqs: int = 4096, ) -> Harvest: """Run Pythia over FineWeb and save the residual stream after each layer in ``layers``. Each context is the first ``ctx_len`` tokens of one document. Activations are float16 shards, one directory per layer, so a trainer downloads only the layer it needs. """ import numpy as np import torch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL).to(DEVICE).eval() name, _, config = dataset.partition(":") stream = load_dataset(name, name=config or None, split="train", streaming=True) n_seqs = n_tokens // ctx_len rows: list[list[int]] = [] texts: list[str] = [] for doc in stream: texts.append(doc["text"]) if len(texts) == 1000: enc = tok(texts, truncation=True, max_length=ctx_len)["input_ids"] rows += [ids for ids in enc if len(ids) == ctx_len] texts = [] if len(rows) >= n_seqs: break tokens = np.array(rows[:n_seqs], dtype=np.int32) print(f"{len(tokens):,} contexts of {ctx_len} tokens from {dataset}") captured: dict[int, torch.Tensor] = {} for layer in layers: model.gpt_neox.layers[layer].register_forward_hook( lambda _m, _i, out, layer=layer: captured.__setitem__(layer, out[0] if isinstance(out, tuple) else out)) root = Path(tempfile.mkdtemp()) for layer in layers: (root / f"layer_{layer}").mkdir() d_model = model.config.hidden_size with torch.no_grad(): for shard, s in enumerate(range(0, len(tokens), shard_seqs)): chunk = tokens[s:s + shard_seqs] out = {layer: np.empty((len(chunk), ctx_len, d_model), dtype=np.float16) for layer in layers} for b in range(0, len(chunk), 256): model(input_ids=torch.as_tensor(chunk[b:b + 256], dtype=torch.long, device=DEVICE)) for layer in layers: out[layer][b:b + 256] = captured[layer].clamp(-6e4, 6e4).half().cpu().numpy() for layer in layers: np.save(root / f"layer_{layer}" / f"shard_{shard:03d}.npy", out[layer]) np.save(root / "tokens.npy", tokens) print(f"saved {len(layers)} layers x {len(tokens) * ctx_len:,} tokens") acts = await asyncio.gather(*[Dir.from_local(str(root / f"layer_{layer}")) for layer in layers]) return Harvest(model=MODEL, dataset=dataset, layers=layers, ctx_len=ctx_len, d_model=d_model, n_seqs=len(tokens), acts=list(acts), tokens=await File.from_local(str(root / "tokens.npy"))) # {{/docs-fragment harvest}} async def load_layer(harvest: Harvest, layer: int): """Download one layer's shards and put them on the GPU, with the token ids.""" import numpy as np import torch local = Path(await harvest.acts[harvest.layers.index(layer)].download()) shards = sorted(local.rglob("shard_*.npy")) acts = torch.cat([torch.from_numpy(np.load(p)).to(DEVICE) for p in shards]) tokens = np.load(await harvest.tokens.download()) return acts, tokens # {{docs-fragment train}} @gpu_env.task(report=True, cache=flyte.Cache("auto", salt=SAE_VERSION)) async def train_sae( harvest: Harvest, layer: int, width: int, ks: list[int], steps: int = 8000, batch_size: int = 4096, label_k: int = 32, n_features: int = 40, n_top: int = 12, n_sampled: int = 8, held_out: float = 0.05, seed: int = 0, ) -> Trained: """Train one TopK SAE per k on one layer, evaluate each on held-out text, and sample features to label.""" import sae as S import torch from transformers import AutoModelForCausalLM, AutoTokenizer torch.backends.cuda.matmul.allow_tf32 = True acts, tokens = await load_layer(harvest, layer) n_train = int(len(acts) * (1 - held_out)) print(f"layer {layer}: {n_train:,} training and {len(acts) - n_train:,} held-out contexts, width {width}, k {ks}") started = time.time() curve_so_far: list[dict] = [] def on_log(point: dict) -> None: # stream the training curves into this task's report curve_so_far.append(point) flyte.report.replace(reports.training(layer, width, ks, steps, curve_so_far, time.time() - started)) flyte.report.flush() # Training runs in a worker thread, so the report can stream from the callback. saes, scale, curve = await asyncio.to_thread(S.train, acts[:n_train], width, ks, steps, batch_size, seed=seed, on_log=on_log) train_s = time.time() - started print(f"trained {len(ks)} SAEs for {steps} steps in {train_s / 60:.1f} min") # Evaluate on held-out contexts: reconstruction, sparsity, and what the model loses with the SAE in place. model = AutoModelForCausalLM.from_pretrained(harvest.model).to(DEVICE).eval() eval_tokens = torch.as_tensor(tokens[n_train:][:512], dtype=torch.long, device=DEVICE) ce = S.spliced_losses(model, eval_tokens, layer, saes, scale) stats = [] for sae in saes: m = S.reconstruction_metrics(sae, acts[n_train:], scale) st = SAEStats(layer=layer, width=width, k=sae.k, fve=m["fve"], l0=m["l0"], dead_frac=m["dead_frac"], ce_clean=ce["clean"], ce_sae=ce[f"k{sae.k}"], ce_zero=ce["zero"], loss_recovered=S.loss_recovered(ce["clean"], ce[f"k{sae.k}"], ce["zero"]), density_hist=S.density_histogram(m["density"])) print(f" k={sae.k}: FVE {st.fve:.3f}, L0 {st.l0:.1f}, dead {st.dead_frac:.1%}, " f"loss {st.ce_clean:.3f} -> {st.ce_sae:.3f} (zero {st.ce_zero:.3f}), recovered {st.loss_recovered:.1%}") stats.append(st) out = Path(tempfile.mkdtemp()) weights = [] for sae in saes: path = out / f"sae_L{layer}_w{width}_k{sae.k}.pt" torch.save({"state_dict": sae.state_dict(), "scale": scale, "layer": layer, "width": width, "k": sae.k, "d_model": sae.d_model, "model": harvest.model, "hook": f"gpt_neox.layers.{layer} output"}, path) weights.append(await File.from_local(str(path))) examples = None if n_features and label_k in ks: tok = AutoTokenizer.from_pretrained(harvest.model) feats = S.feature_examples(saes[ks.index(label_k)], acts, tokens, scale, lambda t: tok.decode([t]), n_features=n_features, n_top=n_top, n_sampled=n_sampled, seed=seed + layer) path = out / "examples.json" path.write_text(json.dumps(feats)) examples = await File.from_local(str(path)) print(f" sampled {len(feats)} features for autointerp") return Trained(layer=layer, width=width, ks=ks, stats=stats, weights=weights, curve=curve, train_s=round(train_s, 1), examples=examples, label_k=label_k if examples else 0) # {{/docs-fragment train}} # {{docs-fragment claude}} class Unanswered(Exception): """Claude gave no complete JSON answer: a refusal, or output cut off at max_tokens.""" async def ask_claude(system: str, prompt: str, schema: dict, max_tokens: int = 4096) -> str: import anthropic client = anthropic.AsyncAnthropic(max_retries=8) message = await client.messages.create( model=CLAUDE, max_tokens=max_tokens, system=system, output_config={"effort": "low", "format": {"type": "json_schema", "schema": schema}}, messages=[{"role": "user", "content": prompt}], ) # Any thinking counts toward max_tokens, so check that the answer finished before reading it. if message.stop_reason != "end_turn": raise Unanswered(f"stop_reason={message.stop_reason}") text = next((b.text for b in message.content if b.type == "text"), None) if text is None: raise Unanswered("no text block") return text @flyte.trace async def explain_feature(layer: int, feature: int, prompt: str) -> str: """Claude's explanation of one feature. Traced, so a retried task replays it instead of paying again.""" return await ask_claude(autointerp.EXPLAIN_SYSTEM, prompt, autointerp.EXPLAIN_SCHEMA) @flyte.trace async def detect_feature(layer: int, feature: int, prompt: str) -> str: """Claude's guess of which held-out excerpts the explanation predicts. Traced, like the explanation.""" return await ask_claude(autointerp.DETECT_SYSTEM, prompt, autointerp.DETECT_SCHEMA) # {{/docs-fragment claude}} # {{docs-fragment label}} @interp_env.task(retries=1, cache=flyte.Cache("auto", salt=autointerp.VERSION)) async def label_features(layer: int, width: int, k: int, examples: File, concurrency: int = 8) -> str: """Explain each sampled feature, then score every explanation on the feature's held-out contexts. Each feature is also scored with another feature's explanation. That control shows what the test gives an explanation that is fluent but wrong. A feature whose calls fail is recorded as unlabeled, so one bad answer never fails the whole task. """ with open(await examples.download()) as f: features = json.load(f) gate = asyncio.Semaphore(concurrency) unlabeled: list[dict] = [] async def explain(feat: dict) -> dict | None: try: async with gate: answer = json.loads(await explain_feature(layer, feat["feature"], autointerp.explain_prompt(feat))) return {**feat, **answer} except Exception as exc: # Unanswered, malformed JSON, or an API error that outlived the retries unlabeled.append({"feature": feat["feature"], "error": f"explain: {exc}"}) return None labeled = [f for f in await asyncio.gather(*[explain(f) for f in features]) if f is not None] shuffled = [labeled[(i + 1) % len(labeled)]["explanation"] for i in range(len(labeled))] async def score(feat: dict, explanation: str) -> float | None: test = autointerp.detect_set(feat, seed=feat["feature"]) try: async with gate: answer = await detect_feature(layer, feat["feature"], autointerp.detect_prompt(explanation, test)) return autointerp.detection_score(answer, test) except Exception as exc: unlabeled.append({"feature": feat["feature"], "error": f"detect: {exc}"}) return None real = await asyncio.gather(*[score(f, f["explanation"]) for f in labeled]) control = await asyncio.gather(*[score(f, e) for f, e in zip(labeled, shuffled)]) scored = [] for feat, s, c in zip(labeled, real, control): if s is None or c is None: continue feat.update(score=s, control=c) scored.append(feat) print(f" #{feat['feature']}: {s:.2f} (control {c:.2f}) {feat['explanation']}") if scored: print(f"layer {layer}: mean detection {sum(f['score'] for f in scored) / len(scored):.2f}, " f"mismatched control {sum(f['control'] for f in scored) / len(scored):.2f}") unlabeled = list({u["feature"]: u for u in unlabeled}.values()) # one entry per feature for u in unlabeled: print(f" #{u['feature']} unlabeled: {u['error']}") return json.dumps({"layer": layer, "width": width, "k": k, "features": scored, "unlabeled": unlabeled}) # {{/docs-fragment label}} # {{docs-fragment publish}} async def publish(best: Trained, stats: SAEStats, labeled: dict, run_name: str) -> File: card = await artifacts.Card.create_from.aio(content=reports.card(best, stats, labeled, run_name), format="html", card_type="model") scores = [f["score"] for f in labeled["features"]] metadata = artifacts.Metadata.create_model_metadata( name="pythia-70m-topk-sae", description=(f"TopK SAE on Pythia-70m-deduped layer {stats.layer}: {stats.width} features, k={stats.k}, " f"{stats.fve:.0%} variance explained, {stats.loss_recovered:.0%} loss recovered"), framework="PyTorch", model_type="TopK sparse autoencoder", architecture=f"d_model 512 -> {stats.width} -> 512, TopK k={stats.k}", task="interpretability", modality=("text",), serial_format="pt", card=card, attrs={"layer": str(stats.layer), "width": str(stats.width), "k": str(stats.k), "fve": f"{stats.fve:.4f}", "loss_recovered": f"{stats.loss_recovered:.4f}", "dead_frac": f"{stats.dead_frac:.4f}", "detection": f"{sum(scores) / len(scores):.3f}"}, ) return artifacts.new(best.weights[best.ks.index(stats.k)], metadata) # {{/docs-fragment publish}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True) async def find_features( layers: list[int] = [1, 3, 5], widths: list[int] = [4096, 16384], ks: list[int] = [16, 32, 64], n_tokens: int = 8_000_000, steps: int = 8000, label_k: int = 32, label_width: int = 16384, features_per_sae: int = 40, ) -> File: """Harvest activations, train an SAE grid in parallel, label features with Claude, and publish the best SAE.""" if label_width not in widths: label_width = max(widths) started = time.time() await flyte.report.replace.aio(reports.page_start(layers, widths, ks, n_tokens), do_flush=True) harvest = await harvest_activations(layers=layers, n_tokens=n_tokens) trained: list[Trained] = await asyncio.gather(*[ train_sae(harvest, layer, width, ks, steps=steps, label_k=label_k, n_features=features_per_sae if width == label_width else 0) for layer in layers for width in widths ]) await flyte.report.replace.aio(reports.overview(trained, [], harvest, time.time() - started), do_flush=True) labeled = [json.loads(s) for s in await asyncio.gather(*[ label_features(t.layer, t.width, t.label_k, t.examples) for t in trained if t.examples is not None ])] await flyte.report.replace.aio(reports.overview(trained, labeled, harvest, time.time() - started)) flyte.report.get_tab("Feature browser").replace(reports.browser(labeled)) await flyte.report.flush.aio() # The SAE whose features Claude explained best, by mean detection score. mean = lambda lab: sum(f["score"] for f in lab["features"]) / len(lab["features"]) best_labels = max((lab for lab in labeled if lab["features"]), key=mean) best = next(t for t in trained if (t.layer, t.width) == (best_labels["layer"], best_labels["width"])) stats = next(s for s in best.stats if s.k == best_labels["k"]) return await publish(best, stats, best_labels, flyte.ctx().action.run_name) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--smoke", action="store_true", help="1 layer, 1 width, 0.5M tokens, 8 features") parser.add_argument("--widths", type=int, nargs="+", default=[4096, 16384]) args = parser.parse_args() flyte.init_from_config() if args.smoke: run = flyte.run(find_features, layers=[3], widths=[4096], n_tokens=500_000, steps=600, features_per_sae=8) else: run = flyte.run(find_features, widths=args.widths) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/sparse_autoencoders/find_features.py* ## Results A run with the defaults trains 18 SAEs (3 layers, 2 widths, 3 values of k) on 8 million tokens of FineWeb. An earlier run of the same harvest and training code took 18 minutes from an empty cache: 3 minutes for the harvest, 3 to 6 minutes for each 4,096-feature trainer, 11 to 14 minutes for each 16,384-feature trainer, all six running at once, and about a minute for the 360 Claude calls of autointerp. The numbers and screenshots below are from a run of the code as published here, which reused that cached harvest, retrained every SAE, and took 16 minutes. ![The run's overview: loss recovered, SAEs trained, features labeled, mean detection score, and the metrics of every SAE](../../../_static/images/tutorials/sparse-autoencoders/sae-metrics.png) Every SAE recovers most of the model's loss. With the 16,384-feature SAE at k = 32 spliced in: | Layer | Variance explained | Dead features | Loss clean | Loss with SAE | Loss zero-ablated | Loss recovered | | --- | --- | --- | --- | --- | --- | --- | | 1 | 0.878 | 0.0% | 4.163 | 4.298 | 8.66 | 97.0% | | 3 | 0.957 | 0.1% | 4.163 | 4.411 | 9.43 | 95.3% | | 5 | 0.885 | 0.0% | 4.163 | 4.476 | 8.72 | 93.1% | The sparsity plots show the trade-off the SAE literature reports. More active features per token (a larger k) reconstruct better, and so do more features in the dictionary at the same k. Later layers are harder: at layer 5, even the best SAE loses 5% of the loss. Variance explained alone would rank the layers differently, since layer 3 has the highest variance explained and only the middle loss recovered. That is why the evaluation splices the SAE into the model. Almost no feature is dead: the AuxK loss keeps them alive. ![Variance explained and loss recovered against L0 for every SAE, and the autointerp scores per layer](../../../_static/images/tutorials/sparse-autoencoders/sae-frontier.png) Claude explained 40 features from each layer's 16,384-feature SAE, 120 in all, sampled at random among those that fire in at least 56 contexts: | Layer | Mean detection score | Mismatched explanation | Features scoring 0.85 or more | | --- | --- | --- | --- | | 1 | 0.77 | 0.50 | 15 of 40 | | 3 | 0.70 | 0.50 | 9 of 40 | | 5 | 0.72 | 0.53 | 13 of 40 | The mean is 0.73 over all 120, against 0.51 for the control, and every call returned a finished answer, so no feature was left unlabeled. The control stays at chance, so the score measures the explanation, not the test. The 12 features that score 1.0 are the ones a reader believes at a glance: the word "iPhone", the plural "systems", "covered", "billion" and "trillion" in money amounts, "use" as a noun, sentence-initial "These", and "especially" after a comma adding a condition. Close behind, at 0.94, are "Learn" opening a call to action, "out of" and the phrase after it, and closing quotation marks. In this sample, layer 1 has more single-word features, which are easy to predict, and the later layers have more features about syntax and position, which are harder to explain in a sentence. The ones at the bottom of the browser are mostly fragments of split words and diffuse features that fire on function words, which is also what the papers find. ![The feature browser: features sorted by detection score, with Claude's explanation and the activating tokens highlighted](../../../_static/images/tutorials/sparse-autoencoders/feature-browser.png) The SAE whose features scored best, layer 1 with 16,384 features at k = 32, is published as the `pythia-70m-topk-sae` artifact, with a card that shows its metrics and its five most interpretable sampled features. ### What the first run taught us The first full run showed Claude only each feature's 20 strongest contexts, and the mean detection score was 0.64. The explanations read well, but they failed the test. One feature's 20 strongest contexts were all the word "iPhone", and Claude's explanation, the word "iPhone", scored 0.62. Its held-out contexts showed why: at a third of its peak, the same feature fires on "Angela", "Explorer", and other names. The strongest contexts were not the whole feature. Showing Claude 12 top contexts and 8 sampled from the rest of its clear firings, as [Paulo et al.](https://arxiv.org/abs/2410.13928) recommend, raised the mean score to 0.72 on the same SAEs. Only the sample that Claude explained changed. The iPhone feature's new explanation also named a weaker meaning, and scored 1.0. A review then made every excerpt the same length, so that length could not hint at the answer, and the final run above scored 0.73. ## Add a width without redoing the rest Every task is cached, so a run that changes one input only redoes the work that depends on it. Add a third width: CODE10 We ran this demo before the last changes to the autointerp code and the cache salts, so the numbers in this section come from that earlier run; the SAE training code was the same, and its 4,096 and 16,384-feature SAEs matched the ones above to every digit. In that run, the harvest and the six existing trainers came back from the cache in under a second each, and so did the three autointerp tasks, since their inputs had not changed. Only the three 32,768-feature trainers ran, about 25 minutes each on one L4. The driver still writes a fresh report with all 27 SAEs in it. The new width was not worth it at this data size: | Layer | Loss recovered, 16,384 features | Loss recovered, 32,768 features | | --- | --- | --- | | 1 | 97.0% | 97.3% | | 3 | 95.3% | 95.2% | | 5 | 93.1% | 92.8% | All at k = 32. Doubling the dictionary bought almost nothing here. Two things likely contribute. The data is small: the scaling laws in Gao et al. call for more tokens as the width grows, and 8 million tokens may be too few for 32,768 features. And the training budget did not grow with the width: every trainer runs the same 8,000 steps, while the learning rate shrinks as one over the square root of the width, so the wider SAE also takes smaller steps for the same time. This run does not separate the two. A larger harvest (a change to `n_tokens`, which makes a new cached harvest) and a longer schedule for the wide SAEs are the next experiments. ## At real scale - **The harvest is the dataset.** Gemma Scope trained on 4 to 16 billion tokens per SAE. At that size the activations do not fit on one disk, and most teams either stream them from object storage in shards, as this tutorial does at small scale, or recompute them on the fly next to the trainer. The cached `Dir` keeps the first option cheap to repeat. - **The grid is the experiment.** Gemma Scope released more than 400 SAEs: every layer, several widths, several sparsities. Each is an independent GPU job reading the same harvest, which is the shape of `train_sae`. - **Autointerp is the long tail.** Labeling every feature of a 16-million-feature SAE is many millions of LLM calls. Tracing the calls makes the labeling job restartable without paying twice, and the detection score lets you sort and filter features without reading them. ## Related - **Tasks > Configure tasks > Caching** - **Tasks > Build tasks > Traces** - **Tasks > Build tasks > Files and directories** - **Tasks > Build tasks > Reports** - **Artifacts > Publish your own artifacts** === PAGE: https://www.union.ai/docs/v2/union/tutorials/frontier-ai/closed-loop-discovery === An active learning loop where a surrogate model proposes molecules, a quantum chemistry oracle measures them on a warm CPU pool, and a scientist approves each batch before it runs. # Closed-loop molecular discovery > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/closed_loop_discovery). AI-for-science labs no longer screen a library once and stop. They run a loop: a model proposes candidates, a simulation or a robotic lab measures the most promising ones, the measurements retrain the model, and the next batch is better. [Lila Sciences](https://www.lila.ai/news/scaling-autonomous-science-to-build-scientific-superintelligence) builds whole "AI Science Factories" around this loop. [A-Lab](https://www.nature.com/articles/s41586-023-06734-w) ran it for 17 days on inorganic materials, with robots doing the synthesis. EvolutionaryScale's [esmGFP](https://www.evolutionaryscale.ai/blog/esm3) came out of a model that generated thousands of candidate proteins, of which a small fraction were made and tested in the lab. And for molecules, [pool-based active learning](https://pubs.rsc.org/en/content/articlelanding/2021/sc/d0sc06805e) finds most of the top hits of a virtual screen after measuring a few percent of the library. The loop is simple to describe and awkward to run. The measurement is the expensive part, so it has to fan out over many machines and must never be paid for twice. Measurements fail: a calculation does not converge, a robot drops a plate. The loop runs for hours or days, so a crash in round 7 should not throw away rounds 1 to 6. And a person usually signs off on what goes to the lab, because lab time is the scarce resource, which means the loop has to stop and wait for an answer without stalling when nobody is around. This tutorial runs the loop on Union at a scale that finishes in under an hour. By the end you will have: - a pool of 20,000 drug-like molecules from ZINC250k, and an *oracle* that computes each one's HOMO-LUMO gap with GFN2-xTB, a semi-empirical quantum chemistry method; - a surrogate model with uncertainty, an ensemble of MLPs on molecular fingerprints, retrained every round, and an acquisition function that picks a diverse batch of 64; - a human approval step before every batch, with a timeout so an unattended run keeps going; - a random search with the same oracle budget, run alongside, so you can see what the model is worth; - the best molecules published as a dataset artifact with a card. ## The task The objective is to find the molecules with the smallest HOMO-LUMO gap, the energy between the highest occupied and lowest unoccupied molecular orbitals. A small gap is a first screen for organic semiconductors and dyes. Small gaps are rare in a drug-like library: the median molecule in the pool has a gap near 3 eV, and fewer than 1 molecule in 100 has a gap below 1 eV. The oracle is real compute, not a table lookup. For each molecule it embeds 8 3D conformers with RDKit, relaxes them with a force field, optimizes the best 3 with GFN2-xTB, and reads the orbital energies of the lowest-energy structure. That takes a few seconds per molecule and can fail in several ways, which is what makes it a fair stand-in for a lab. ```mermaid flowchart LR P["build_pool
20,000 molecules"] --> D["discover
driver"] D --> R["run_round
cached per round"] R --> S["propose
MLP ensemble, warm CPU"] S --> G{"approve-round-N
condition"} G -- "approved or
timed out" --> M1["measure
GFN2-xTB"] G --> M2["measure"] G --> M3["... 128 per round"] M1 & M2 & M3 --> R D --> A["artifact:
top candidates"] classDef human fill:#e8790033,stroke:#e87900,stroke-width:1.5px classDef cpu fill:#94a3b826,stroke:#94a3b8,stroke-width:1px class G human class P,D,R,S,M1,M2,M3,A cpu ``` ## What Union adds | Need | Construct | | --- | --- | | Measure 128 molecules a round without a pod per molecule | A reusable environment, `flyte.ReusePolicy(replicas=(2, 12))` | | Never measure a molecule twice, in this run or any later one | `flyte.Cache("auto", salt=ORACLE_VERSION)` on the per-molecule `measure` task | | Keep the surrogate's imports and data warm between rounds | A one-replica reusable environment for `propose` | | Let a scientist approve each batch | `flyte.new_condition`, with a timeout that auto-approves | | Resume a crashed loop from the last finished round | Each round is a cached task whose output is the whole loop state | | See the loop's progress while it runs | A live report, with tabs for the surrogate, the batches, and the oracle | | Keep the result | `flyte.artifacts` with a dataset card | ## Getting started You need a Union cluster. The pool is downloaded from a public URL inside the run, and every package comes from PyPI. ```bash git clone https://github.com/unionai/unionai-examples cd unionai-examples/v2/tutorials/closed_loop_discovery python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules, about 6 minutes ``` The 45 minutes assume someone approves each batch within a few seconds of it being proposed. Each round waits up to 3 minutes (`approval_timeout_s=180`) for an answer, so an unattended run adds about 30 minutes of waiting. To run without the gate, launch with `approval_timeout_s=0`: ```python flyte.run(discover, approval_timeout_s=0) ``` To approve a batch from Python, look the condition up by its name: ```python import flyte from flyte.remote import Condition flyte.init_from_config() Condition.get("approve-round-3", run_name="").signal(True) ``` From the CLI, a condition is signaled by its action name, a generated ID. `flyte get condition` lists the conditions of a run with their action names: ```bash flyte get condition flyte signal condition true ``` ## The image and environments One image serves every task: RDKit for molecules, `tblite` and ASE for GFN2-xTB, scikit-learn for the surrogate, and `unionai-reuse`, which reusable environments need. The oracle runs on a pool of 2-CPU replicas that grows to 12 while a round is in flight. Each call measures one molecule, so a slow molecule holds up one slot, not a batch. The surrogate gets a single warm replica with 4 CPUs. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "discover" # params = "rounds=2 batch_size=16 pool_size=2000" # /// """Closed-loop molecular discovery: a surrogate proposes, a quantum chemistry oracle measures. build_pool 20,000 drug-like molecules from ZINC250k, with fingerprints round 0: measure 64 random molecules, shared by both arms for each round: propose (warm CPU) retrain an MLP ensemble, pick 64 by a confidence bound approval (condition) a scientist approves the batch, or it auto-approves on timeout N x measure (CPU pool) GFN2-xTB HOMO-LUMO gap, cached per molecule and 64 random molecules through the same oracle, as the control arm report best gap found against oracle calls, and publish the top molecules as a dataset The objective is to find molecules with a small HOMO-LUMO gap, a cheap proxy for organic semiconductors and dyes. The oracle is real compute that can fail: conformer embedding, a GFN2-xTB geometry optimization, and a single point. Each round is a cached task whose output is the whole loop state, so a driver that crashes resumes from the last finished round, and a molecule measured once is never computed again, in this run or the next. python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules """ import asyncio import random import sys import tempfile import time from dataclasses import dataclass, field, replace import flyte import flyte.artifacts as artifacts import flyte.errors import flyte.report import reports from flyte.io import File from oracle import ORACLE_VERSION, Measurement from surrogate import SURROGATE_VERSION def round_s(x: float) -> float: return round(x, 1) ZINC_URL = ( "https://raw.githubusercontent.com/aspuru-guzik-group/chemical_vae/master/" "models/zinc_properties/250k_rndm_zinc_drugs_clean_3.csv" ) # {{docs-fragment envs}} # RDKit for molecules (its drawing code needs the X rendering libraries), tblite and ASE for # GFN2-xTB, scikit-learn for the surrogate, and unionai-reuse for the reusable environments. image = ( flyte.Image.from_debian_base(name="closed-loop-discovery", python_version=(3, 12)) .with_apt_packages("libxrender1", "libxext6", "libexpat1") .with_pip_packages("rdkit==2026.9.1", "tblite==0.8.0", "ase==3.29.0", "scikit-learn==1.9.1", "numpy==2.5.4", "unionai-reuse==0.2.1") ) CODE = ["oracle.py", "surrogate.py", "reports.py", "viz.py"] # The oracle: a warm pool of small CPU pods, one molecule per call. Every call is cached on # its SMILES string, so a molecule is measured once, ever, whichever arm or run asks for it. # "auto" caching hashes the task's own source, not the modules it imports, so the tasks that # use oracle.py and surrogate.py add those modules' versions to their cache keys (see below). oracle_env = flyte.TaskEnvironment( name="discovery-oracle", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), reusable=flyte.ReusePolicy(replicas=(2, 12), concurrency=1, idle_ttl=600, scaledown_ttl=120), env_vars={"OMP_NUM_THREADS": "2", "OMP_STACKSIZE": "1G"}, include=CODE, ) # The surrogate retrains every round on a single warm replica, which keeps its imports and # the downloaded pool between rounds. model_env = flyte.TaskEnvironment( name="discovery-model", image=image, resources=flyte.Resources(cpu=4, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=900), include=CODE, ) driver_env = flyte.TaskEnvironment( name="discovery-driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), include=CODE, depends_on=[oracle_env, model_env], ) # {{/docs-fragment envs}} # {{docs-fragment state}} @dataclass class Pick: smiles: str mean: float # predicted gap, eV std: float # ensemble spread, eV score: float # the acquisition score, mean - beta * std @dataclass class Proposal: round: int batch: list[Pick] # the active learning batch control: list[Pick] # the random control batch, with the same model's predictions train_size: int pool_median: float # median predicted gap over the whole pool fit_seconds: float @dataclass class RoundLog: round: int decision: str # "seed library", "approved", "rejected", "auto-approved", "no gate" gate_seconds: float = 0.0 proposal: Proposal | None = None active: list[Measurement] = field(default_factory=list) control: list[Measurement] = field(default_factory=list) seconds: float = 0.0 @dataclass class LoopState: rounds: list[RoundLog] = field(default_factory=list) vetoed: list[str] = field(default_factory=list) # molecules a scientist rejected def measured(self, arm: str) -> list[Measurement]: """Every measurement of one arm ("active" or "control") so far.""" return [m for r in self.rounds for m in getattr(r, arm)] # {{/docs-fragment state}} # {{docs-fragment pool}} @model_env.task(cache="auto") async def build_pool(pool_size: int = 20_000, seed: int = 0) -> File: """A random sample of neutral ZINC250k molecules, with their Morgan fingerprints.""" import csv import io import urllib.request import numpy as np from rdkit import Chem, RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize from surrogate import fingerprints RDLogger.DisableLog("rdApp.*") text = urllib.request.urlopen(ZINC_URL, timeout=120).read().decode() rows = [r["smiles"].strip() for r in csv.DictReader(io.StringIO(text))] random.Random(seed).shuffle(rows) # Gas-phase GFN2-xTB gives zwitterions and ions unphysically small gaps, so the pool keeps # neutral molecules only: neutralize what can be, and drop charged atoms other than nitro groups. uncharger, nitro = rdMolStandardize.Uncharger(), Chem.MolFromSmarts("[N+](=O)[O-]") pool, seen = [], set() for s in rows: mol = Chem.MolFromSmiles(s) if mol is None: continue mol = uncharger.uncharge(mol) charged = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) if Chem.GetFormalCharge(mol) != 0 or charged > 2 * len(mol.GetSubstructMatches(nitro)): continue smiles = Chem.MolToSmiles(mol) if smiles not in seen: seen.add(smiles) pool.append(smiles) if len(pool) == pool_size: break path = f"{tempfile.mkdtemp()}/pool.npz" np.savez_compressed(path, smiles=np.array(pool), fps=fingerprints(pool)) print(f"pool: {len(pool)} molecules from {len(rows)} in ZINC250k") return await File.from_local(path) # {{/docs-fragment pool}} async def load_pool(pool: File): import numpy as np data = np.load(await pool.download()) return [str(s) for s in data["smiles"]], data["fps"] # {{docs-fragment measure}} @oracle_env.task(cache=flyte.Cache("auto", salt=ORACLE_VERSION), retries=2) async def measure(smiles: str) -> Measurement: """Measure one molecule's HOMO-LUMO gap with GFN2-xTB. A failed calculation is a result, not an error.""" from oracle import measure_gap m = await asyncio.to_thread(measure_gap, smiles) m.measured_in = flyte.ctx().action.run_name or "" print(f"{smiles}: {'%.3f eV' % m.gap if m.ok else 'FAILED'} after {m.attempts} attempt(s) in {m.seconds:.1f}s {m.error}") return m # {{/docs-fragment measure}} # {{docs-fragment propose}} @model_env.task(cache=flyte.Cache("auto", salt=SURROGATE_VERSION)) async def propose( round_num: int, pool: File, train_smiles: list[str], train_gaps: list[float], exclude: list[str], control: list[str], batch_size: int, beta: float = 1.0, max_similarity: float = 0.6, ) -> Proposal: """Retrain the ensemble on everything measured so far and pick the next batch by a lower confidence bound.""" import numpy as np import surrogate started = time.time() smiles, packed = await load_pool(pool) index = {s: i for i, s in enumerate(smiles)} X = surrogate.unpack(packed) models = surrogate.fit_ensemble(X[[index[s] for s in train_smiles]], np.array(train_gaps), seed=round_num) mean, std = surrogate.predict(models, X) score = mean - beta * std # small predicted gap, or high uncertainty chosen = surrogate.select_batch(score, packed, {index[s] for s in exclude}, batch_size, max_similarity) def pick(i: int) -> Pick: return Pick(smiles[i], float(mean[i]), float(std[i]), float(score[i])) print(f"round {round_num}: trained on {len(train_smiles)}, batch predicted {mean[chosen].mean():.2f} eV") return Proposal(round_num, [pick(i) for i in chosen], [pick(index[s]) for s in control], len(train_smiles), float(np.median(mean)), round_s(time.time() - started)) # {{/docs-fragment propose}} # {{docs-fragment approval}} async def approval(round_num: int, proposal: Proposal, state: LoopState, timeout_s: int) -> tuple[str, float]: """Ask a scientist to approve the batch before it goes to the lab. Silence counts as approval.""" if timeout_s <= 0: return "no gate", 0.0 started = time.time() condition = await flyte.new_condition.aio( f"approve-round-{round_num}", prompt=reports.approval_prompt(proposal, state, timeout_s), prompt_type="markdown", data_type=bool, description=f"Send round {round_num}'s {len(proposal.batch)} molecules to the oracle?", timeout=timeout_s, ) try: approved = await condition.wait.aio() decision = "approved" if approved else "rejected" except flyte.errors.ConditionTimedoutError: decision = "auto-approved" # nobody answered: an unattended run keeps going return decision, round_s(time.time() - started) # {{/docs-fragment approval}} # {{docs-fragment round}} @driver_env.task(cache=flyte.Cache("auto", salt=f"{ORACLE_VERSION}+{SURROGATE_VERSION}"), retries=1) async def run_round( round_num: int, state: LoopState, pool: File, batch_size: int, beta: float, max_similarity: float, approval_timeout_s: int, seed: int, campaign: str, ) -> LoopState: """One turn of the loop. The output is the whole state, so a finished round is never run twice. The state includes the approval decision, so a cached round is not asked about again. The campaign name is part of the cache key: a run with a new campaign asks for approval afresh. """ started = time.time() smiles, _ = await load_pool(pool) rng = random.Random(seed * 1_000 + round_num) if round_num == 0: # The seed library: random molecules, measured once and shared by both arms. seed_batch = rng.sample(smiles, batch_size) results = list(await asyncio.gather(*[measure(s) for s in seed_batch])) log = RoundLog(0, "seed library", active=results, control=results) return replace(state, rounds=[replace(log, seconds=round_s(time.time() - started))]) active, control = state.measured("active"), state.measured("control") seen_control = {m.smiles for m in control} control_batch = rng.sample([s for s in smiles if s not in seen_control], batch_size) train = [m for m in active if m.ok] proposal = await propose( round_num, pool, [m.smiles for m in train], [m.gap for m in train], exclude=[m.smiles for m in active] + state.vetoed, control=control_batch, batch_size=batch_size, beta=beta, max_similarity=max_similarity, ) decision, waited = await approval(round_num, proposal, state, approval_timeout_s) log = RoundLog(round_num, decision, waited, proposal) if decision == "rejected": state = replace(state, vetoed=state.vetoed + [p.smiles for p in proposal.batch]) else: # Both arms go to the oracle at once. A molecule in both is computed once: the second # call is a cache hit. batch = [p.smiles for p in proposal.batch] results = await asyncio.gather(*[measure(s) for s in batch + control_batch]) log.active, log.control = list(results[: len(batch)]), list(results[len(batch):]) log.seconds = round_s(time.time() - started) return replace(state, rounds=state.rounds + [log]) # {{/docs-fragment round}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True, retries=2) async def discover( rounds: int = 10, batch_size: int = 64, pool_size: int = 20_000, beta: float = 1.0, max_similarity: float = 0.6, approval_timeout_s: int = 180, hit_gap: float = 1.0, seed: int = 0, campaign: str = "zinc-small-gap", ) -> File: """Run the closed loop and the random control, report both, and publish the best molecules. Rounds are cached, approvals included: rerunning with the same inputs replays the campaign without asking anyone. Pass a new ``campaign`` name to start over and be asked again. """ pool = await build_pool(pool_size, seed) state = LoopState() for r in range(rounds + 1): with flyte.group(f"round-{r}"): state = await run_round( r, state, pool, batch_size, beta, max_similarity, approval_timeout_s, seed, campaign) await flyte.report.replace.aio(reports.live(state, rounds, hit_gap, pool_size), do_flush=True) top = reports.top_molecules(state, 50) # The rounds' own durations: a resumed driver replays cached rounds in seconds, and this # still reports how long the loop took when it ran. loop_seconds = sum(r.seconds for r in state.rounds) await flyte.report.replace.aio(reports.final(state, hit_gap, pool_size, top, loop_seconds)) flyte.report.get_tab("Surrogate").replace(reports.surrogate_tab(state)) flyte.report.get_tab("Batches").replace(reports.batches_tab(state)) flyte.report.get_tab("Oracle").replace(reports.oracle_tab(state, flyte.ctx().action.run_name or "")) await flyte.report.flush.aio() path = f"{tempfile.mkdtemp()}/top_candidates.csv" reports.write_csv(top, path) summary = reports.summary(state, hit_gap) card = await artifacts.Card.create_from.aio(content=reports.card(state, top, hit_gap), format="html", card_type="data") metadata = artifacts.Metadata( name="closed-loop-top-candidates", description=f"The {len(top)} smallest-gap molecules found in {summary['calls']} GFN2-xTB calculations " f"over {pool_size:,} ZINC molecules; best {top[0]['gap_ev']:.2f} eV", kind="data", card=card, attrs={k: str(v) for k, v in summary.items()} | {"objective": "minimize GFN2-xTB HOMO-LUMO gap"}, ) return artifacts.new(await File.from_local(path), metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() if "--smoke" in sys.argv: run = flyte.run(discover, rounds=2, batch_size=16, pool_size=2_000, approval_timeout_s=60) else: run = flyte.run(discover) print(run.url) # {{/docs-fragment run}} CODE5 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "discover" # params = "rounds=2 batch_size=16 pool_size=2000" # /// """Closed-loop molecular discovery: a surrogate proposes, a quantum chemistry oracle measures. build_pool 20,000 drug-like molecules from ZINC250k, with fingerprints round 0: measure 64 random molecules, shared by both arms for each round: propose (warm CPU) retrain an MLP ensemble, pick 64 by a confidence bound approval (condition) a scientist approves the batch, or it auto-approves on timeout N x measure (CPU pool) GFN2-xTB HOMO-LUMO gap, cached per molecule and 64 random molecules through the same oracle, as the control arm report best gap found against oracle calls, and publish the top molecules as a dataset The objective is to find molecules with a small HOMO-LUMO gap, a cheap proxy for organic semiconductors and dyes. The oracle is real compute that can fail: conformer embedding, a GFN2-xTB geometry optimization, and a single point. Each round is a cached task whose output is the whole loop state, so a driver that crashes resumes from the last finished round, and a molecule measured once is never computed again, in this run or the next. python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules """ import asyncio import random import sys import tempfile import time from dataclasses import dataclass, field, replace import flyte import flyte.artifacts as artifacts import flyte.errors import flyte.report import reports from flyte.io import File from oracle import ORACLE_VERSION, Measurement from surrogate import SURROGATE_VERSION def round_s(x: float) -> float: return round(x, 1) ZINC_URL = ( "https://raw.githubusercontent.com/aspuru-guzik-group/chemical_vae/master/" "models/zinc_properties/250k_rndm_zinc_drugs_clean_3.csv" ) # {{docs-fragment envs}} # RDKit for molecules (its drawing code needs the X rendering libraries), tblite and ASE for # GFN2-xTB, scikit-learn for the surrogate, and unionai-reuse for the reusable environments. image = ( flyte.Image.from_debian_base(name="closed-loop-discovery", python_version=(3, 12)) .with_apt_packages("libxrender1", "libxext6", "libexpat1") .with_pip_packages("rdkit==2026.9.1", "tblite==0.8.0", "ase==3.29.0", "scikit-learn==1.9.1", "numpy==2.5.4", "unionai-reuse==0.2.1") ) CODE = ["oracle.py", "surrogate.py", "reports.py", "viz.py"] # The oracle: a warm pool of small CPU pods, one molecule per call. Every call is cached on # its SMILES string, so a molecule is measured once, ever, whichever arm or run asks for it. # "auto" caching hashes the task's own source, not the modules it imports, so the tasks that # use oracle.py and surrogate.py add those modules' versions to their cache keys (see below). oracle_env = flyte.TaskEnvironment( name="discovery-oracle", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), reusable=flyte.ReusePolicy(replicas=(2, 12), concurrency=1, idle_ttl=600, scaledown_ttl=120), env_vars={"OMP_NUM_THREADS": "2", "OMP_STACKSIZE": "1G"}, include=CODE, ) # The surrogate retrains every round on a single warm replica, which keeps its imports and # the downloaded pool between rounds. model_env = flyte.TaskEnvironment( name="discovery-model", image=image, resources=flyte.Resources(cpu=4, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=900), include=CODE, ) driver_env = flyte.TaskEnvironment( name="discovery-driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), include=CODE, depends_on=[oracle_env, model_env], ) # {{/docs-fragment envs}} # {{docs-fragment state}} @dataclass class Pick: smiles: str mean: float # predicted gap, eV std: float # ensemble spread, eV score: float # the acquisition score, mean - beta * std @dataclass class Proposal: round: int batch: list[Pick] # the active learning batch control: list[Pick] # the random control batch, with the same model's predictions train_size: int pool_median: float # median predicted gap over the whole pool fit_seconds: float @dataclass class RoundLog: round: int decision: str # "seed library", "approved", "rejected", "auto-approved", "no gate" gate_seconds: float = 0.0 proposal: Proposal | None = None active: list[Measurement] = field(default_factory=list) control: list[Measurement] = field(default_factory=list) seconds: float = 0.0 @dataclass class LoopState: rounds: list[RoundLog] = field(default_factory=list) vetoed: list[str] = field(default_factory=list) # molecules a scientist rejected def measured(self, arm: str) -> list[Measurement]: """Every measurement of one arm ("active" or "control") so far.""" return [m for r in self.rounds for m in getattr(r, arm)] # {{/docs-fragment state}} # {{docs-fragment pool}} @model_env.task(cache="auto") async def build_pool(pool_size: int = 20_000, seed: int = 0) -> File: """A random sample of neutral ZINC250k molecules, with their Morgan fingerprints.""" import csv import io import urllib.request import numpy as np from rdkit import Chem, RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize from surrogate import fingerprints RDLogger.DisableLog("rdApp.*") text = urllib.request.urlopen(ZINC_URL, timeout=120).read().decode() rows = [r["smiles"].strip() for r in csv.DictReader(io.StringIO(text))] random.Random(seed).shuffle(rows) # Gas-phase GFN2-xTB gives zwitterions and ions unphysically small gaps, so the pool keeps # neutral molecules only: neutralize what can be, and drop charged atoms other than nitro groups. uncharger, nitro = rdMolStandardize.Uncharger(), Chem.MolFromSmarts("[N+](=O)[O-]") pool, seen = [], set() for s in rows: mol = Chem.MolFromSmiles(s) if mol is None: continue mol = uncharger.uncharge(mol) charged = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) if Chem.GetFormalCharge(mol) != 0 or charged > 2 * len(mol.GetSubstructMatches(nitro)): continue smiles = Chem.MolToSmiles(mol) if smiles not in seen: seen.add(smiles) pool.append(smiles) if len(pool) == pool_size: break path = f"{tempfile.mkdtemp()}/pool.npz" np.savez_compressed(path, smiles=np.array(pool), fps=fingerprints(pool)) print(f"pool: {len(pool)} molecules from {len(rows)} in ZINC250k") return await File.from_local(path) # {{/docs-fragment pool}} async def load_pool(pool: File): import numpy as np data = np.load(await pool.download()) return [str(s) for s in data["smiles"]], data["fps"] # {{docs-fragment measure}} @oracle_env.task(cache=flyte.Cache("auto", salt=ORACLE_VERSION), retries=2) async def measure(smiles: str) -> Measurement: """Measure one molecule's HOMO-LUMO gap with GFN2-xTB. A failed calculation is a result, not an error.""" from oracle import measure_gap m = await asyncio.to_thread(measure_gap, smiles) m.measured_in = flyte.ctx().action.run_name or "" print(f"{smiles}: {'%.3f eV' % m.gap if m.ok else 'FAILED'} after {m.attempts} attempt(s) in {m.seconds:.1f}s {m.error}") return m # {{/docs-fragment measure}} # {{docs-fragment propose}} @model_env.task(cache=flyte.Cache("auto", salt=SURROGATE_VERSION)) async def propose( round_num: int, pool: File, train_smiles: list[str], train_gaps: list[float], exclude: list[str], control: list[str], batch_size: int, beta: float = 1.0, max_similarity: float = 0.6, ) -> Proposal: """Retrain the ensemble on everything measured so far and pick the next batch by a lower confidence bound.""" import numpy as np import surrogate started = time.time() smiles, packed = await load_pool(pool) index = {s: i for i, s in enumerate(smiles)} X = surrogate.unpack(packed) models = surrogate.fit_ensemble(X[[index[s] for s in train_smiles]], np.array(train_gaps), seed=round_num) mean, std = surrogate.predict(models, X) score = mean - beta * std # small predicted gap, or high uncertainty chosen = surrogate.select_batch(score, packed, {index[s] for s in exclude}, batch_size, max_similarity) def pick(i: int) -> Pick: return Pick(smiles[i], float(mean[i]), float(std[i]), float(score[i])) print(f"round {round_num}: trained on {len(train_smiles)}, batch predicted {mean[chosen].mean():.2f} eV") return Proposal(round_num, [pick(i) for i in chosen], [pick(index[s]) for s in control], len(train_smiles), float(np.median(mean)), round_s(time.time() - started)) # {{/docs-fragment propose}} # {{docs-fragment approval}} async def approval(round_num: int, proposal: Proposal, state: LoopState, timeout_s: int) -> tuple[str, float]: """Ask a scientist to approve the batch before it goes to the lab. Silence counts as approval.""" if timeout_s <= 0: return "no gate", 0.0 started = time.time() condition = await flyte.new_condition.aio( f"approve-round-{round_num}", prompt=reports.approval_prompt(proposal, state, timeout_s), prompt_type="markdown", data_type=bool, description=f"Send round {round_num}'s {len(proposal.batch)} molecules to the oracle?", timeout=timeout_s, ) try: approved = await condition.wait.aio() decision = "approved" if approved else "rejected" except flyte.errors.ConditionTimedoutError: decision = "auto-approved" # nobody answered: an unattended run keeps going return decision, round_s(time.time() - started) # {{/docs-fragment approval}} # {{docs-fragment round}} @driver_env.task(cache=flyte.Cache("auto", salt=f"{ORACLE_VERSION}+{SURROGATE_VERSION}"), retries=1) async def run_round( round_num: int, state: LoopState, pool: File, batch_size: int, beta: float, max_similarity: float, approval_timeout_s: int, seed: int, campaign: str, ) -> LoopState: """One turn of the loop. The output is the whole state, so a finished round is never run twice. The state includes the approval decision, so a cached round is not asked about again. The campaign name is part of the cache key: a run with a new campaign asks for approval afresh. """ started = time.time() smiles, _ = await load_pool(pool) rng = random.Random(seed * 1_000 + round_num) if round_num == 0: # The seed library: random molecules, measured once and shared by both arms. seed_batch = rng.sample(smiles, batch_size) results = list(await asyncio.gather(*[measure(s) for s in seed_batch])) log = RoundLog(0, "seed library", active=results, control=results) return replace(state, rounds=[replace(log, seconds=round_s(time.time() - started))]) active, control = state.measured("active"), state.measured("control") seen_control = {m.smiles for m in control} control_batch = rng.sample([s for s in smiles if s not in seen_control], batch_size) train = [m for m in active if m.ok] proposal = await propose( round_num, pool, [m.smiles for m in train], [m.gap for m in train], exclude=[m.smiles for m in active] + state.vetoed, control=control_batch, batch_size=batch_size, beta=beta, max_similarity=max_similarity, ) decision, waited = await approval(round_num, proposal, state, approval_timeout_s) log = RoundLog(round_num, decision, waited, proposal) if decision == "rejected": state = replace(state, vetoed=state.vetoed + [p.smiles for p in proposal.batch]) else: # Both arms go to the oracle at once. A molecule in both is computed once: the second # call is a cache hit. batch = [p.smiles for p in proposal.batch] results = await asyncio.gather(*[measure(s) for s in batch + control_batch]) log.active, log.control = list(results[: len(batch)]), list(results[len(batch):]) log.seconds = round_s(time.time() - started) return replace(state, rounds=state.rounds + [log]) # {{/docs-fragment round}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True, retries=2) async def discover( rounds: int = 10, batch_size: int = 64, pool_size: int = 20_000, beta: float = 1.0, max_similarity: float = 0.6, approval_timeout_s: int = 180, hit_gap: float = 1.0, seed: int = 0, campaign: str = "zinc-small-gap", ) -> File: """Run the closed loop and the random control, report both, and publish the best molecules. Rounds are cached, approvals included: rerunning with the same inputs replays the campaign without asking anyone. Pass a new ``campaign`` name to start over and be asked again. """ pool = await build_pool(pool_size, seed) state = LoopState() for r in range(rounds + 1): with flyte.group(f"round-{r}"): state = await run_round( r, state, pool, batch_size, beta, max_similarity, approval_timeout_s, seed, campaign) await flyte.report.replace.aio(reports.live(state, rounds, hit_gap, pool_size), do_flush=True) top = reports.top_molecules(state, 50) # The rounds' own durations: a resumed driver replays cached rounds in seconds, and this # still reports how long the loop took when it ran. loop_seconds = sum(r.seconds for r in state.rounds) await flyte.report.replace.aio(reports.final(state, hit_gap, pool_size, top, loop_seconds)) flyte.report.get_tab("Surrogate").replace(reports.surrogate_tab(state)) flyte.report.get_tab("Batches").replace(reports.batches_tab(state)) flyte.report.get_tab("Oracle").replace(reports.oracle_tab(state, flyte.ctx().action.run_name or "")) await flyte.report.flush.aio() path = f"{tempfile.mkdtemp()}/top_candidates.csv" reports.write_csv(top, path) summary = reports.summary(state, hit_gap) card = await artifacts.Card.create_from.aio(content=reports.card(state, top, hit_gap), format="html", card_type="data") metadata = artifacts.Metadata( name="closed-loop-top-candidates", description=f"The {len(top)} smallest-gap molecules found in {summary['calls']} GFN2-xTB calculations " f"over {pool_size:,} ZINC molecules; best {top[0]['gap_ev']:.2f} eV", kind="data", card=card, attrs={k: str(v) for k, v in summary.items()} | {"objective": "minimize GFN2-xTB HOMO-LUMO gap"}, ) return artifacts.new(await File.from_local(path), metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() if "--smoke" in sys.argv: run = flyte.run(discover, rounds=2, batch_size=16, pool_size=2_000, approval_timeout_s=60) else: run = flyte.run(discover) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/closed_loop_discovery/discovery.py* ## The oracle `measure_gap` is plain Python with no Flyte in it. Each attempt embeds conformers, relaxes them, optimizes the best ones with GFN2-xTB, checks that no bond broke during the optimization, and reads the orbital energies. A failed attempt is retried with random-coordinate embedding and a higher electronic temperature, which helps a stubborn SCF converge. CODE6 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/closed_loop_discovery/oracle.py* The task around it is short. The calculation runs in a thread so the replica stays responsive. A molecule that fails every attempt comes back as a `Measurement` with `ok=False` and the reasons, so it counts against the budget like a failed experiment and never fails the round. Task-level `retries=2` are for the infrastructure: a replica that is preempted mid-calculation. The task's cache keys every result on the SMILES string, and the result records the run that computed it, so the report can count how many measurements came from earlier runs. `"auto"` caching hashes the task's own source, not the modules it imports, so a change to `oracle.py` would go unnoticed. The cache is salted with `ORACLE_VERSION` from `oracle.py`; bump it when you change the protocol and every molecule is measured again. `propose` is salted the same way with `SURROGATE_VERSION` from `surrogate.py`. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "discover" # params = "rounds=2 batch_size=16 pool_size=2000" # /// """Closed-loop molecular discovery: a surrogate proposes, a quantum chemistry oracle measures. build_pool 20,000 drug-like molecules from ZINC250k, with fingerprints round 0: measure 64 random molecules, shared by both arms for each round: propose (warm CPU) retrain an MLP ensemble, pick 64 by a confidence bound approval (condition) a scientist approves the batch, or it auto-approves on timeout N x measure (CPU pool) GFN2-xTB HOMO-LUMO gap, cached per molecule and 64 random molecules through the same oracle, as the control arm report best gap found against oracle calls, and publish the top molecules as a dataset The objective is to find molecules with a small HOMO-LUMO gap, a cheap proxy for organic semiconductors and dyes. The oracle is real compute that can fail: conformer embedding, a GFN2-xTB geometry optimization, and a single point. Each round is a cached task whose output is the whole loop state, so a driver that crashes resumes from the last finished round, and a molecule measured once is never computed again, in this run or the next. python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules """ import asyncio import random import sys import tempfile import time from dataclasses import dataclass, field, replace import flyte import flyte.artifacts as artifacts import flyte.errors import flyte.report import reports from flyte.io import File from oracle import ORACLE_VERSION, Measurement from surrogate import SURROGATE_VERSION def round_s(x: float) -> float: return round(x, 1) ZINC_URL = ( "https://raw.githubusercontent.com/aspuru-guzik-group/chemical_vae/master/" "models/zinc_properties/250k_rndm_zinc_drugs_clean_3.csv" ) # {{docs-fragment envs}} # RDKit for molecules (its drawing code needs the X rendering libraries), tblite and ASE for # GFN2-xTB, scikit-learn for the surrogate, and unionai-reuse for the reusable environments. image = ( flyte.Image.from_debian_base(name="closed-loop-discovery", python_version=(3, 12)) .with_apt_packages("libxrender1", "libxext6", "libexpat1") .with_pip_packages("rdkit==2026.9.1", "tblite==0.8.0", "ase==3.29.0", "scikit-learn==1.9.1", "numpy==2.5.4", "unionai-reuse==0.2.1") ) CODE = ["oracle.py", "surrogate.py", "reports.py", "viz.py"] # The oracle: a warm pool of small CPU pods, one molecule per call. Every call is cached on # its SMILES string, so a molecule is measured once, ever, whichever arm or run asks for it. # "auto" caching hashes the task's own source, not the modules it imports, so the tasks that # use oracle.py and surrogate.py add those modules' versions to their cache keys (see below). oracle_env = flyte.TaskEnvironment( name="discovery-oracle", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), reusable=flyte.ReusePolicy(replicas=(2, 12), concurrency=1, idle_ttl=600, scaledown_ttl=120), env_vars={"OMP_NUM_THREADS": "2", "OMP_STACKSIZE": "1G"}, include=CODE, ) # The surrogate retrains every round on a single warm replica, which keeps its imports and # the downloaded pool between rounds. model_env = flyte.TaskEnvironment( name="discovery-model", image=image, resources=flyte.Resources(cpu=4, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=900), include=CODE, ) driver_env = flyte.TaskEnvironment( name="discovery-driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), include=CODE, depends_on=[oracle_env, model_env], ) # {{/docs-fragment envs}} # {{docs-fragment state}} @dataclass class Pick: smiles: str mean: float # predicted gap, eV std: float # ensemble spread, eV score: float # the acquisition score, mean - beta * std @dataclass class Proposal: round: int batch: list[Pick] # the active learning batch control: list[Pick] # the random control batch, with the same model's predictions train_size: int pool_median: float # median predicted gap over the whole pool fit_seconds: float @dataclass class RoundLog: round: int decision: str # "seed library", "approved", "rejected", "auto-approved", "no gate" gate_seconds: float = 0.0 proposal: Proposal | None = None active: list[Measurement] = field(default_factory=list) control: list[Measurement] = field(default_factory=list) seconds: float = 0.0 @dataclass class LoopState: rounds: list[RoundLog] = field(default_factory=list) vetoed: list[str] = field(default_factory=list) # molecules a scientist rejected def measured(self, arm: str) -> list[Measurement]: """Every measurement of one arm ("active" or "control") so far.""" return [m for r in self.rounds for m in getattr(r, arm)] # {{/docs-fragment state}} # {{docs-fragment pool}} @model_env.task(cache="auto") async def build_pool(pool_size: int = 20_000, seed: int = 0) -> File: """A random sample of neutral ZINC250k molecules, with their Morgan fingerprints.""" import csv import io import urllib.request import numpy as np from rdkit import Chem, RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize from surrogate import fingerprints RDLogger.DisableLog("rdApp.*") text = urllib.request.urlopen(ZINC_URL, timeout=120).read().decode() rows = [r["smiles"].strip() for r in csv.DictReader(io.StringIO(text))] random.Random(seed).shuffle(rows) # Gas-phase GFN2-xTB gives zwitterions and ions unphysically small gaps, so the pool keeps # neutral molecules only: neutralize what can be, and drop charged atoms other than nitro groups. uncharger, nitro = rdMolStandardize.Uncharger(), Chem.MolFromSmarts("[N+](=O)[O-]") pool, seen = [], set() for s in rows: mol = Chem.MolFromSmiles(s) if mol is None: continue mol = uncharger.uncharge(mol) charged = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) if Chem.GetFormalCharge(mol) != 0 or charged > 2 * len(mol.GetSubstructMatches(nitro)): continue smiles = Chem.MolToSmiles(mol) if smiles not in seen: seen.add(smiles) pool.append(smiles) if len(pool) == pool_size: break path = f"{tempfile.mkdtemp()}/pool.npz" np.savez_compressed(path, smiles=np.array(pool), fps=fingerprints(pool)) print(f"pool: {len(pool)} molecules from {len(rows)} in ZINC250k") return await File.from_local(path) # {{/docs-fragment pool}} async def load_pool(pool: File): import numpy as np data = np.load(await pool.download()) return [str(s) for s in data["smiles"]], data["fps"] # {{docs-fragment measure}} @oracle_env.task(cache=flyte.Cache("auto", salt=ORACLE_VERSION), retries=2) async def measure(smiles: str) -> Measurement: """Measure one molecule's HOMO-LUMO gap with GFN2-xTB. A failed calculation is a result, not an error.""" from oracle import measure_gap m = await asyncio.to_thread(measure_gap, smiles) m.measured_in = flyte.ctx().action.run_name or "" print(f"{smiles}: {'%.3f eV' % m.gap if m.ok else 'FAILED'} after {m.attempts} attempt(s) in {m.seconds:.1f}s {m.error}") return m # {{/docs-fragment measure}} # {{docs-fragment propose}} @model_env.task(cache=flyte.Cache("auto", salt=SURROGATE_VERSION)) async def propose( round_num: int, pool: File, train_smiles: list[str], train_gaps: list[float], exclude: list[str], control: list[str], batch_size: int, beta: float = 1.0, max_similarity: float = 0.6, ) -> Proposal: """Retrain the ensemble on everything measured so far and pick the next batch by a lower confidence bound.""" import numpy as np import surrogate started = time.time() smiles, packed = await load_pool(pool) index = {s: i for i, s in enumerate(smiles)} X = surrogate.unpack(packed) models = surrogate.fit_ensemble(X[[index[s] for s in train_smiles]], np.array(train_gaps), seed=round_num) mean, std = surrogate.predict(models, X) score = mean - beta * std # small predicted gap, or high uncertainty chosen = surrogate.select_batch(score, packed, {index[s] for s in exclude}, batch_size, max_similarity) def pick(i: int) -> Pick: return Pick(smiles[i], float(mean[i]), float(std[i]), float(score[i])) print(f"round {round_num}: trained on {len(train_smiles)}, batch predicted {mean[chosen].mean():.2f} eV") return Proposal(round_num, [pick(i) for i in chosen], [pick(index[s]) for s in control], len(train_smiles), float(np.median(mean)), round_s(time.time() - started)) # {{/docs-fragment propose}} # {{docs-fragment approval}} async def approval(round_num: int, proposal: Proposal, state: LoopState, timeout_s: int) -> tuple[str, float]: """Ask a scientist to approve the batch before it goes to the lab. Silence counts as approval.""" if timeout_s <= 0: return "no gate", 0.0 started = time.time() condition = await flyte.new_condition.aio( f"approve-round-{round_num}", prompt=reports.approval_prompt(proposal, state, timeout_s), prompt_type="markdown", data_type=bool, description=f"Send round {round_num}'s {len(proposal.batch)} molecules to the oracle?", timeout=timeout_s, ) try: approved = await condition.wait.aio() decision = "approved" if approved else "rejected" except flyte.errors.ConditionTimedoutError: decision = "auto-approved" # nobody answered: an unattended run keeps going return decision, round_s(time.time() - started) # {{/docs-fragment approval}} # {{docs-fragment round}} @driver_env.task(cache=flyte.Cache("auto", salt=f"{ORACLE_VERSION}+{SURROGATE_VERSION}"), retries=1) async def run_round( round_num: int, state: LoopState, pool: File, batch_size: int, beta: float, max_similarity: float, approval_timeout_s: int, seed: int, campaign: str, ) -> LoopState: """One turn of the loop. The output is the whole state, so a finished round is never run twice. The state includes the approval decision, so a cached round is not asked about again. The campaign name is part of the cache key: a run with a new campaign asks for approval afresh. """ started = time.time() smiles, _ = await load_pool(pool) rng = random.Random(seed * 1_000 + round_num) if round_num == 0: # The seed library: random molecules, measured once and shared by both arms. seed_batch = rng.sample(smiles, batch_size) results = list(await asyncio.gather(*[measure(s) for s in seed_batch])) log = RoundLog(0, "seed library", active=results, control=results) return replace(state, rounds=[replace(log, seconds=round_s(time.time() - started))]) active, control = state.measured("active"), state.measured("control") seen_control = {m.smiles for m in control} control_batch = rng.sample([s for s in smiles if s not in seen_control], batch_size) train = [m for m in active if m.ok] proposal = await propose( round_num, pool, [m.smiles for m in train], [m.gap for m in train], exclude=[m.smiles for m in active] + state.vetoed, control=control_batch, batch_size=batch_size, beta=beta, max_similarity=max_similarity, ) decision, waited = await approval(round_num, proposal, state, approval_timeout_s) log = RoundLog(round_num, decision, waited, proposal) if decision == "rejected": state = replace(state, vetoed=state.vetoed + [p.smiles for p in proposal.batch]) else: # Both arms go to the oracle at once. A molecule in both is computed once: the second # call is a cache hit. batch = [p.smiles for p in proposal.batch] results = await asyncio.gather(*[measure(s) for s in batch + control_batch]) log.active, log.control = list(results[: len(batch)]), list(results[len(batch):]) log.seconds = round_s(time.time() - started) return replace(state, rounds=state.rounds + [log]) # {{/docs-fragment round}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True, retries=2) async def discover( rounds: int = 10, batch_size: int = 64, pool_size: int = 20_000, beta: float = 1.0, max_similarity: float = 0.6, approval_timeout_s: int = 180, hit_gap: float = 1.0, seed: int = 0, campaign: str = "zinc-small-gap", ) -> File: """Run the closed loop and the random control, report both, and publish the best molecules. Rounds are cached, approvals included: rerunning with the same inputs replays the campaign without asking anyone. Pass a new ``campaign`` name to start over and be asked again. """ pool = await build_pool(pool_size, seed) state = LoopState() for r in range(rounds + 1): with flyte.group(f"round-{r}"): state = await run_round( r, state, pool, batch_size, beta, max_similarity, approval_timeout_s, seed, campaign) await flyte.report.replace.aio(reports.live(state, rounds, hit_gap, pool_size), do_flush=True) top = reports.top_molecules(state, 50) # The rounds' own durations: a resumed driver replays cached rounds in seconds, and this # still reports how long the loop took when it ran. loop_seconds = sum(r.seconds for r in state.rounds) await flyte.report.replace.aio(reports.final(state, hit_gap, pool_size, top, loop_seconds)) flyte.report.get_tab("Surrogate").replace(reports.surrogate_tab(state)) flyte.report.get_tab("Batches").replace(reports.batches_tab(state)) flyte.report.get_tab("Oracle").replace(reports.oracle_tab(state, flyte.ctx().action.run_name or "")) await flyte.report.flush.aio() path = f"{tempfile.mkdtemp()}/top_candidates.csv" reports.write_csv(top, path) summary = reports.summary(state, hit_gap) card = await artifacts.Card.create_from.aio(content=reports.card(state, top, hit_gap), format="html", card_type="data") metadata = artifacts.Metadata( name="closed-loop-top-candidates", description=f"The {len(top)} smallest-gap molecules found in {summary['calls']} GFN2-xTB calculations " f"over {pool_size:,} ZINC molecules; best {top[0]['gap_ev']:.2f} eV", kind="data", card=card, attrs={k: str(v) for k, v in summary.items()} | {"objective": "minimize GFN2-xTB HOMO-LUMO gap"}, ) return artifacts.new(await File.from_local(path), metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() if "--smoke" in sys.argv: run = flyte.run(discover, rounds=2, batch_size=16, pool_size=2_000, approval_timeout_s=60) else: run = flyte.run(discover) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/closed_loop_discovery/discovery.py* ## The surrogate and the acquisition function The surrogate is a bootstrap ensemble of 8 MLPs on 2048-bit Morgan fingerprints. Each member sees a resample of the measured molecules, so the members disagree where data is thin, and that spread is the model's uncertainty. Each round, every molecule in the pool gets a lower confidence bound on its gap, `mean - beta * std`, and the batch is filled greedily from the best bound down, skipping molecules too similar to one already picked. ``` """The surrogate and the acquisition function. The surrogate is a bootstrap ensemble of small MLPs on Morgan fingerprints. Each member is trained on a resample of the measured molecules, so the members agree where the data is dense and disagree where it is thin: the spread of their predictions is the model's uncertainty. Acquisition is a lower confidence bound on the gap, ``mean - beta * std``: a molecule is worth measuring if it is predicted to have a small gap, or if the model is unsure about it. A greedy diversity filter then skips any molecule too similar (Tanimoto) to one already in the batch, so a batch does not spend its budget on 64 near-copies of the same scaffold. """ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy as np # Part of the cache key of every task that uses this module: bump it when the model, its # features, or the acquisition changes, so cached proposals are not reused. SURROGATE_VERSION = "mlp-ensemble-lcb/1" FP_BITS = 2048 def fingerprints(smiles: list[str]) -> np.ndarray: """Morgan fingerprints (radius 2) as a packed uint8 matrix, 256 bytes per molecule.""" import numpy as np from rdkit import Chem, DataStructs from rdkit.Chem import rdFingerprintGenerator gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=FP_BITS) out = np.zeros((len(smiles), FP_BITS), dtype=np.uint8) for i, s in enumerate(smiles): DataStructs.ConvertToNumpyArray(gen.GetFingerprint(Chem.MolFromSmiles(s)), out[i]) return np.packbits(out, axis=1) def unpack(packed: np.ndarray) -> np.ndarray: import numpy as np return np.unpackbits(packed, axis=1).astype(np.float32) # {{docs-fragment select}} def fit_ensemble(X: np.ndarray, y: np.ndarray, members: int = 8, seed: int = 0) -> list: import numpy as np from sklearn.neural_network import MLPRegressor rng = np.random.default_rng(seed) models = [] for m in range(members): idx = rng.choice(len(y), len(y), replace=True) net = MLPRegressor(hidden_layer_sizes=(256, 64), alpha=1e-3, learning_rate_init=1e-3, max_iter=300, random_state=seed * 100 + m) models.append(net.fit(X[idx], y[idx])) return models def predict(models: list, X: np.ndarray, chunk: int = 4096) -> tuple[np.ndarray, np.ndarray]: import numpy as np preds = np.stack([np.concatenate([m.predict(X[i:i + chunk]) for i in range(0, len(X), chunk)]) for m in models]) return preds.mean(0), preds.std(0) def tanimoto(a: np.ndarray, b: np.ndarray) -> np.ndarray: """Tanimoto similarity of one packed fingerprint ``a`` to each row of ``b``.""" import numpy as np inter = np.unpackbits(a & b, axis=-1).sum(-1) union = np.unpackbits(a | b, axis=-1).sum(-1) return inter / np.maximum(union, 1) def select_batch(score: np.ndarray, packed: np.ndarray, exclude: set[int], k: int, max_similarity: float) -> list[int]: """Greedy: best score first, skipping excluded molecules and near-duplicates of earlier picks.""" import numpy as np picked: list[int] = [] for i in np.argsort(score): # lowest score (best) first i = int(i) if i in exclude: continue if picked and tanimoto(packed[i], packed[picked]).max() > max_similarity: continue picked.append(i) if len(picked) == k: break return picked # {{/docs-fragment select}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/closed_loop_discovery/surrogate.py* `propose` retrains the ensemble on every successful measurement so far and scores the whole pool. It also predicts the random control batch, which gives an unbiased, prospective test of the model every round. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "discover" # params = "rounds=2 batch_size=16 pool_size=2000" # /// """Closed-loop molecular discovery: a surrogate proposes, a quantum chemistry oracle measures. build_pool 20,000 drug-like molecules from ZINC250k, with fingerprints round 0: measure 64 random molecules, shared by both arms for each round: propose (warm CPU) retrain an MLP ensemble, pick 64 by a confidence bound approval (condition) a scientist approves the batch, or it auto-approves on timeout N x measure (CPU pool) GFN2-xTB HOMO-LUMO gap, cached per molecule and 64 random molecules through the same oracle, as the control arm report best gap found against oracle calls, and publish the top molecules as a dataset The objective is to find molecules with a small HOMO-LUMO gap, a cheap proxy for organic semiconductors and dyes. The oracle is real compute that can fail: conformer embedding, a GFN2-xTB geometry optimization, and a single point. Each round is a cached task whose output is the whole loop state, so a driver that crashes resumes from the last finished round, and a molecule measured once is never computed again, in this run or the next. python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules """ import asyncio import random import sys import tempfile import time from dataclasses import dataclass, field, replace import flyte import flyte.artifacts as artifacts import flyte.errors import flyte.report import reports from flyte.io import File from oracle import ORACLE_VERSION, Measurement from surrogate import SURROGATE_VERSION def round_s(x: float) -> float: return round(x, 1) ZINC_URL = ( "https://raw.githubusercontent.com/aspuru-guzik-group/chemical_vae/master/" "models/zinc_properties/250k_rndm_zinc_drugs_clean_3.csv" ) # {{docs-fragment envs}} # RDKit for molecules (its drawing code needs the X rendering libraries), tblite and ASE for # GFN2-xTB, scikit-learn for the surrogate, and unionai-reuse for the reusable environments. image = ( flyte.Image.from_debian_base(name="closed-loop-discovery", python_version=(3, 12)) .with_apt_packages("libxrender1", "libxext6", "libexpat1") .with_pip_packages("rdkit==2026.9.1", "tblite==0.8.0", "ase==3.29.0", "scikit-learn==1.9.1", "numpy==2.5.4", "unionai-reuse==0.2.1") ) CODE = ["oracle.py", "surrogate.py", "reports.py", "viz.py"] # The oracle: a warm pool of small CPU pods, one molecule per call. Every call is cached on # its SMILES string, so a molecule is measured once, ever, whichever arm or run asks for it. # "auto" caching hashes the task's own source, not the modules it imports, so the tasks that # use oracle.py and surrogate.py add those modules' versions to their cache keys (see below). oracle_env = flyte.TaskEnvironment( name="discovery-oracle", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), reusable=flyte.ReusePolicy(replicas=(2, 12), concurrency=1, idle_ttl=600, scaledown_ttl=120), env_vars={"OMP_NUM_THREADS": "2", "OMP_STACKSIZE": "1G"}, include=CODE, ) # The surrogate retrains every round on a single warm replica, which keeps its imports and # the downloaded pool between rounds. model_env = flyte.TaskEnvironment( name="discovery-model", image=image, resources=flyte.Resources(cpu=4, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=900), include=CODE, ) driver_env = flyte.TaskEnvironment( name="discovery-driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), include=CODE, depends_on=[oracle_env, model_env], ) # {{/docs-fragment envs}} # {{docs-fragment state}} @dataclass class Pick: smiles: str mean: float # predicted gap, eV std: float # ensemble spread, eV score: float # the acquisition score, mean - beta * std @dataclass class Proposal: round: int batch: list[Pick] # the active learning batch control: list[Pick] # the random control batch, with the same model's predictions train_size: int pool_median: float # median predicted gap over the whole pool fit_seconds: float @dataclass class RoundLog: round: int decision: str # "seed library", "approved", "rejected", "auto-approved", "no gate" gate_seconds: float = 0.0 proposal: Proposal | None = None active: list[Measurement] = field(default_factory=list) control: list[Measurement] = field(default_factory=list) seconds: float = 0.0 @dataclass class LoopState: rounds: list[RoundLog] = field(default_factory=list) vetoed: list[str] = field(default_factory=list) # molecules a scientist rejected def measured(self, arm: str) -> list[Measurement]: """Every measurement of one arm ("active" or "control") so far.""" return [m for r in self.rounds for m in getattr(r, arm)] # {{/docs-fragment state}} # {{docs-fragment pool}} @model_env.task(cache="auto") async def build_pool(pool_size: int = 20_000, seed: int = 0) -> File: """A random sample of neutral ZINC250k molecules, with their Morgan fingerprints.""" import csv import io import urllib.request import numpy as np from rdkit import Chem, RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize from surrogate import fingerprints RDLogger.DisableLog("rdApp.*") text = urllib.request.urlopen(ZINC_URL, timeout=120).read().decode() rows = [r["smiles"].strip() for r in csv.DictReader(io.StringIO(text))] random.Random(seed).shuffle(rows) # Gas-phase GFN2-xTB gives zwitterions and ions unphysically small gaps, so the pool keeps # neutral molecules only: neutralize what can be, and drop charged atoms other than nitro groups. uncharger, nitro = rdMolStandardize.Uncharger(), Chem.MolFromSmarts("[N+](=O)[O-]") pool, seen = [], set() for s in rows: mol = Chem.MolFromSmiles(s) if mol is None: continue mol = uncharger.uncharge(mol) charged = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) if Chem.GetFormalCharge(mol) != 0 or charged > 2 * len(mol.GetSubstructMatches(nitro)): continue smiles = Chem.MolToSmiles(mol) if smiles not in seen: seen.add(smiles) pool.append(smiles) if len(pool) == pool_size: break path = f"{tempfile.mkdtemp()}/pool.npz" np.savez_compressed(path, smiles=np.array(pool), fps=fingerprints(pool)) print(f"pool: {len(pool)} molecules from {len(rows)} in ZINC250k") return await File.from_local(path) # {{/docs-fragment pool}} async def load_pool(pool: File): import numpy as np data = np.load(await pool.download()) return [str(s) for s in data["smiles"]], data["fps"] # {{docs-fragment measure}} @oracle_env.task(cache=flyte.Cache("auto", salt=ORACLE_VERSION), retries=2) async def measure(smiles: str) -> Measurement: """Measure one molecule's HOMO-LUMO gap with GFN2-xTB. A failed calculation is a result, not an error.""" from oracle import measure_gap m = await asyncio.to_thread(measure_gap, smiles) m.measured_in = flyte.ctx().action.run_name or "" print(f"{smiles}: {'%.3f eV' % m.gap if m.ok else 'FAILED'} after {m.attempts} attempt(s) in {m.seconds:.1f}s {m.error}") return m # {{/docs-fragment measure}} # {{docs-fragment propose}} @model_env.task(cache=flyte.Cache("auto", salt=SURROGATE_VERSION)) async def propose( round_num: int, pool: File, train_smiles: list[str], train_gaps: list[float], exclude: list[str], control: list[str], batch_size: int, beta: float = 1.0, max_similarity: float = 0.6, ) -> Proposal: """Retrain the ensemble on everything measured so far and pick the next batch by a lower confidence bound.""" import numpy as np import surrogate started = time.time() smiles, packed = await load_pool(pool) index = {s: i for i, s in enumerate(smiles)} X = surrogate.unpack(packed) models = surrogate.fit_ensemble(X[[index[s] for s in train_smiles]], np.array(train_gaps), seed=round_num) mean, std = surrogate.predict(models, X) score = mean - beta * std # small predicted gap, or high uncertainty chosen = surrogate.select_batch(score, packed, {index[s] for s in exclude}, batch_size, max_similarity) def pick(i: int) -> Pick: return Pick(smiles[i], float(mean[i]), float(std[i]), float(score[i])) print(f"round {round_num}: trained on {len(train_smiles)}, batch predicted {mean[chosen].mean():.2f} eV") return Proposal(round_num, [pick(i) for i in chosen], [pick(index[s]) for s in control], len(train_smiles), float(np.median(mean)), round_s(time.time() - started)) # {{/docs-fragment propose}} # {{docs-fragment approval}} async def approval(round_num: int, proposal: Proposal, state: LoopState, timeout_s: int) -> tuple[str, float]: """Ask a scientist to approve the batch before it goes to the lab. Silence counts as approval.""" if timeout_s <= 0: return "no gate", 0.0 started = time.time() condition = await flyte.new_condition.aio( f"approve-round-{round_num}", prompt=reports.approval_prompt(proposal, state, timeout_s), prompt_type="markdown", data_type=bool, description=f"Send round {round_num}'s {len(proposal.batch)} molecules to the oracle?", timeout=timeout_s, ) try: approved = await condition.wait.aio() decision = "approved" if approved else "rejected" except flyte.errors.ConditionTimedoutError: decision = "auto-approved" # nobody answered: an unattended run keeps going return decision, round_s(time.time() - started) # {{/docs-fragment approval}} # {{docs-fragment round}} @driver_env.task(cache=flyte.Cache("auto", salt=f"{ORACLE_VERSION}+{SURROGATE_VERSION}"), retries=1) async def run_round( round_num: int, state: LoopState, pool: File, batch_size: int, beta: float, max_similarity: float, approval_timeout_s: int, seed: int, campaign: str, ) -> LoopState: """One turn of the loop. The output is the whole state, so a finished round is never run twice. The state includes the approval decision, so a cached round is not asked about again. The campaign name is part of the cache key: a run with a new campaign asks for approval afresh. """ started = time.time() smiles, _ = await load_pool(pool) rng = random.Random(seed * 1_000 + round_num) if round_num == 0: # The seed library: random molecules, measured once and shared by both arms. seed_batch = rng.sample(smiles, batch_size) results = list(await asyncio.gather(*[measure(s) for s in seed_batch])) log = RoundLog(0, "seed library", active=results, control=results) return replace(state, rounds=[replace(log, seconds=round_s(time.time() - started))]) active, control = state.measured("active"), state.measured("control") seen_control = {m.smiles for m in control} control_batch = rng.sample([s for s in smiles if s not in seen_control], batch_size) train = [m for m in active if m.ok] proposal = await propose( round_num, pool, [m.smiles for m in train], [m.gap for m in train], exclude=[m.smiles for m in active] + state.vetoed, control=control_batch, batch_size=batch_size, beta=beta, max_similarity=max_similarity, ) decision, waited = await approval(round_num, proposal, state, approval_timeout_s) log = RoundLog(round_num, decision, waited, proposal) if decision == "rejected": state = replace(state, vetoed=state.vetoed + [p.smiles for p in proposal.batch]) else: # Both arms go to the oracle at once. A molecule in both is computed once: the second # call is a cache hit. batch = [p.smiles for p in proposal.batch] results = await asyncio.gather(*[measure(s) for s in batch + control_batch]) log.active, log.control = list(results[: len(batch)]), list(results[len(batch):]) log.seconds = round_s(time.time() - started) return replace(state, rounds=state.rounds + [log]) # {{/docs-fragment round}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True, retries=2) async def discover( rounds: int = 10, batch_size: int = 64, pool_size: int = 20_000, beta: float = 1.0, max_similarity: float = 0.6, approval_timeout_s: int = 180, hit_gap: float = 1.0, seed: int = 0, campaign: str = "zinc-small-gap", ) -> File: """Run the closed loop and the random control, report both, and publish the best molecules. Rounds are cached, approvals included: rerunning with the same inputs replays the campaign without asking anyone. Pass a new ``campaign`` name to start over and be asked again. """ pool = await build_pool(pool_size, seed) state = LoopState() for r in range(rounds + 1): with flyte.group(f"round-{r}"): state = await run_round( r, state, pool, batch_size, beta, max_similarity, approval_timeout_s, seed, campaign) await flyte.report.replace.aio(reports.live(state, rounds, hit_gap, pool_size), do_flush=True) top = reports.top_molecules(state, 50) # The rounds' own durations: a resumed driver replays cached rounds in seconds, and this # still reports how long the loop took when it ran. loop_seconds = sum(r.seconds for r in state.rounds) await flyte.report.replace.aio(reports.final(state, hit_gap, pool_size, top, loop_seconds)) flyte.report.get_tab("Surrogate").replace(reports.surrogate_tab(state)) flyte.report.get_tab("Batches").replace(reports.batches_tab(state)) flyte.report.get_tab("Oracle").replace(reports.oracle_tab(state, flyte.ctx().action.run_name or "")) await flyte.report.flush.aio() path = f"{tempfile.mkdtemp()}/top_candidates.csv" reports.write_csv(top, path) summary = reports.summary(state, hit_gap) card = await artifacts.Card.create_from.aio(content=reports.card(state, top, hit_gap), format="html", card_type="data") metadata = artifacts.Metadata( name="closed-loop-top-candidates", description=f"The {len(top)} smallest-gap molecules found in {summary['calls']} GFN2-xTB calculations " f"over {pool_size:,} ZINC molecules; best {top[0]['gap_ev']:.2f} eV", kind="data", card=card, attrs={k: str(v) for k, v in summary.items()} | {"objective": "minimize GFN2-xTB HOMO-LUMO gap"}, ) return artifacts.new(await File.from_local(path), metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() if "--smoke" in sys.argv: run = flyte.run(discover, rounds=2, batch_size=16, pool_size=2_000, approval_timeout_s=60) else: run = flyte.run(discover) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/closed_loop_discovery/discovery.py* ## The approval gate Before a batch goes to the oracle, the loop asks for approval. `flyte.new_condition` registers a condition on the run with a Markdown prompt that summarizes the batch: what the model predicts, how wrong it was last round, and the top 10 molecules. The run waits until someone signals the condition, from the UI, the CLI, or the API. A rejected batch is skipped, and its molecules are never proposed again. A loop that runs overnight must not stall on a question nobody is awake to answer, so the condition has a timeout. If it expires, `wait()` raises `ConditionTimedoutError` and the batch is approved automatically. Set `approval_timeout_s=0` to turn the gate off. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "discover" # params = "rounds=2 batch_size=16 pool_size=2000" # /// """Closed-loop molecular discovery: a surrogate proposes, a quantum chemistry oracle measures. build_pool 20,000 drug-like molecules from ZINC250k, with fingerprints round 0: measure 64 random molecules, shared by both arms for each round: propose (warm CPU) retrain an MLP ensemble, pick 64 by a confidence bound approval (condition) a scientist approves the batch, or it auto-approves on timeout N x measure (CPU pool) GFN2-xTB HOMO-LUMO gap, cached per molecule and 64 random molecules through the same oracle, as the control arm report best gap found against oracle calls, and publish the top molecules as a dataset The objective is to find molecules with a small HOMO-LUMO gap, a cheap proxy for organic semiconductors and dyes. The oracle is real compute that can fail: conformer embedding, a GFN2-xTB geometry optimization, and a single point. Each round is a cached task whose output is the whole loop state, so a driver that crashes resumes from the last finished round, and a molecule measured once is never computed again, in this run or the next. python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules """ import asyncio import random import sys import tempfile import time from dataclasses import dataclass, field, replace import flyte import flyte.artifacts as artifacts import flyte.errors import flyte.report import reports from flyte.io import File from oracle import ORACLE_VERSION, Measurement from surrogate import SURROGATE_VERSION def round_s(x: float) -> float: return round(x, 1) ZINC_URL = ( "https://raw.githubusercontent.com/aspuru-guzik-group/chemical_vae/master/" "models/zinc_properties/250k_rndm_zinc_drugs_clean_3.csv" ) # {{docs-fragment envs}} # RDKit for molecules (its drawing code needs the X rendering libraries), tblite and ASE for # GFN2-xTB, scikit-learn for the surrogate, and unionai-reuse for the reusable environments. image = ( flyte.Image.from_debian_base(name="closed-loop-discovery", python_version=(3, 12)) .with_apt_packages("libxrender1", "libxext6", "libexpat1") .with_pip_packages("rdkit==2026.9.1", "tblite==0.8.0", "ase==3.29.0", "scikit-learn==1.9.1", "numpy==2.5.4", "unionai-reuse==0.2.1") ) CODE = ["oracle.py", "surrogate.py", "reports.py", "viz.py"] # The oracle: a warm pool of small CPU pods, one molecule per call. Every call is cached on # its SMILES string, so a molecule is measured once, ever, whichever arm or run asks for it. # "auto" caching hashes the task's own source, not the modules it imports, so the tasks that # use oracle.py and surrogate.py add those modules' versions to their cache keys (see below). oracle_env = flyte.TaskEnvironment( name="discovery-oracle", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), reusable=flyte.ReusePolicy(replicas=(2, 12), concurrency=1, idle_ttl=600, scaledown_ttl=120), env_vars={"OMP_NUM_THREADS": "2", "OMP_STACKSIZE": "1G"}, include=CODE, ) # The surrogate retrains every round on a single warm replica, which keeps its imports and # the downloaded pool between rounds. model_env = flyte.TaskEnvironment( name="discovery-model", image=image, resources=flyte.Resources(cpu=4, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=900), include=CODE, ) driver_env = flyte.TaskEnvironment( name="discovery-driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), include=CODE, depends_on=[oracle_env, model_env], ) # {{/docs-fragment envs}} # {{docs-fragment state}} @dataclass class Pick: smiles: str mean: float # predicted gap, eV std: float # ensemble spread, eV score: float # the acquisition score, mean - beta * std @dataclass class Proposal: round: int batch: list[Pick] # the active learning batch control: list[Pick] # the random control batch, with the same model's predictions train_size: int pool_median: float # median predicted gap over the whole pool fit_seconds: float @dataclass class RoundLog: round: int decision: str # "seed library", "approved", "rejected", "auto-approved", "no gate" gate_seconds: float = 0.0 proposal: Proposal | None = None active: list[Measurement] = field(default_factory=list) control: list[Measurement] = field(default_factory=list) seconds: float = 0.0 @dataclass class LoopState: rounds: list[RoundLog] = field(default_factory=list) vetoed: list[str] = field(default_factory=list) # molecules a scientist rejected def measured(self, arm: str) -> list[Measurement]: """Every measurement of one arm ("active" or "control") so far.""" return [m for r in self.rounds for m in getattr(r, arm)] # {{/docs-fragment state}} # {{docs-fragment pool}} @model_env.task(cache="auto") async def build_pool(pool_size: int = 20_000, seed: int = 0) -> File: """A random sample of neutral ZINC250k molecules, with their Morgan fingerprints.""" import csv import io import urllib.request import numpy as np from rdkit import Chem, RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize from surrogate import fingerprints RDLogger.DisableLog("rdApp.*") text = urllib.request.urlopen(ZINC_URL, timeout=120).read().decode() rows = [r["smiles"].strip() for r in csv.DictReader(io.StringIO(text))] random.Random(seed).shuffle(rows) # Gas-phase GFN2-xTB gives zwitterions and ions unphysically small gaps, so the pool keeps # neutral molecules only: neutralize what can be, and drop charged atoms other than nitro groups. uncharger, nitro = rdMolStandardize.Uncharger(), Chem.MolFromSmarts("[N+](=O)[O-]") pool, seen = [], set() for s in rows: mol = Chem.MolFromSmiles(s) if mol is None: continue mol = uncharger.uncharge(mol) charged = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) if Chem.GetFormalCharge(mol) != 0 or charged > 2 * len(mol.GetSubstructMatches(nitro)): continue smiles = Chem.MolToSmiles(mol) if smiles not in seen: seen.add(smiles) pool.append(smiles) if len(pool) == pool_size: break path = f"{tempfile.mkdtemp()}/pool.npz" np.savez_compressed(path, smiles=np.array(pool), fps=fingerprints(pool)) print(f"pool: {len(pool)} molecules from {len(rows)} in ZINC250k") return await File.from_local(path) # {{/docs-fragment pool}} async def load_pool(pool: File): import numpy as np data = np.load(await pool.download()) return [str(s) for s in data["smiles"]], data["fps"] # {{docs-fragment measure}} @oracle_env.task(cache=flyte.Cache("auto", salt=ORACLE_VERSION), retries=2) async def measure(smiles: str) -> Measurement: """Measure one molecule's HOMO-LUMO gap with GFN2-xTB. A failed calculation is a result, not an error.""" from oracle import measure_gap m = await asyncio.to_thread(measure_gap, smiles) m.measured_in = flyte.ctx().action.run_name or "" print(f"{smiles}: {'%.3f eV' % m.gap if m.ok else 'FAILED'} after {m.attempts} attempt(s) in {m.seconds:.1f}s {m.error}") return m # {{/docs-fragment measure}} # {{docs-fragment propose}} @model_env.task(cache=flyte.Cache("auto", salt=SURROGATE_VERSION)) async def propose( round_num: int, pool: File, train_smiles: list[str], train_gaps: list[float], exclude: list[str], control: list[str], batch_size: int, beta: float = 1.0, max_similarity: float = 0.6, ) -> Proposal: """Retrain the ensemble on everything measured so far and pick the next batch by a lower confidence bound.""" import numpy as np import surrogate started = time.time() smiles, packed = await load_pool(pool) index = {s: i for i, s in enumerate(smiles)} X = surrogate.unpack(packed) models = surrogate.fit_ensemble(X[[index[s] for s in train_smiles]], np.array(train_gaps), seed=round_num) mean, std = surrogate.predict(models, X) score = mean - beta * std # small predicted gap, or high uncertainty chosen = surrogate.select_batch(score, packed, {index[s] for s in exclude}, batch_size, max_similarity) def pick(i: int) -> Pick: return Pick(smiles[i], float(mean[i]), float(std[i]), float(score[i])) print(f"round {round_num}: trained on {len(train_smiles)}, batch predicted {mean[chosen].mean():.2f} eV") return Proposal(round_num, [pick(i) for i in chosen], [pick(index[s]) for s in control], len(train_smiles), float(np.median(mean)), round_s(time.time() - started)) # {{/docs-fragment propose}} # {{docs-fragment approval}} async def approval(round_num: int, proposal: Proposal, state: LoopState, timeout_s: int) -> tuple[str, float]: """Ask a scientist to approve the batch before it goes to the lab. Silence counts as approval.""" if timeout_s <= 0: return "no gate", 0.0 started = time.time() condition = await flyte.new_condition.aio( f"approve-round-{round_num}", prompt=reports.approval_prompt(proposal, state, timeout_s), prompt_type="markdown", data_type=bool, description=f"Send round {round_num}'s {len(proposal.batch)} molecules to the oracle?", timeout=timeout_s, ) try: approved = await condition.wait.aio() decision = "approved" if approved else "rejected" except flyte.errors.ConditionTimedoutError: decision = "auto-approved" # nobody answered: an unattended run keeps going return decision, round_s(time.time() - started) # {{/docs-fragment approval}} # {{docs-fragment round}} @driver_env.task(cache=flyte.Cache("auto", salt=f"{ORACLE_VERSION}+{SURROGATE_VERSION}"), retries=1) async def run_round( round_num: int, state: LoopState, pool: File, batch_size: int, beta: float, max_similarity: float, approval_timeout_s: int, seed: int, campaign: str, ) -> LoopState: """One turn of the loop. The output is the whole state, so a finished round is never run twice. The state includes the approval decision, so a cached round is not asked about again. The campaign name is part of the cache key: a run with a new campaign asks for approval afresh. """ started = time.time() smiles, _ = await load_pool(pool) rng = random.Random(seed * 1_000 + round_num) if round_num == 0: # The seed library: random molecules, measured once and shared by both arms. seed_batch = rng.sample(smiles, batch_size) results = list(await asyncio.gather(*[measure(s) for s in seed_batch])) log = RoundLog(0, "seed library", active=results, control=results) return replace(state, rounds=[replace(log, seconds=round_s(time.time() - started))]) active, control = state.measured("active"), state.measured("control") seen_control = {m.smiles for m in control} control_batch = rng.sample([s for s in smiles if s not in seen_control], batch_size) train = [m for m in active if m.ok] proposal = await propose( round_num, pool, [m.smiles for m in train], [m.gap for m in train], exclude=[m.smiles for m in active] + state.vetoed, control=control_batch, batch_size=batch_size, beta=beta, max_similarity=max_similarity, ) decision, waited = await approval(round_num, proposal, state, approval_timeout_s) log = RoundLog(round_num, decision, waited, proposal) if decision == "rejected": state = replace(state, vetoed=state.vetoed + [p.smiles for p in proposal.batch]) else: # Both arms go to the oracle at once. A molecule in both is computed once: the second # call is a cache hit. batch = [p.smiles for p in proposal.batch] results = await asyncio.gather(*[measure(s) for s in batch + control_batch]) log.active, log.control = list(results[: len(batch)]), list(results[len(batch):]) log.seconds = round_s(time.time() - started) return replace(state, rounds=state.rounds + [log]) # {{/docs-fragment round}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True, retries=2) async def discover( rounds: int = 10, batch_size: int = 64, pool_size: int = 20_000, beta: float = 1.0, max_similarity: float = 0.6, approval_timeout_s: int = 180, hit_gap: float = 1.0, seed: int = 0, campaign: str = "zinc-small-gap", ) -> File: """Run the closed loop and the random control, report both, and publish the best molecules. Rounds are cached, approvals included: rerunning with the same inputs replays the campaign without asking anyone. Pass a new ``campaign`` name to start over and be asked again. """ pool = await build_pool(pool_size, seed) state = LoopState() for r in range(rounds + 1): with flyte.group(f"round-{r}"): state = await run_round( r, state, pool, batch_size, beta, max_similarity, approval_timeout_s, seed, campaign) await flyte.report.replace.aio(reports.live(state, rounds, hit_gap, pool_size), do_flush=True) top = reports.top_molecules(state, 50) # The rounds' own durations: a resumed driver replays cached rounds in seconds, and this # still reports how long the loop took when it ran. loop_seconds = sum(r.seconds for r in state.rounds) await flyte.report.replace.aio(reports.final(state, hit_gap, pool_size, top, loop_seconds)) flyte.report.get_tab("Surrogate").replace(reports.surrogate_tab(state)) flyte.report.get_tab("Batches").replace(reports.batches_tab(state)) flyte.report.get_tab("Oracle").replace(reports.oracle_tab(state, flyte.ctx().action.run_name or "")) await flyte.report.flush.aio() path = f"{tempfile.mkdtemp()}/top_candidates.csv" reports.write_csv(top, path) summary = reports.summary(state, hit_gap) card = await artifacts.Card.create_from.aio(content=reports.card(state, top, hit_gap), format="html", card_type="data") metadata = artifacts.Metadata( name="closed-loop-top-candidates", description=f"The {len(top)} smallest-gap molecules found in {summary['calls']} GFN2-xTB calculations " f"over {pool_size:,} ZINC molecules; best {top[0]['gap_ev']:.2f} eV", kind="data", card=card, attrs={k: str(v) for k, v in summary.items()} | {"objective": "minimize GFN2-xTB HOMO-LUMO gap"}, ) return artifacts.new(await File.from_local(path), metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() if "--smoke" in sys.argv: run = flyte.run(discover, rounds=2, batch_size=16, pool_size=2_000, approval_timeout_s=60) else: run = flyte.run(discover) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/closed_loop_discovery/discovery.py* ## One round, durably A round picks the random control batch, asks for a proposal, waits for approval, and measures both batches at once on the oracle pool. Round 0 is the seed library, random molecules shared by both arms, because the model needs data before it can propose anything. The loop state is a few dataclasses: a `Pick` is one proposed molecule with its prediction, a `Proposal` is one round's two batches, a `RoundLog` is what happened in a round, and `LoopState` is every round so far plus the molecules a scientist vetoed. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "discover" # params = "rounds=2 batch_size=16 pool_size=2000" # /// """Closed-loop molecular discovery: a surrogate proposes, a quantum chemistry oracle measures. build_pool 20,000 drug-like molecules from ZINC250k, with fingerprints round 0: measure 64 random molecules, shared by both arms for each round: propose (warm CPU) retrain an MLP ensemble, pick 64 by a confidence bound approval (condition) a scientist approves the batch, or it auto-approves on timeout N x measure (CPU pool) GFN2-xTB HOMO-LUMO gap, cached per molecule and 64 random molecules through the same oracle, as the control arm report best gap found against oracle calls, and publish the top molecules as a dataset The objective is to find molecules with a small HOMO-LUMO gap, a cheap proxy for organic semiconductors and dyes. The oracle is real compute that can fail: conformer embedding, a GFN2-xTB geometry optimization, and a single point. Each round is a cached task whose output is the whole loop state, so a driver that crashes resumes from the last finished round, and a molecule measured once is never computed again, in this run or the next. python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules """ import asyncio import random import sys import tempfile import time from dataclasses import dataclass, field, replace import flyte import flyte.artifacts as artifacts import flyte.errors import flyte.report import reports from flyte.io import File from oracle import ORACLE_VERSION, Measurement from surrogate import SURROGATE_VERSION def round_s(x: float) -> float: return round(x, 1) ZINC_URL = ( "https://raw.githubusercontent.com/aspuru-guzik-group/chemical_vae/master/" "models/zinc_properties/250k_rndm_zinc_drugs_clean_3.csv" ) # {{docs-fragment envs}} # RDKit for molecules (its drawing code needs the X rendering libraries), tblite and ASE for # GFN2-xTB, scikit-learn for the surrogate, and unionai-reuse for the reusable environments. image = ( flyte.Image.from_debian_base(name="closed-loop-discovery", python_version=(3, 12)) .with_apt_packages("libxrender1", "libxext6", "libexpat1") .with_pip_packages("rdkit==2026.9.1", "tblite==0.8.0", "ase==3.29.0", "scikit-learn==1.9.1", "numpy==2.5.4", "unionai-reuse==0.2.1") ) CODE = ["oracle.py", "surrogate.py", "reports.py", "viz.py"] # The oracle: a warm pool of small CPU pods, one molecule per call. Every call is cached on # its SMILES string, so a molecule is measured once, ever, whichever arm or run asks for it. # "auto" caching hashes the task's own source, not the modules it imports, so the tasks that # use oracle.py and surrogate.py add those modules' versions to their cache keys (see below). oracle_env = flyte.TaskEnvironment( name="discovery-oracle", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), reusable=flyte.ReusePolicy(replicas=(2, 12), concurrency=1, idle_ttl=600, scaledown_ttl=120), env_vars={"OMP_NUM_THREADS": "2", "OMP_STACKSIZE": "1G"}, include=CODE, ) # The surrogate retrains every round on a single warm replica, which keeps its imports and # the downloaded pool between rounds. model_env = flyte.TaskEnvironment( name="discovery-model", image=image, resources=flyte.Resources(cpu=4, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=900), include=CODE, ) driver_env = flyte.TaskEnvironment( name="discovery-driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), include=CODE, depends_on=[oracle_env, model_env], ) # {{/docs-fragment envs}} # {{docs-fragment state}} @dataclass class Pick: smiles: str mean: float # predicted gap, eV std: float # ensemble spread, eV score: float # the acquisition score, mean - beta * std @dataclass class Proposal: round: int batch: list[Pick] # the active learning batch control: list[Pick] # the random control batch, with the same model's predictions train_size: int pool_median: float # median predicted gap over the whole pool fit_seconds: float @dataclass class RoundLog: round: int decision: str # "seed library", "approved", "rejected", "auto-approved", "no gate" gate_seconds: float = 0.0 proposal: Proposal | None = None active: list[Measurement] = field(default_factory=list) control: list[Measurement] = field(default_factory=list) seconds: float = 0.0 @dataclass class LoopState: rounds: list[RoundLog] = field(default_factory=list) vetoed: list[str] = field(default_factory=list) # molecules a scientist rejected def measured(self, arm: str) -> list[Measurement]: """Every measurement of one arm ("active" or "control") so far.""" return [m for r in self.rounds for m in getattr(r, arm)] # {{/docs-fragment state}} # {{docs-fragment pool}} @model_env.task(cache="auto") async def build_pool(pool_size: int = 20_000, seed: int = 0) -> File: """A random sample of neutral ZINC250k molecules, with their Morgan fingerprints.""" import csv import io import urllib.request import numpy as np from rdkit import Chem, RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize from surrogate import fingerprints RDLogger.DisableLog("rdApp.*") text = urllib.request.urlopen(ZINC_URL, timeout=120).read().decode() rows = [r["smiles"].strip() for r in csv.DictReader(io.StringIO(text))] random.Random(seed).shuffle(rows) # Gas-phase GFN2-xTB gives zwitterions and ions unphysically small gaps, so the pool keeps # neutral molecules only: neutralize what can be, and drop charged atoms other than nitro groups. uncharger, nitro = rdMolStandardize.Uncharger(), Chem.MolFromSmarts("[N+](=O)[O-]") pool, seen = [], set() for s in rows: mol = Chem.MolFromSmiles(s) if mol is None: continue mol = uncharger.uncharge(mol) charged = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) if Chem.GetFormalCharge(mol) != 0 or charged > 2 * len(mol.GetSubstructMatches(nitro)): continue smiles = Chem.MolToSmiles(mol) if smiles not in seen: seen.add(smiles) pool.append(smiles) if len(pool) == pool_size: break path = f"{tempfile.mkdtemp()}/pool.npz" np.savez_compressed(path, smiles=np.array(pool), fps=fingerprints(pool)) print(f"pool: {len(pool)} molecules from {len(rows)} in ZINC250k") return await File.from_local(path) # {{/docs-fragment pool}} async def load_pool(pool: File): import numpy as np data = np.load(await pool.download()) return [str(s) for s in data["smiles"]], data["fps"] # {{docs-fragment measure}} @oracle_env.task(cache=flyte.Cache("auto", salt=ORACLE_VERSION), retries=2) async def measure(smiles: str) -> Measurement: """Measure one molecule's HOMO-LUMO gap with GFN2-xTB. A failed calculation is a result, not an error.""" from oracle import measure_gap m = await asyncio.to_thread(measure_gap, smiles) m.measured_in = flyte.ctx().action.run_name or "" print(f"{smiles}: {'%.3f eV' % m.gap if m.ok else 'FAILED'} after {m.attempts} attempt(s) in {m.seconds:.1f}s {m.error}") return m # {{/docs-fragment measure}} # {{docs-fragment propose}} @model_env.task(cache=flyte.Cache("auto", salt=SURROGATE_VERSION)) async def propose( round_num: int, pool: File, train_smiles: list[str], train_gaps: list[float], exclude: list[str], control: list[str], batch_size: int, beta: float = 1.0, max_similarity: float = 0.6, ) -> Proposal: """Retrain the ensemble on everything measured so far and pick the next batch by a lower confidence bound.""" import numpy as np import surrogate started = time.time() smiles, packed = await load_pool(pool) index = {s: i for i, s in enumerate(smiles)} X = surrogate.unpack(packed) models = surrogate.fit_ensemble(X[[index[s] for s in train_smiles]], np.array(train_gaps), seed=round_num) mean, std = surrogate.predict(models, X) score = mean - beta * std # small predicted gap, or high uncertainty chosen = surrogate.select_batch(score, packed, {index[s] for s in exclude}, batch_size, max_similarity) def pick(i: int) -> Pick: return Pick(smiles[i], float(mean[i]), float(std[i]), float(score[i])) print(f"round {round_num}: trained on {len(train_smiles)}, batch predicted {mean[chosen].mean():.2f} eV") return Proposal(round_num, [pick(i) for i in chosen], [pick(index[s]) for s in control], len(train_smiles), float(np.median(mean)), round_s(time.time() - started)) # {{/docs-fragment propose}} # {{docs-fragment approval}} async def approval(round_num: int, proposal: Proposal, state: LoopState, timeout_s: int) -> tuple[str, float]: """Ask a scientist to approve the batch before it goes to the lab. Silence counts as approval.""" if timeout_s <= 0: return "no gate", 0.0 started = time.time() condition = await flyte.new_condition.aio( f"approve-round-{round_num}", prompt=reports.approval_prompt(proposal, state, timeout_s), prompt_type="markdown", data_type=bool, description=f"Send round {round_num}'s {len(proposal.batch)} molecules to the oracle?", timeout=timeout_s, ) try: approved = await condition.wait.aio() decision = "approved" if approved else "rejected" except flyte.errors.ConditionTimedoutError: decision = "auto-approved" # nobody answered: an unattended run keeps going return decision, round_s(time.time() - started) # {{/docs-fragment approval}} # {{docs-fragment round}} @driver_env.task(cache=flyte.Cache("auto", salt=f"{ORACLE_VERSION}+{SURROGATE_VERSION}"), retries=1) async def run_round( round_num: int, state: LoopState, pool: File, batch_size: int, beta: float, max_similarity: float, approval_timeout_s: int, seed: int, campaign: str, ) -> LoopState: """One turn of the loop. The output is the whole state, so a finished round is never run twice. The state includes the approval decision, so a cached round is not asked about again. The campaign name is part of the cache key: a run with a new campaign asks for approval afresh. """ started = time.time() smiles, _ = await load_pool(pool) rng = random.Random(seed * 1_000 + round_num) if round_num == 0: # The seed library: random molecules, measured once and shared by both arms. seed_batch = rng.sample(smiles, batch_size) results = list(await asyncio.gather(*[measure(s) for s in seed_batch])) log = RoundLog(0, "seed library", active=results, control=results) return replace(state, rounds=[replace(log, seconds=round_s(time.time() - started))]) active, control = state.measured("active"), state.measured("control") seen_control = {m.smiles for m in control} control_batch = rng.sample([s for s in smiles if s not in seen_control], batch_size) train = [m for m in active if m.ok] proposal = await propose( round_num, pool, [m.smiles for m in train], [m.gap for m in train], exclude=[m.smiles for m in active] + state.vetoed, control=control_batch, batch_size=batch_size, beta=beta, max_similarity=max_similarity, ) decision, waited = await approval(round_num, proposal, state, approval_timeout_s) log = RoundLog(round_num, decision, waited, proposal) if decision == "rejected": state = replace(state, vetoed=state.vetoed + [p.smiles for p in proposal.batch]) else: # Both arms go to the oracle at once. A molecule in both is computed once: the second # call is a cache hit. batch = [p.smiles for p in proposal.batch] results = await asyncio.gather(*[measure(s) for s in batch + control_batch]) log.active, log.control = list(results[: len(batch)]), list(results[len(batch):]) log.seconds = round_s(time.time() - started) return replace(state, rounds=state.rounds + [log]) # {{/docs-fragment round}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True, retries=2) async def discover( rounds: int = 10, batch_size: int = 64, pool_size: int = 20_000, beta: float = 1.0, max_similarity: float = 0.6, approval_timeout_s: int = 180, hit_gap: float = 1.0, seed: int = 0, campaign: str = "zinc-small-gap", ) -> File: """Run the closed loop and the random control, report both, and publish the best molecules. Rounds are cached, approvals included: rerunning with the same inputs replays the campaign without asking anyone. Pass a new ``campaign`` name to start over and be asked again. """ pool = await build_pool(pool_size, seed) state = LoopState() for r in range(rounds + 1): with flyte.group(f"round-{r}"): state = await run_round( r, state, pool, batch_size, beta, max_similarity, approval_timeout_s, seed, campaign) await flyte.report.replace.aio(reports.live(state, rounds, hit_gap, pool_size), do_flush=True) top = reports.top_molecules(state, 50) # The rounds' own durations: a resumed driver replays cached rounds in seconds, and this # still reports how long the loop took when it ran. loop_seconds = sum(r.seconds for r in state.rounds) await flyte.report.replace.aio(reports.final(state, hit_gap, pool_size, top, loop_seconds)) flyte.report.get_tab("Surrogate").replace(reports.surrogate_tab(state)) flyte.report.get_tab("Batches").replace(reports.batches_tab(state)) flyte.report.get_tab("Oracle").replace(reports.oracle_tab(state, flyte.ctx().action.run_name or "")) await flyte.report.flush.aio() path = f"{tempfile.mkdtemp()}/top_candidates.csv" reports.write_csv(top, path) summary = reports.summary(state, hit_gap) card = await artifacts.Card.create_from.aio(content=reports.card(state, top, hit_gap), format="html", card_type="data") metadata = artifacts.Metadata( name="closed-loop-top-candidates", description=f"The {len(top)} smallest-gap molecules found in {summary['calls']} GFN2-xTB calculations " f"over {pool_size:,} ZINC molecules; best {top[0]['gap_ev']:.2f} eV", kind="data", card=card, attrs={k: str(v) for k, v in summary.items()} | {"objective": "minimize GFN2-xTB HOMO-LUMO gap"}, ) return artifacts.new(await File.from_local(path), metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() if "--smoke" in sys.argv: run = flyte.run(discover, rounds=2, batch_size=16, pool_size=2_000, approval_timeout_s=60) else: run = flyte.run(discover) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/closed_loop_discovery/discovery.py* `run_round` takes the loop state and returns the next one, and it is cached. If the driver crashes in round 7, its retry calls `run_round` for rounds 0 to 6 with the same inputs, gets the cached states back in seconds, and carries on. A finished round, approval included, is never run or asked about twice. That cuts both ways. The approval decision is part of the cached output, so a later run with the same inputs replays every round, and every past approval, without asking anyone. That is what you want when a driver crashes, and not what you want when you start a new campaign on the same pool. `run_round` takes a `campaign` name as an input for that reason: launch with a new one, for example `flyte.run(discover, campaign="zinc-small-gap-2")`, and every round is proposed, approved, and recorded afresh, while molecules measured before still come from the oracle's cache. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "discover" # params = "rounds=2 batch_size=16 pool_size=2000" # /// """Closed-loop molecular discovery: a surrogate proposes, a quantum chemistry oracle measures. build_pool 20,000 drug-like molecules from ZINC250k, with fingerprints round 0: measure 64 random molecules, shared by both arms for each round: propose (warm CPU) retrain an MLP ensemble, pick 64 by a confidence bound approval (condition) a scientist approves the batch, or it auto-approves on timeout N x measure (CPU pool) GFN2-xTB HOMO-LUMO gap, cached per molecule and 64 random molecules through the same oracle, as the control arm report best gap found against oracle calls, and publish the top molecules as a dataset The objective is to find molecules with a small HOMO-LUMO gap, a cheap proxy for organic semiconductors and dyes. The oracle is real compute that can fail: conformer embedding, a GFN2-xTB geometry optimization, and a single point. Each round is a cached task whose output is the whole loop state, so a driver that crashes resumes from the last finished round, and a molecule measured once is never computed again, in this run or the next. python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules """ import asyncio import random import sys import tempfile import time from dataclasses import dataclass, field, replace import flyte import flyte.artifacts as artifacts import flyte.errors import flyte.report import reports from flyte.io import File from oracle import ORACLE_VERSION, Measurement from surrogate import SURROGATE_VERSION def round_s(x: float) -> float: return round(x, 1) ZINC_URL = ( "https://raw.githubusercontent.com/aspuru-guzik-group/chemical_vae/master/" "models/zinc_properties/250k_rndm_zinc_drugs_clean_3.csv" ) # {{docs-fragment envs}} # RDKit for molecules (its drawing code needs the X rendering libraries), tblite and ASE for # GFN2-xTB, scikit-learn for the surrogate, and unionai-reuse for the reusable environments. image = ( flyte.Image.from_debian_base(name="closed-loop-discovery", python_version=(3, 12)) .with_apt_packages("libxrender1", "libxext6", "libexpat1") .with_pip_packages("rdkit==2026.9.1", "tblite==0.8.0", "ase==3.29.0", "scikit-learn==1.9.1", "numpy==2.5.4", "unionai-reuse==0.2.1") ) CODE = ["oracle.py", "surrogate.py", "reports.py", "viz.py"] # The oracle: a warm pool of small CPU pods, one molecule per call. Every call is cached on # its SMILES string, so a molecule is measured once, ever, whichever arm or run asks for it. # "auto" caching hashes the task's own source, not the modules it imports, so the tasks that # use oracle.py and surrogate.py add those modules' versions to their cache keys (see below). oracle_env = flyte.TaskEnvironment( name="discovery-oracle", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), reusable=flyte.ReusePolicy(replicas=(2, 12), concurrency=1, idle_ttl=600, scaledown_ttl=120), env_vars={"OMP_NUM_THREADS": "2", "OMP_STACKSIZE": "1G"}, include=CODE, ) # The surrogate retrains every round on a single warm replica, which keeps its imports and # the downloaded pool between rounds. model_env = flyte.TaskEnvironment( name="discovery-model", image=image, resources=flyte.Resources(cpu=4, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=900), include=CODE, ) driver_env = flyte.TaskEnvironment( name="discovery-driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), include=CODE, depends_on=[oracle_env, model_env], ) # {{/docs-fragment envs}} # {{docs-fragment state}} @dataclass class Pick: smiles: str mean: float # predicted gap, eV std: float # ensemble spread, eV score: float # the acquisition score, mean - beta * std @dataclass class Proposal: round: int batch: list[Pick] # the active learning batch control: list[Pick] # the random control batch, with the same model's predictions train_size: int pool_median: float # median predicted gap over the whole pool fit_seconds: float @dataclass class RoundLog: round: int decision: str # "seed library", "approved", "rejected", "auto-approved", "no gate" gate_seconds: float = 0.0 proposal: Proposal | None = None active: list[Measurement] = field(default_factory=list) control: list[Measurement] = field(default_factory=list) seconds: float = 0.0 @dataclass class LoopState: rounds: list[RoundLog] = field(default_factory=list) vetoed: list[str] = field(default_factory=list) # molecules a scientist rejected def measured(self, arm: str) -> list[Measurement]: """Every measurement of one arm ("active" or "control") so far.""" return [m for r in self.rounds for m in getattr(r, arm)] # {{/docs-fragment state}} # {{docs-fragment pool}} @model_env.task(cache="auto") async def build_pool(pool_size: int = 20_000, seed: int = 0) -> File: """A random sample of neutral ZINC250k molecules, with their Morgan fingerprints.""" import csv import io import urllib.request import numpy as np from rdkit import Chem, RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize from surrogate import fingerprints RDLogger.DisableLog("rdApp.*") text = urllib.request.urlopen(ZINC_URL, timeout=120).read().decode() rows = [r["smiles"].strip() for r in csv.DictReader(io.StringIO(text))] random.Random(seed).shuffle(rows) # Gas-phase GFN2-xTB gives zwitterions and ions unphysically small gaps, so the pool keeps # neutral molecules only: neutralize what can be, and drop charged atoms other than nitro groups. uncharger, nitro = rdMolStandardize.Uncharger(), Chem.MolFromSmarts("[N+](=O)[O-]") pool, seen = [], set() for s in rows: mol = Chem.MolFromSmiles(s) if mol is None: continue mol = uncharger.uncharge(mol) charged = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) if Chem.GetFormalCharge(mol) != 0 or charged > 2 * len(mol.GetSubstructMatches(nitro)): continue smiles = Chem.MolToSmiles(mol) if smiles not in seen: seen.add(smiles) pool.append(smiles) if len(pool) == pool_size: break path = f"{tempfile.mkdtemp()}/pool.npz" np.savez_compressed(path, smiles=np.array(pool), fps=fingerprints(pool)) print(f"pool: {len(pool)} molecules from {len(rows)} in ZINC250k") return await File.from_local(path) # {{/docs-fragment pool}} async def load_pool(pool: File): import numpy as np data = np.load(await pool.download()) return [str(s) for s in data["smiles"]], data["fps"] # {{docs-fragment measure}} @oracle_env.task(cache=flyte.Cache("auto", salt=ORACLE_VERSION), retries=2) async def measure(smiles: str) -> Measurement: """Measure one molecule's HOMO-LUMO gap with GFN2-xTB. A failed calculation is a result, not an error.""" from oracle import measure_gap m = await asyncio.to_thread(measure_gap, smiles) m.measured_in = flyte.ctx().action.run_name or "" print(f"{smiles}: {'%.3f eV' % m.gap if m.ok else 'FAILED'} after {m.attempts} attempt(s) in {m.seconds:.1f}s {m.error}") return m # {{/docs-fragment measure}} # {{docs-fragment propose}} @model_env.task(cache=flyte.Cache("auto", salt=SURROGATE_VERSION)) async def propose( round_num: int, pool: File, train_smiles: list[str], train_gaps: list[float], exclude: list[str], control: list[str], batch_size: int, beta: float = 1.0, max_similarity: float = 0.6, ) -> Proposal: """Retrain the ensemble on everything measured so far and pick the next batch by a lower confidence bound.""" import numpy as np import surrogate started = time.time() smiles, packed = await load_pool(pool) index = {s: i for i, s in enumerate(smiles)} X = surrogate.unpack(packed) models = surrogate.fit_ensemble(X[[index[s] for s in train_smiles]], np.array(train_gaps), seed=round_num) mean, std = surrogate.predict(models, X) score = mean - beta * std # small predicted gap, or high uncertainty chosen = surrogate.select_batch(score, packed, {index[s] for s in exclude}, batch_size, max_similarity) def pick(i: int) -> Pick: return Pick(smiles[i], float(mean[i]), float(std[i]), float(score[i])) print(f"round {round_num}: trained on {len(train_smiles)}, batch predicted {mean[chosen].mean():.2f} eV") return Proposal(round_num, [pick(i) for i in chosen], [pick(index[s]) for s in control], len(train_smiles), float(np.median(mean)), round_s(time.time() - started)) # {{/docs-fragment propose}} # {{docs-fragment approval}} async def approval(round_num: int, proposal: Proposal, state: LoopState, timeout_s: int) -> tuple[str, float]: """Ask a scientist to approve the batch before it goes to the lab. Silence counts as approval.""" if timeout_s <= 0: return "no gate", 0.0 started = time.time() condition = await flyte.new_condition.aio( f"approve-round-{round_num}", prompt=reports.approval_prompt(proposal, state, timeout_s), prompt_type="markdown", data_type=bool, description=f"Send round {round_num}'s {len(proposal.batch)} molecules to the oracle?", timeout=timeout_s, ) try: approved = await condition.wait.aio() decision = "approved" if approved else "rejected" except flyte.errors.ConditionTimedoutError: decision = "auto-approved" # nobody answered: an unattended run keeps going return decision, round_s(time.time() - started) # {{/docs-fragment approval}} # {{docs-fragment round}} @driver_env.task(cache=flyte.Cache("auto", salt=f"{ORACLE_VERSION}+{SURROGATE_VERSION}"), retries=1) async def run_round( round_num: int, state: LoopState, pool: File, batch_size: int, beta: float, max_similarity: float, approval_timeout_s: int, seed: int, campaign: str, ) -> LoopState: """One turn of the loop. The output is the whole state, so a finished round is never run twice. The state includes the approval decision, so a cached round is not asked about again. The campaign name is part of the cache key: a run with a new campaign asks for approval afresh. """ started = time.time() smiles, _ = await load_pool(pool) rng = random.Random(seed * 1_000 + round_num) if round_num == 0: # The seed library: random molecules, measured once and shared by both arms. seed_batch = rng.sample(smiles, batch_size) results = list(await asyncio.gather(*[measure(s) for s in seed_batch])) log = RoundLog(0, "seed library", active=results, control=results) return replace(state, rounds=[replace(log, seconds=round_s(time.time() - started))]) active, control = state.measured("active"), state.measured("control") seen_control = {m.smiles for m in control} control_batch = rng.sample([s for s in smiles if s not in seen_control], batch_size) train = [m for m in active if m.ok] proposal = await propose( round_num, pool, [m.smiles for m in train], [m.gap for m in train], exclude=[m.smiles for m in active] + state.vetoed, control=control_batch, batch_size=batch_size, beta=beta, max_similarity=max_similarity, ) decision, waited = await approval(round_num, proposal, state, approval_timeout_s) log = RoundLog(round_num, decision, waited, proposal) if decision == "rejected": state = replace(state, vetoed=state.vetoed + [p.smiles for p in proposal.batch]) else: # Both arms go to the oracle at once. A molecule in both is computed once: the second # call is a cache hit. batch = [p.smiles for p in proposal.batch] results = await asyncio.gather(*[measure(s) for s in batch + control_batch]) log.active, log.control = list(results[: len(batch)]), list(results[len(batch):]) log.seconds = round_s(time.time() - started) return replace(state, rounds=state.rounds + [log]) # {{/docs-fragment round}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True, retries=2) async def discover( rounds: int = 10, batch_size: int = 64, pool_size: int = 20_000, beta: float = 1.0, max_similarity: float = 0.6, approval_timeout_s: int = 180, hit_gap: float = 1.0, seed: int = 0, campaign: str = "zinc-small-gap", ) -> File: """Run the closed loop and the random control, report both, and publish the best molecules. Rounds are cached, approvals included: rerunning with the same inputs replays the campaign without asking anyone. Pass a new ``campaign`` name to start over and be asked again. """ pool = await build_pool(pool_size, seed) state = LoopState() for r in range(rounds + 1): with flyte.group(f"round-{r}"): state = await run_round( r, state, pool, batch_size, beta, max_similarity, approval_timeout_s, seed, campaign) await flyte.report.replace.aio(reports.live(state, rounds, hit_gap, pool_size), do_flush=True) top = reports.top_molecules(state, 50) # The rounds' own durations: a resumed driver replays cached rounds in seconds, and this # still reports how long the loop took when it ran. loop_seconds = sum(r.seconds for r in state.rounds) await flyte.report.replace.aio(reports.final(state, hit_gap, pool_size, top, loop_seconds)) flyte.report.get_tab("Surrogate").replace(reports.surrogate_tab(state)) flyte.report.get_tab("Batches").replace(reports.batches_tab(state)) flyte.report.get_tab("Oracle").replace(reports.oracle_tab(state, flyte.ctx().action.run_name or "")) await flyte.report.flush.aio() path = f"{tempfile.mkdtemp()}/top_candidates.csv" reports.write_csv(top, path) summary = reports.summary(state, hit_gap) card = await artifacts.Card.create_from.aio(content=reports.card(state, top, hit_gap), format="html", card_type="data") metadata = artifacts.Metadata( name="closed-loop-top-candidates", description=f"The {len(top)} smallest-gap molecules found in {summary['calls']} GFN2-xTB calculations " f"over {pool_size:,} ZINC molecules; best {top[0]['gap_ev']:.2f} eV", kind="data", card=card, attrs={k: str(v) for k, v in summary.items()} | {"objective": "minimize GFN2-xTB HOMO-LUMO gap"}, ) return artifacts.new(await File.from_local(path), metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() if "--smoke" in sys.argv: run = flyte.run(discover, rounds=2, batch_size=16, pool_size=2_000, approval_timeout_s=60) else: run = flyte.run(discover) print(run.url) # {{/docs-fragment run}} CODE7 # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte==2.13.0", # ] # main = "discover" # params = "rounds=2 batch_size=16 pool_size=2000" # /// """Closed-loop molecular discovery: a surrogate proposes, a quantum chemistry oracle measures. build_pool 20,000 drug-like molecules from ZINC250k, with fingerprints round 0: measure 64 random molecules, shared by both arms for each round: propose (warm CPU) retrain an MLP ensemble, pick 64 by a confidence bound approval (condition) a scientist approves the batch, or it auto-approves on timeout N x measure (CPU pool) GFN2-xTB HOMO-LUMO gap, cached per molecule and 64 random molecules through the same oracle, as the control arm report best gap found against oracle calls, and publish the top molecules as a dataset The objective is to find molecules with a small HOMO-LUMO gap, a cheap proxy for organic semiconductors and dyes. The oracle is real compute that can fail: conformer embedding, a GFN2-xTB geometry optimization, and a single point. Each round is a cached task whose output is the whole loop state, so a driver that crashes resumes from the last finished round, and a molecule measured once is never computed again, in this run or the next. python discovery.py # 10 rounds of 64 over 20,000 molecules, about 45 minutes python discovery.py --smoke # 2 rounds of 16 over 2,000 molecules """ import asyncio import random import sys import tempfile import time from dataclasses import dataclass, field, replace import flyte import flyte.artifacts as artifacts import flyte.errors import flyte.report import reports from flyte.io import File from oracle import ORACLE_VERSION, Measurement from surrogate import SURROGATE_VERSION def round_s(x: float) -> float: return round(x, 1) ZINC_URL = ( "https://raw.githubusercontent.com/aspuru-guzik-group/chemical_vae/master/" "models/zinc_properties/250k_rndm_zinc_drugs_clean_3.csv" ) # {{docs-fragment envs}} # RDKit for molecules (its drawing code needs the X rendering libraries), tblite and ASE for # GFN2-xTB, scikit-learn for the surrogate, and unionai-reuse for the reusable environments. image = ( flyte.Image.from_debian_base(name="closed-loop-discovery", python_version=(3, 12)) .with_apt_packages("libxrender1", "libxext6", "libexpat1") .with_pip_packages("rdkit==2026.9.1", "tblite==0.8.0", "ase==3.29.0", "scikit-learn==1.9.1", "numpy==2.5.4", "unionai-reuse==0.2.1") ) CODE = ["oracle.py", "surrogate.py", "reports.py", "viz.py"] # The oracle: a warm pool of small CPU pods, one molecule per call. Every call is cached on # its SMILES string, so a molecule is measured once, ever, whichever arm or run asks for it. # "auto" caching hashes the task's own source, not the modules it imports, so the tasks that # use oracle.py and surrogate.py add those modules' versions to their cache keys (see below). oracle_env = flyte.TaskEnvironment( name="discovery-oracle", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), reusable=flyte.ReusePolicy(replicas=(2, 12), concurrency=1, idle_ttl=600, scaledown_ttl=120), env_vars={"OMP_NUM_THREADS": "2", "OMP_STACKSIZE": "1G"}, include=CODE, ) # The surrogate retrains every round on a single warm replica, which keeps its imports and # the downloaded pool between rounds. model_env = flyte.TaskEnvironment( name="discovery-model", image=image, resources=flyte.Resources(cpu=4, memory="8Gi"), reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=900), include=CODE, ) driver_env = flyte.TaskEnvironment( name="discovery-driver", image=image, resources=flyte.Resources(cpu=2, memory="4Gi"), include=CODE, depends_on=[oracle_env, model_env], ) # {{/docs-fragment envs}} # {{docs-fragment state}} @dataclass class Pick: smiles: str mean: float # predicted gap, eV std: float # ensemble spread, eV score: float # the acquisition score, mean - beta * std @dataclass class Proposal: round: int batch: list[Pick] # the active learning batch control: list[Pick] # the random control batch, with the same model's predictions train_size: int pool_median: float # median predicted gap over the whole pool fit_seconds: float @dataclass class RoundLog: round: int decision: str # "seed library", "approved", "rejected", "auto-approved", "no gate" gate_seconds: float = 0.0 proposal: Proposal | None = None active: list[Measurement] = field(default_factory=list) control: list[Measurement] = field(default_factory=list) seconds: float = 0.0 @dataclass class LoopState: rounds: list[RoundLog] = field(default_factory=list) vetoed: list[str] = field(default_factory=list) # molecules a scientist rejected def measured(self, arm: str) -> list[Measurement]: """Every measurement of one arm ("active" or "control") so far.""" return [m for r in self.rounds for m in getattr(r, arm)] # {{/docs-fragment state}} # {{docs-fragment pool}} @model_env.task(cache="auto") async def build_pool(pool_size: int = 20_000, seed: int = 0) -> File: """A random sample of neutral ZINC250k molecules, with their Morgan fingerprints.""" import csv import io import urllib.request import numpy as np from rdkit import Chem, RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize from surrogate import fingerprints RDLogger.DisableLog("rdApp.*") text = urllib.request.urlopen(ZINC_URL, timeout=120).read().decode() rows = [r["smiles"].strip() for r in csv.DictReader(io.StringIO(text))] random.Random(seed).shuffle(rows) # Gas-phase GFN2-xTB gives zwitterions and ions unphysically small gaps, so the pool keeps # neutral molecules only: neutralize what can be, and drop charged atoms other than nitro groups. uncharger, nitro = rdMolStandardize.Uncharger(), Chem.MolFromSmarts("[N+](=O)[O-]") pool, seen = [], set() for s in rows: mol = Chem.MolFromSmiles(s) if mol is None: continue mol = uncharger.uncharge(mol) charged = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) if Chem.GetFormalCharge(mol) != 0 or charged > 2 * len(mol.GetSubstructMatches(nitro)): continue smiles = Chem.MolToSmiles(mol) if smiles not in seen: seen.add(smiles) pool.append(smiles) if len(pool) == pool_size: break path = f"{tempfile.mkdtemp()}/pool.npz" np.savez_compressed(path, smiles=np.array(pool), fps=fingerprints(pool)) print(f"pool: {len(pool)} molecules from {len(rows)} in ZINC250k") return await File.from_local(path) # {{/docs-fragment pool}} async def load_pool(pool: File): import numpy as np data = np.load(await pool.download()) return [str(s) for s in data["smiles"]], data["fps"] # {{docs-fragment measure}} @oracle_env.task(cache=flyte.Cache("auto", salt=ORACLE_VERSION), retries=2) async def measure(smiles: str) -> Measurement: """Measure one molecule's HOMO-LUMO gap with GFN2-xTB. A failed calculation is a result, not an error.""" from oracle import measure_gap m = await asyncio.to_thread(measure_gap, smiles) m.measured_in = flyte.ctx().action.run_name or "" print(f"{smiles}: {'%.3f eV' % m.gap if m.ok else 'FAILED'} after {m.attempts} attempt(s) in {m.seconds:.1f}s {m.error}") return m # {{/docs-fragment measure}} # {{docs-fragment propose}} @model_env.task(cache=flyte.Cache("auto", salt=SURROGATE_VERSION)) async def propose( round_num: int, pool: File, train_smiles: list[str], train_gaps: list[float], exclude: list[str], control: list[str], batch_size: int, beta: float = 1.0, max_similarity: float = 0.6, ) -> Proposal: """Retrain the ensemble on everything measured so far and pick the next batch by a lower confidence bound.""" import numpy as np import surrogate started = time.time() smiles, packed = await load_pool(pool) index = {s: i for i, s in enumerate(smiles)} X = surrogate.unpack(packed) models = surrogate.fit_ensemble(X[[index[s] for s in train_smiles]], np.array(train_gaps), seed=round_num) mean, std = surrogate.predict(models, X) score = mean - beta * std # small predicted gap, or high uncertainty chosen = surrogate.select_batch(score, packed, {index[s] for s in exclude}, batch_size, max_similarity) def pick(i: int) -> Pick: return Pick(smiles[i], float(mean[i]), float(std[i]), float(score[i])) print(f"round {round_num}: trained on {len(train_smiles)}, batch predicted {mean[chosen].mean():.2f} eV") return Proposal(round_num, [pick(i) for i in chosen], [pick(index[s]) for s in control], len(train_smiles), float(np.median(mean)), round_s(time.time() - started)) # {{/docs-fragment propose}} # {{docs-fragment approval}} async def approval(round_num: int, proposal: Proposal, state: LoopState, timeout_s: int) -> tuple[str, float]: """Ask a scientist to approve the batch before it goes to the lab. Silence counts as approval.""" if timeout_s <= 0: return "no gate", 0.0 started = time.time() condition = await flyte.new_condition.aio( f"approve-round-{round_num}", prompt=reports.approval_prompt(proposal, state, timeout_s), prompt_type="markdown", data_type=bool, description=f"Send round {round_num}'s {len(proposal.batch)} molecules to the oracle?", timeout=timeout_s, ) try: approved = await condition.wait.aio() decision = "approved" if approved else "rejected" except flyte.errors.ConditionTimedoutError: decision = "auto-approved" # nobody answered: an unattended run keeps going return decision, round_s(time.time() - started) # {{/docs-fragment approval}} # {{docs-fragment round}} @driver_env.task(cache=flyte.Cache("auto", salt=f"{ORACLE_VERSION}+{SURROGATE_VERSION}"), retries=1) async def run_round( round_num: int, state: LoopState, pool: File, batch_size: int, beta: float, max_similarity: float, approval_timeout_s: int, seed: int, campaign: str, ) -> LoopState: """One turn of the loop. The output is the whole state, so a finished round is never run twice. The state includes the approval decision, so a cached round is not asked about again. The campaign name is part of the cache key: a run with a new campaign asks for approval afresh. """ started = time.time() smiles, _ = await load_pool(pool) rng = random.Random(seed * 1_000 + round_num) if round_num == 0: # The seed library: random molecules, measured once and shared by both arms. seed_batch = rng.sample(smiles, batch_size) results = list(await asyncio.gather(*[measure(s) for s in seed_batch])) log = RoundLog(0, "seed library", active=results, control=results) return replace(state, rounds=[replace(log, seconds=round_s(time.time() - started))]) active, control = state.measured("active"), state.measured("control") seen_control = {m.smiles for m in control} control_batch = rng.sample([s for s in smiles if s not in seen_control], batch_size) train = [m for m in active if m.ok] proposal = await propose( round_num, pool, [m.smiles for m in train], [m.gap for m in train], exclude=[m.smiles for m in active] + state.vetoed, control=control_batch, batch_size=batch_size, beta=beta, max_similarity=max_similarity, ) decision, waited = await approval(round_num, proposal, state, approval_timeout_s) log = RoundLog(round_num, decision, waited, proposal) if decision == "rejected": state = replace(state, vetoed=state.vetoed + [p.smiles for p in proposal.batch]) else: # Both arms go to the oracle at once. A molecule in both is computed once: the second # call is a cache hit. batch = [p.smiles for p in proposal.batch] results = await asyncio.gather(*[measure(s) for s in batch + control_batch]) log.active, log.control = list(results[: len(batch)]), list(results[len(batch):]) log.seconds = round_s(time.time() - started) return replace(state, rounds=state.rounds + [log]) # {{/docs-fragment round}} # {{docs-fragment driver}} @driver_env.task(report=True, produces_artifacts=True, retries=2) async def discover( rounds: int = 10, batch_size: int = 64, pool_size: int = 20_000, beta: float = 1.0, max_similarity: float = 0.6, approval_timeout_s: int = 180, hit_gap: float = 1.0, seed: int = 0, campaign: str = "zinc-small-gap", ) -> File: """Run the closed loop and the random control, report both, and publish the best molecules. Rounds are cached, approvals included: rerunning with the same inputs replays the campaign without asking anyone. Pass a new ``campaign`` name to start over and be asked again. """ pool = await build_pool(pool_size, seed) state = LoopState() for r in range(rounds + 1): with flyte.group(f"round-{r}"): state = await run_round( r, state, pool, batch_size, beta, max_similarity, approval_timeout_s, seed, campaign) await flyte.report.replace.aio(reports.live(state, rounds, hit_gap, pool_size), do_flush=True) top = reports.top_molecules(state, 50) # The rounds' own durations: a resumed driver replays cached rounds in seconds, and this # still reports how long the loop took when it ran. loop_seconds = sum(r.seconds for r in state.rounds) await flyte.report.replace.aio(reports.final(state, hit_gap, pool_size, top, loop_seconds)) flyte.report.get_tab("Surrogate").replace(reports.surrogate_tab(state)) flyte.report.get_tab("Batches").replace(reports.batches_tab(state)) flyte.report.get_tab("Oracle").replace(reports.oracle_tab(state, flyte.ctx().action.run_name or "")) await flyte.report.flush.aio() path = f"{tempfile.mkdtemp()}/top_candidates.csv" reports.write_csv(top, path) summary = reports.summary(state, hit_gap) card = await artifacts.Card.create_from.aio(content=reports.card(state, top, hit_gap), format="html", card_type="data") metadata = artifacts.Metadata( name="closed-loop-top-candidates", description=f"The {len(top)} smallest-gap molecules found in {summary['calls']} GFN2-xTB calculations " f"over {pool_size:,} ZINC molecules; best {top[0]['gap_ev']:.2f} eV", kind="data", card=card, attrs={k: str(v) for k, v in summary.items()} | {"objective": "minimize GFN2-xTB HOMO-LUMO gap"}, ) return artifacts.new(await File.from_local(path), metadata) # {{/docs-fragment driver}} # {{docs-fragment run}} if __name__ == "__main__": flyte.init_from_config() if "--smoke" in sys.argv: run = flyte.run(discover, rounds=2, batch_size=16, pool_size=2_000, approval_timeout_s=60) else: run = flyte.run(discover) print(run.url) # {{/docs-fragment run}} ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/closed_loop_discovery/discovery.py* ## Results A run with the defaults took 48 minutes: 10 rounds after the seed library, 64 molecules per arm per round, 704 oracle calls per arm, and 1,328 distinct molecules in all (16 molecules were picked by both arms in the same round and computed once). Each GFN2-xTB measurement took 10 seconds at the median and 58 seconds at the most. 22 of the measurements were cache hits from an earlier smoke run, which happened to sample the same molecules, and were never recomputed. | | Active learning | Random search | | --- | --- | --- | | Oracle calls | 704 | 704 | | Molecules found below 1 eV | 31 | 4 | | Smallest gap found | 0.32 eV | 0.82 eV | | Mean gap of a batch, rounds 4 to 10 | about 2.0 eV | about 2.9 eV | Both arms start from the same seed library, which held one molecule below 1 eV. Random search found 3 more in 640 calls, the rate you would expect when fewer than 1 molecule in 100 qualifies. Active learning found 30 more with the same budget. Its first two batches were no better than random, and the second was worse, with a mean gap of 3.5 eV: trained on 128 molecules, the model's uncertainty dominated the bound and it explored. From round 4 on, every batch averaged about 2 eV, and the count of small-gap molecules climbed in almost every round. ![The discovery report: molecules below 1 eV for each arm, the best gap found against oracle calls, the mean gap of each batch, and the top molecules](../../../_static/images/tutorials/closed-loop-discovery/discovery-report.png) The Surrogate tab is the honest part of the report. On the random control, which the model never chose, its error stayed between 0.7 and 0.9 eV and its rank correlation between 0.2 and 0.45: it is a poor predictor of the gap of an average molecule. On its own batches, its error fell from 1.8 eV to under 0.5 eV, because those batches are where it has learned the most. That is enough to rank the small-gap tail, which is all the loop needs. The ensemble is overconfident: at round 10, 33% of control molecules fell inside one predicted standard deviation and 53% inside two, against 68% and 95% for a calibrated model. Bootstrap ensembles of small networks are known to do this. If you need calibrated uncertainty, rescale the standard deviation with the control's residuals each round; the control set gives you the data for it for free. ![The Surrogate tab: error per round on the model's own batch and on the random control, the calibration curve, predicted against measured, and the per-round table](../../../_static/images/tutorials/closed-loop-discovery/surrogate-tab.png) The best molecule, an (E)-3-(4-nitrophenyl)acryloyl thiourea, was found in round 7. The model predicted 1.82 ยฑ 0.16 eV for it, well inside the batch but far from the 0.32 eV it measured. Most of the top 12 are nitroaromatics with an electron donor on the other side of a conjugated path. These are real push-pull chromophores, and GFN2-xTB also underestimates their gaps, so they are what you would send to a DFT calculation next, not a final answer. No calculation in the run failed, and none needed a retry. Failures are rare for neutral drug-like molecules at this level of theory. In local testing, one small-gap molecule broke a bond during the xTB optimization on its first two attempts and was measured on the third, with random coordinates and a higher electronic temperature. The handling is there for the molecules and oracles where failures are common. ### The approval gate in practice Every round opened a condition named `approve-round-N` on the run, which pauses the round and shows the Markdown prompt in the UI's signal form. Round 1 was approved with the `signal_condition` tool of the Flyte MCP server, and the others with `Condition.signal(True)` from a script, 20 to 30 seconds after they opened. Round 7 was left alone: its condition timed out after 180 seconds, the driver caught `ConditionTimedoutError`, and the round went ahead as auto-approved. The Oracle tab records each decision and how long it waited. ### Resuming a finished loop Launching the same command again produced a new run that finished in 16 seconds. Every `run_round` call was a cache hit, so none of the 11 rounds ran again, no condition was opened, and the driver rebuilt the report and republished the artifact from the cached states. A driver that crashes partway through resumes the same way, from the last round that finished. Because the run used the same `campaign`, it also reused all 10 approvals from the first run. The 50 smallest-gap molecules are published as the `closed-loop-top-candidates` artifact, a CSV with the measured orbital energies, which arm found each molecule, and what the model predicted before it was measured. Its card has the same charts and the top molecules. ### Design choices in the pool, the oracle, and the image - **The pool.** The pool neutralizes molecules and keeps only nitro groups as charged atoms. In the gas phase, GFN2-xTB gives zwitterions such as amino acids gaps near 0.1 eV, and those artifacts would fill the top of the ranking. - **The oracle.** Each measurement runs a conformer search and an xTB geometry optimization, about 10 seconds of real compute, so the gaps depend on a converged structure. A single-point calculation on a force-field geometry takes 20 milliseconds, which is a table lookup in all but name. - **The drawings.** RDKit's drawing code loads `libXrender` and `libexpat`, which the slim Debian base image leaves out. Without them the report falls back to SMILES strings. The image installs them with `with_apt_packages`. ## At real scale - **A real oracle.** Swap `measure_gap` for a DFT calculation, a docking run, or a call to a lab scheduler. A DFT oracle needs bigger replicas and longer timeouts; nothing else in the loop changes. - **A bigger library.** Enamine REAL has billions of molecules. Score the pool in shards with a fan-out of `propose` tasks, and keep the fingerprints in a `flyte.io.DataFrame`. - **A better surrogate.** Replace the MLP ensemble with a graph neural network ensemble on a GPU. `propose` is the only task that changes. - **Multi-fidelity.** Send cheap GFN2-xTB results through the loop, and let the approval gate forward the best few to DFT, the way a lab triages before synthesis. ## Related - **Tasks > Build tasks > External conditions** - **Tasks > Configure tasks > Reusable containers** - **Tasks > Configure tasks > Caching** - **Tasks > Build tasks > Reports** - **Artifacts > Publish your own artifacts** === PAGE: https://www.union.ai/docs/v2/union/tutorials/computer-vision === Image and vision-language model workloads. # Computer vision Tutorials for image and vision-language model workloads. ### **Computer vision > Fine-tuning a VLM** Adapt Qwen2.5-VL to occluded image classification by training a 10K-parameter adapter with multi-node DeepSpeed, recovery checkpoints you can resume from, and live training dashboards. ### **Computer vision > RT-DETR object detection** Fine-tune RT-DETRv2 on a COCO dataset with live training charts, mAP evaluation, and bounding-box demos. ### **Computer vision > Multimodal retrieval evaluation** Benchmark ColPali, SigLIP, and OCR+BM25 visual document retrieval on ViDoRe with warm GPU containers, dynamic batching, and an interactive report. ## Subpages - **Computer vision > Fine-tuning a VLM** - Adapt Qwen2.5-VL to occluded image classification by training a 10K-parameter adapter with multi-node DeepSpeed, recovery checkpoints you can resume from, and live training dashboards. - **Computer vision > Multimodal retrieval evaluation** - Benchmark ColPali, SigLIP, and OCR+BM25 visual document retrieval on ViDoRe with warm GPU containers, dynamic batching, and an interactive report. - **Computer vision > RT-DETR object detection** - Fine-tune RT-DETRv2 on a COCO dataset with live training charts, mAP evaluation, and bounding-box demos. === PAGE: https://www.union.ai/docs/v2/union/tutorials/computer-vision/qwen-vl-finetuning === Adapt Qwen2.5-VL to occluded image classification by training a 10K-parameter adapter with multi-node DeepSpeed, recovery checkpoints you can resume from, and live training dashboards. # Fine-tuning a VLM Large vision-language models like Qwen2.5-VL are remarkably capable out of the box. But adapting one to a specialized task raises an immediate question: do you really need to update 3 billion parameters? Usually, no. The **frozen backbone pattern** is a practical alternative: keep all pretrained weights frozen and train only a small, task-specific adapter inserted before the vision encoder. The adapter learns to transform its input in a way that makes the frozen model perform well on your task without touching the underlying billions of parameters. The result is faster training, lower memory pressure, and a much smaller set of weights to store and version. This tutorial makes that pattern concrete. We take a partially-occluded image classification task (CIFAR-10 images with random black rectangles covering about 5 to 20% of the frame) and train a tiny Conv2d adapter to "see through" the occlusion before the frozen VLM processes it. The adapter has approximately **10,500 trainable parameters**. The backbone has 3 billion. The machine learning is interesting, but the real focus here is on shipping a production-grade training pipeline: - **Multi-node distributed training** across 2 nodes ร— 4 GPUs using PyTorch Elastic and DeepSpeed Stage 2 - **Automatic fault tolerance**: checkpoints upload to object storage after every validation epoch; if training fails, the pipeline returns the last known-good checkpoint instead of crashing - **Live observability**: a streaming HTML dashboard in the Flyte UI updates in real-time as training runs, no separate monitoring infrastructure required - **Cached data preparation**: dataset processing runs once and is reused across all reruns - **Clean task isolation**: each stage runs with exactly the resources it needs, nothing more > [!NOTE] > Full code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning). ## Overview The pipeline has four tasks with clearly defined responsibilities: 1. **Dataset preparation** (`prepare_occlusion_dataset`): Downloads CIFAR-10, applies random occlusions, and writes image manifests as streaming JSONL files to object storage. Runs on CPU and is cached, so it only runs once regardless of how many times you rerun the pipeline with the same config. 2. **Multi-node training** (`train_qwen_adapter_multinode`): Runs PyTorch Lightning with DeepSpeed Stage 2 across 2 nodes ร— 4 L40s GPUs. Only the adapter trains; the 3B backbone stays frozen. 3. **Evaluation** (`evaluate_qwen_adapter`): Loads the saved adapter, runs inference on validation examples, and produces a predictions report. Runs on a single GPU. 4. **Driver** (`qwen_vl_multinode_deepspeed`): The pipeline entry point. Orchestrates the three tasks above, supplies the WandB settings for the training run, handles recovery from training failures, and produces a final HTML report in the Flyte UI. Why this separation? It mirrors how production pipelines should be structured. Data prep is cheap and deterministic so we cache it. Training is expensive and failure-prone so we isolate it with fault tolerance. Evaluation needs different hardware than training. The driver is pure coordination, so it gets minimal resources. ## Implementation ### Setting up the environment Different tasks need different compute. Flyte's `TaskEnvironment` is how you declare exactly what each task needs. First, define the container images. Training needs a full CUDA stack with ML libraries, driver compatibility, and DeepSpeed's build tools: ``` gpu_image = ( flyte.Image.from_base("nvidia/cuda:12.8.0-cudnn-devel-ubuntu22.04") .clone(name="qwen_vl_multinode_deepspeed", python_version=(3, 13), extendable=True) .with_apt_packages("build-essential") .with_pip_packages( "torch==2.9.1", "torchvision==0.24.1", "lightning==2.6.1", "transformers==4.57.3", "deepspeed==0.18.8", "datasets==4.4.1", "pillow==11.3.0", "flyteplugins-pytorch>=2.0.11", "flyteplugins-jsonl>=2.0.11", "flyteplugins-wandb>=2.0.11", ) ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/config.py* `from_base` starts from the official NVIDIA CUDA image, giving you NCCL, cuDNN, and the right driver headers out of the box. `with_apt_packages("build-essential")` is required because DeepSpeed compiles CUDA kernels at first use and without build tools, it silently falls back to slower CPU implementations. The non-GPU image for data preparation and orchestration is much lighter: ``` non_gpu_image = flyte.Image.from_debian_base( name="qwen_vl_multinode_deepspeed_non_gpu" ).with_pip_packages( "flyteplugins-pytorch>=2.0.11", "flyteplugins-jsonl>=2.0.11", "flyteplugins-wandb>=2.0.11", "lightning==2.6.1", "datasets==4.4.1", "pillow==11.3.0", "torchvision==0.24.1", ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/config.py* With images defined, each task gets its own resource declaration: ``` dataset_env = flyte.TaskEnvironment( name="qwen_vl_dataset_prep", image=non_gpu_image, resources=flyte.Resources(cpu=5, memory="15Gi"), cache="auto", ) training_env = flyte.TaskEnvironment( name="qwen_vl_multinode_training", image=gpu_image, resources=flyte.Resources( cpu=42, memory="256Gi", gpu=f"L40s:{DEVICES_PER_NODE}", shm="16Gi", ), plugin_config=Elastic(nnodes=NUM_NODES, nproc_per_node=DEVICES_PER_NODE), secrets=[ flyte.Secret(key="wandb_api_key", as_env_var="WANDB_API_KEY") ], # TODO: update with your own secret key env_vars={ "TORCH_DISTRIBUTED_DEBUG": "INFO", "NCCL_DEBUG": "WARN", "TOKENIZERS_PARALLELISM": "false", "CUDA_HOME": "/usr/local/cuda", "DS_SKIP_CUDA_CHECK": "1", }, ) evaluation_env = flyte.TaskEnvironment( name="qwen_vl_adapter_eval", image=gpu_image, resources=flyte.Resources(cpu=16, memory="64Gi", gpu="L40s:1"), cache="auto", ) driver_env = flyte.TaskEnvironment( name="qwen_vl_multinode_driver", image=non_gpu_image, resources=flyte.Resources(cpu=2, memory="4Gi"), depends_on=[dataset_env, training_env, evaluation_env], ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/config.py* A few things worth noting here: - **`Elastic(nnodes=2, nproc_per_node=4)`**: Flyte's integration with PyTorch's elastic launch. It handles process spawning (one process per GPU), rank assignment, and distributed environment setup (master address, world size, rendezvous) without any shell scripting or manual `torchrun` invocations. - **`shm="16Gi"`**: Shared memory is required for NCCL inter-GPU communication on the same node. Without it, you'll see cryptic errors from the communication library when training starts. - **`cache="auto"`**: The dataset preparation task is cached by input hash. Running the pipeline twice with the same hyperparameters skips it entirely on the second run. - **`depends_on`**: The driver task declares that each worker image must finish building before it starts, ensuring containers are ready before the driver begins orchestrating. - **`secrets`**: The WandB API key is injected from Flyte's secret store as an environment variable. No credentials in code. All training hyperparameters flow through a single typed dataclass: ``` @dataclass class Config: model_name: str = DEFAULT_MODEL_NAME image_size: int = IMAGE_SIZE max_train_samples: int = 1024 max_val_samples: int = 256 epochs: int = 8 per_device_batch_size: int = 1 target_global_batch_size: int = 16 learning_rate: float = 2e-4 weight_decay: float = 1e-2 reconstruction_loss_weight: float = 0.35 report_every_n_steps: int = 10 num_workers: int = 4 max_length: int = 512 eval_examples: int = 16 train_occlusion_min: float = 0.22 train_occlusion_max: float = 0.42 eval_occlusion_min: float = 0.28 eval_occlusion_max: float = 0.45 seed: int = 7 def to_dict(self) -> dict: return asdict(self) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/config.py* Using a dataclass rather than scattered constants or argparse arguments means the full config is serializable, can be stored in artifact metadata alongside the model checkpoint, and flows cleanly as a typed input between tasks. The `to_dict()` method serializes it for WandB logging. ### Preparing the dataset The dataset task handles everything: downloading CIFAR-10, generating occlusions, and writing the manifests. ``` @dataset_env.task async def prepare_occlusion_dataset(config: Config) -> DatasetArtifacts: from PIL import Image from torchvision.datasets import CIFAR10 from flyte.io import Dir from flyteplugins.jsonl import JsonlFile import random rng = random.Random(config.seed) images_dir = Path("/tmp/qwen_vl_occlusion_images") train_images_dir = images_dir / "train" / "images" val_images_dir = images_dir / "validation" / "images" train_images_dir.mkdir(parents=True, exist_ok=True) val_images_dir.mkdir(parents=True, exist_ok=True) prompt = ( "The image may be partially occluded. " "Answer with exactly one CIFAR-10 class label: " + ", ".join(CLASS_NAMES) + ". What is the main object?" ) async def export_split( dataset, split_name: str, limit: int, local_image_dir: Path, occ_min: float, occ_max: float, ): out = JsonlFile.new_remote(f"{split_name}_manifest.jsonl") async with out.writer() as writer: for idx in range(limit): pil_image, label_idx = dataset[idx] resized = pil_image.resize( (config.image_size, config.image_size), resample=Image.Resampling.BICUBIC, ) rel_path = f"{split_name}/images/{split_name}-{idx:05d}.png" resized.save(local_image_dir / f"{split_name}-{idx:05d}.png") occlusion = build_occlusion_box( width=config.image_size, height=config.image_size, rng=rng, min_fraction=occ_min, max_fraction=occ_max, ) await writer.write( { "image_path": rel_path, "label": CLASS_NAMES[label_idx], "label_index": int(label_idx), "prompt": prompt, "occlusion": occlusion, } ) return out train_dataset = CIFAR10(root="/tmp/cifar10", train=True, download=True) val_dataset = CIFAR10(root="/tmp/cifar10", train=False, download=True) train_manifest = await export_split( train_dataset, "train", config.max_train_samples, train_images_dir, config.train_occlusion_min, config.train_occlusion_max, ) val_manifest = await export_split( val_dataset, "validation", config.max_val_samples, val_images_dir, config.eval_occlusion_min, config.eval_occlusion_max, ) return DatasetArtifacts( train_manifest=train_manifest, val_manifest=val_manifest, images=await Dir.from_local(str(images_dir)), ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/data.py* Each image gets a randomly-placed black rectangle. The rectangle's width and height are each 22 to 42% of the image side during training and 28 to 45% during evaluation, so it covers about 5 to 18% of the image area in training and 8 to 20% in evaluation. The occlusion is deliberately harder at eval time to test how robust the adapter is. The bounding box coordinates are written into each manifest record alongside the image path and ground-truth label, so the training task can reconstruct the binary occlusion mask as the adapter's fourth input channel. Two Flyte primitives handle data persistence without any manual storage management: - **`JsonlFile.new_remote()`** opens a streaming writer that writes directly to remote object storage. The training task reads records back via `jf.iter_records_sync()`, so no local file paths and S3 credentials to manage. - **`Dir.from_local()`** uploads the local images directory to object storage and returns a typed handle. The training task downloads it to a local path via `Dir.download_sync()`. Because `cache="auto"` is set on this task, dataset preparation runs once. Subsequent reruns with the same config skip it entirely. ### The adapter Here's the entire trainable component of the model with `~10,500` parameters: ``` class ResidualOcclusionAdapter(nn.Module): def __init__(self, hidden_channels: int = 32): super().__init__() self.net = nn.Sequential( nn.Conv2d(4, hidden_channels, kernel_size=3, padding=1), nn.GELU(), nn.Conv2d(hidden_channels, hidden_channels, kernel_size=3, padding=1), nn.GELU(), nn.Conv2d(hidden_channels, 3, kernel_size=1), nn.Tanh(), ) self.gate = nn.Parameter(torch.tensor(0.10)) def forward( self, pixel_values: torch.Tensor, occlusion_mask: torch.Tensor ) -> torch.Tensor: if pixel_values.ndim != 4: raise ValueError( "ResidualOcclusionAdapter expects dense image tensors with shape " f"(B, C, H, W), but received {tuple(pixel_values.shape)}." ) if occlusion_mask.ndim == 3: occlusion_mask = occlusion_mask.unsqueeze(1) adapter_input = torch.cat( [pixel_values, occlusion_mask.to(pixel_values.dtype)], dim=1, ) residual = self.net(adapter_input) return pixel_values + torch.tanh(self.gate) * residual ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/model.py* The adapter takes the occluded image (3 channels) concatenated with the binary occlusion mask (1 channel) as a 4-channel input. It predicts a residual correction through a small convolutional network, then adds that correction back to the original pixels. The learnable `gate` scalar, initialized to `0.10`, controls how strongly the adapter modifies the image. It starts as a near-identity transformation and gradually grows during training as the adapter gains confidence. The adapter is plugged into Qwen2.5-VL via a Lightning module: ``` class QwenVLAdapterModule(L.LightningModule): def __init__( self, model_name: str, learning_rate: float, weight_decay: float, reconstruction_loss_weight: float, ): super().__init__() from transformers import Qwen2_5_VLForConditionalGeneration self.save_hyperparameters() self.adapter = ResidualOcclusionAdapter() self.backbone = Qwen2_5_VLForConditionalGeneration.from_pretrained( model_name, torch_dtype=torch.bfloat16, attn_implementation="sdpa", ) self.backbone.requires_grad_(False) self.backbone.gradient_checkpointing_enable() # DeepSpeed checkpoints only persist the trainable adapter weights when # `exclude_frozen_parameters=True`. On resume we rebuild the frozen # backbone from Hugging Face and load the checkpoint non-strictly. self.strict_loading = False self.total_params, self.trainable_params = count_parameters(self) self.example_input_array = None self.vision_patch_size = int(self.backbone.config.vision_config.patch_size) self.temporal_patch_size = int( getattr(self.backbone.config.vision_config, "temporal_patch_size", 1) ) ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/model.py* The key line is `self.backbone.requires_grad_(False)`. This freezes all 3 billion backbone parameters which means only the adapter's ~10,500 weights receive gradients. `gradient_checkpointing_enable()` trades compute for memory: instead of keeping the frozen backbone's intermediate activations in GPU memory during the backward pass, they're recomputed on the fly. This is critical when a 3B model is sitting in GPU memory alongside your optimizer state. `strict_loading = False` handles an important DeepSpeed checkpoint detail. When `exclude_frozen_parameters=True` is set on the strategy, DeepSpeed only saves the adapter weights in checkpoints, not the 3B frozen backbone. On resume, the checkpoint won't contain backbone weights, so loading must be non-strict. The `on_load_checkpoint` hook fills in the missing backbone weights from the freshly-loaded HuggingFace model, combining the best of both worlds: small checkpoints and a fully initialized model. The training loss combines two objectives: ``` def _forward_losses( self, batch: dict[str, torch.Tensor] ) -> dict[str, torch.Tensor]: backbone_dtype = next(self.backbone.parameters()).dtype if batch["pixel_values"].ndim == 2: if "image_grid_thw" not in batch: raise ValueError( "Packed Qwen pixel values require `image_grid_thw` to reconstruct " "dense images for the Conv2d adapter." ) grid_thw = batch["image_grid_thw"] dense_pixels = packed_pixels_to_dense_images( batch["pixel_values"].to(dtype=backbone_dtype), grid_thw, patch_size=self.vision_patch_size, temporal_patch_size=self.temporal_patch_size, ) clean_pixels = packed_pixels_to_dense_images( batch["clean_pixel_values"].to(dtype=backbone_dtype), grid_thw, patch_size=self.vision_patch_size, temporal_patch_size=self.temporal_patch_size, ) adapted_dense = self.adapter(dense_pixels, batch["occlusion_mask"]) adapted_pixels = dense_images_to_packed_pixels( adapted_dense, grid_thw, patch_size=self.vision_patch_size, temporal_patch_size=self.temporal_patch_size, ) else: clean_pixels = batch["clean_pixel_values"].to(dtype=backbone_dtype) adapted_dense = self.adapter( batch["pixel_values"].to(dtype=backbone_dtype), batch["occlusion_mask"], ) adapted_pixels = adapted_dense forward_kwargs = { "input_ids": batch["input_ids"], "attention_mask": batch["attention_mask"], "pixel_values": adapted_pixels, "labels": batch["labels"], } if "image_grid_thw" in batch: forward_kwargs["image_grid_thw"] = batch["image_grid_thw"] outputs = self.backbone(**forward_kwargs) clean_pixels = clean_pixels.to( device=adapted_pixels.device, dtype=backbone_dtype ) occlusion_mask = batch["occlusion_mask"].to( device=adapted_pixels.device, dtype=backbone_dtype, ) if occlusion_mask.ndim == 3: occlusion_mask = occlusion_mask.unsqueeze(1) if occlusion_mask.shape[-2:] != adapted_dense.shape[-2:]: occlusion_mask = F.interpolate( occlusion_mask, size=adapted_dense.shape[-2:], mode="nearest", ) reconstruction_error = (adapted_dense - clean_pixels).abs() * occlusion_mask mask_denominator = (occlusion_mask.sum() * adapted_dense.shape[1]).clamp_min( 1.0 ) reconstruction_loss = reconstruction_error.sum() / mask_denominator total_loss = ( outputs.loss + self.hparams.reconstruction_loss_weight * reconstruction_loss ) return { "total_loss": total_loss, "lm_loss": outputs.loss, "reconstruction_loss": reconstruction_loss, } ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/model.py* The **language modeling loss** (cross-entropy on the predicted class label tokens) drives the model to produce correct answers. The **reconstruction loss** (mean absolute error between the adapter's output and the clean image, computed only in the occluded region) pushes the adapter to actually restore the missing pixels rather than finding a representation shortcut. Without it, the adapter could overfit the frozen backbone's quirks and produce correct tokens while generating noise in the masked region. The `reconstruction_loss_weight` (default `0.35`) balances these two objectives. Because Qwen2.5-VL's preprocessor packs image patches into a flat `(num_patches, patch_dim)` tensor, the adapter must unpack this into a spatial `(B, C, H, W)` tensor, apply the convolutions, then repack. The `packed_pixels_to_dense_images` and `dense_images_to_packed_pixels` utilities in `model.py` handle this format conversion transparently. ### Multi-node training with DeepSpeed The training task is a standard PyTorch Lightning training loop with distributed infrastructure handled by Flyte and DeepSpeed: CODE6 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/tasks.py* The `@wandb_init` decorator starts a WandB run with `wandb.init`, using the settings from the `wandb_config` context created in the driver task. With the default settings, only global rank 0 starts a run. The task body retrieves that run with `get_wandb_run()` and passes it to the trainer as a `WandbLogger` (other ranks get no run and train without a logger). The `report=True` flag on the task decorator enables Flyte Reports for live dashboard streaming from this task. ![Live Training](../../../_static/images/tutorials/qwen-vl-finetuning/live_training_graph.png) ![Live Training Contd](../../../_static/images/tutorials/qwen-vl-finetuning/losses.png) DeepSpeed Stage 2 shards optimizer states and gradients across GPUs, reducing per-GPU memory usage significantly. The critical configuration flag here is `exclude_frozen_parameters=True`: CODE7 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/tasks.py* Without `exclude_frozen_parameters=True`, DeepSpeed would shard and checkpoint the frozen backbone weights too, producing enormous checkpoint files, slow checkpoint saves, and unnecessary communication overhead. With it, only the adapter participates in sharding and checkpointing. The backbone is loaded independently on each worker from HuggingFace. Gradient accumulation is computed automatically to hit the target global batch size regardless of how many GPUs are actually running: CODE8 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/tasks.py* With 2 nodes ร— 4 GPUs ร— per-device batch size 1, the effective per-step batch is 8. To reach the default target of 16, the trainer accumulates over 2 steps. Change `NUM_NODES` or `per_device_batch_size` and the calculation adjusts automatically. The trainer brings everything together: CODE9 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/tasks.py* `precision="bf16-mixed"` uses BFloat16, which matches FP32's dynamic range (unlike FP16), so you don't need loss scaling. This is the standard choice for modern VLM training. `benchmark=True` runs cuDNN autotuning on the first batch to select the fastest kernels for your specific input sizes. ### Fault tolerance and recovery Multi-node GPU jobs fail. Hardware hiccups, spot instance preemptions, NCCL timeouts, memory spikes, etc. and the question is when, not if. This pipeline handles it with a two-part system. After every validation epoch, the `RecoveryArtifactCallback` calls `trainer.save_checkpoint()` to write a DeepSpeed checkpoint directory, then uploads all shard files to the recovery URI. Each node's local rank 0 uploads its own shards; global rank 0 uploads the metadata files (`metrics.json`, `summary.json`). A distributed barrier between save and upload ensures all workers finish before training continues. If training fails, the driver task catches the error and returns the last recovery artifact instead of propagating the failure: CODE10 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/tasks.py* A failed run still produces useful output: the latest checkpoint saved before the failure (`latest.ckpt`, not the best-scoring checkpoint), along with a partial training report. To resume from that point, pass the recovery artifact as `resume_training_artifacts` on the next run. The training task downloads it, finds the most recent `.ckpt` file, and passes it to `trainer.fit()` as `ckpt_path`. Training picks up at the last saved epoch with optimizer state and metrics history intact. The recovery URI is constructed from the configurable base path and the run name: CODE11 This means each run gets its own recovery location, so you can identify exactly which run a checkpoint came from. ### Live observability `flyte.report` lets you push HTML content directly into the Flyte UI during task execution, with no separate monitoring infrastructure. The `LiveTrainingReportCallback` uses this to stream training metrics in real-time: CODE12 *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/qwen_vl_frozen_backbone_finetuning/callbacks.py* `on_train_start` (see the full code) initializes the dashboard with an SVG loss chart and an HTML metrics table. Every `report_every_n_steps` training steps, `_push_update` serializes the latest metrics into a `

Visual Document Retrieval โ€” Experiment Comparison

ViDoRe benchmark · {len(report.results)} experiment(s)

{len(report.results)}
Experiments
{best.config.name}
Best by Recall@K
{best.metrics.recall_at_k:.3f}
Best Recall@{best.metrics.k}
{best.metrics.ndcg_at_k:.3f}
Best NDCG@{best.metrics.k}
{best.metrics.mrr:.3f}
Best MRR

Metrics by Experiment

Ranked Results

{table_rows}
ExperimentModel Recall@KNDCG@KMRRK
""" await flyte.report.replace.aio(html) await flyte.report.flush.aio() # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Experiment orchestration # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment run_experiment}} @driver.task async def run_experiment(config: ExperimentConfig, dataset: PageDataset) -> ExperimentResult: """ End-to-end retrieval pipeline for a single ExperimentConfig. Flyte v2's dynamic execution means this driver task can call GPU tasks (index_colpali, search_colpali) based on the runtime value of config.model โ€” no static DAG wiring required. The if/elif is plain Python; Flyte schedules the selected sub-tasks on the appropriate environment. Caching: two experiments that share the same model and corpus (e.g. ColPali at top_k=5 and top_k=10) will hit the same cached index. GPU work is paid at most once per (model, corpus) pair across all experiments. Search queries are sharded into chunks of SEARCH_SHARD_SIZE and dispatched as concurrent task invocations. All shards land on the single warm container (replicas=1) and feed the same DynamicBatcher simultaneously, keeping the GPU saturated throughout search rather than processing one large sequential batch from a single caller. flyte.group wraps each experiment in a named span in the Flyte UI, making it easy to compare latencies and drill into individual runs. """ SEARCH_SHARD_SIZE = 256 with flyte.group(config.name): if config.model == RetrievalModel.COLPALI: index_file = await index_colpali(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_colpali(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] elif config.model == RetrievalModel.SIGLIP: index_file = await index_siglip(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_siglip(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] else: # RetrievalModel.OCR_BM25 page_texts = await extract_page_texts(dataset.page_files) results = await search_bm25(page_texts, dataset.page_ids, dataset.queries, config.top_k) metrics = await evaluate(results, dataset.queries, config.top_k) return ExperimentResult(config=config, metrics=metrics) # {{/docs-fragment run_experiment}} # {{docs-fragment compare_experiments}} @driver.task async def compare_experiments( configs: list[ExperimentConfig], subset: str = "docvqa", max_pages: int = 200, ) -> ComparisonReport: """ Fan out over all experiment configs and return a ranked comparison table. The dataset is loaded once and shared across all experiments. Each config runs as a concurrent Flyte task via asyncio.gather. Experiments that share a model reuse the cached index โ€” you only pay GPU time for new work. On completion, generate_report emits an interactive Chart.js HTML report visible directly in the Flyte execution detail page. Default dataset: vidore_v3_finance_en (~2 942 corpus pages, 1 854 queries) with max_pages=2 000 to exercise the GPU pipeline at scale. """ dataset = await load_vidore_pages(subset=subset, max_pages=max_pages) # All experiments launch concurrently. Shared cached outputs (same model, # same corpus) are served from cache rather than recomputed. experiment_coros = [run_experiment(config=cfg, dataset=dataset) for cfg in configs] results: list[ExperimentResult] = list(await asyncio.gather(*experiment_coros)) report = ComparisonReport(results=results) print(report.summary()) best = report.best_by("recall_at_k") print(f"\nBest by Recall@{best.metrics.k}: {best.config.name}") # Emit the interactive HTML report in the Flyte UI. await generate_report(report) return report # {{/docs-fragment compare_experiments}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Entry point # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if __name__ == "__main__": flyte.init_from_config() # Define the experiment grid. Each ExperimentConfig is one point in the # design space. Adding a new model or varying top_k is one line here โ€” # no task code changes required. # # ColPali appears twice with different top_k values. The cache ensures # index_colpali runs only once and both experiments share that result. # {{docs-fragment grid}} configs = [ ExperimentConfig(name="colpali-top5", model=RetrievalModel.COLPALI, top_k=5), ExperimentConfig(name="colpali-top10", model=RetrievalModel.COLPALI, top_k=10), ExperimentConfig(name="siglip-top5", model=RetrievalModel.SIGLIP, top_k=5), ExperimentConfig(name="ocr-bm25-top5", model=RetrievalModel.OCR_BM25, top_k=5), ] # {{/docs-fragment grid}} run = flyte.with_runcontext().run( compare_experiments, configs=configs, subset="vidore_v3_finance_en", max_pages=2000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multimodal-retrieval-evaluation/retrieval_eval.py* The Python dependencies (ColPali, transformers, docTR, etc.) are declared in the `uv` script header at the top of the file. ## Define the task environments Each model gets its own GPU environment so their warm-container pools scale independently. The ColPali and SigLIP environments use `ReusePolicy` to keep model weights resident; the driver coordinates orchestration, BM25, evaluation, and reporting. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "colpali-engine>=0.3.1", # "transformers>=4.41", # "sentencepiece>=0.2", # "torch>=2.0", # "pillow>=10", # "datasets>=2.18", # "rank-bm25>=0.2", # "numpy>=1.26", # "python-doctr[torch]>=0.8", # "pydantic>=2.0", # "flyte>=2.0.0", # ] # /// """ Multimodal Retrieval Evaluation Pipeline This tutorial is an experiment framework for benchmarking visual document retrieval approaches on the ViDoRe benchmark. Each experiment is defined by an ExperimentConfig; the pipeline fans them out as concurrent Flyte tasks and returns a ranked comparison table with an interactive HTML report. The corpus is a set of PDF page images; queries are plain-text questions. Each retrieval method must find the page that answers each question โ€” no text is provided to the model, only the raw image. ColPali-v1.2 โ€” patch-level multi-vector embeddings from a VLM (PaliGemma). No OCR. The model produces one vector per image patch (~1024 per page). MaxSim late-interaction scoring finds the best matching patch for each query token. SigLIP-SO400M โ€” single global embedding per page from Google's 2023 CLIP successor. One matrix multiply per query; fast and effective but a single vector cannot localise fine-grained regions. OCR + BM25 โ€” text-only baseline. doctr (GPU OCR) extracts text in batches, BM25 matches keywords. Strong on text-dense pages; fails on charts, tables, and figures where content is visual. """ import asyncio import enum import json import math import os import tempfile from functools import lru_cache from io import BytesIO from itertools import islice import numpy as np from PIL import Image as PILImage from pydantic import BaseModel from rank_bm25 import BM25Okapi from extras import DynamicBatcher import flyte import flyte.report from flyte.io import File # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Environments # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One Docker image for all tasks. The PEP 723 header defines Python deps. # ca-certificates is required for HTTPS calls to HuggingFace and blob stores. # {{docs-fragment image}} image = ( flyte.Image.from_uv_script(__file__, name="vidore-eval-v2") .with_apt_packages("ca-certificates", "libxcb1", "libgl1", "libglib2.0-0") # unionai-reuse installs the unionai-actor-bridge binary required by ReusePolicy. # Without it every reusable container exits with StartError (exit code 128). .with_pip_packages("unionai-reuse>=0.1.11") ) # {{/docs-fragment image}} # GPU environment for ColPali image encoding and search. # # ReusePolicy keeps up to 3 warm GPU containers alive between task calls. # Without it, every task invocation cold-starts a new container and downloads # ColPali-v1.2 (~7 GB) from scratch. With it, the container โ€” and the model # weights already loaded into VRAM โ€” is reused for the next task dispatch. # # replicas=1 single warm container โ€” all concurrent shard calls land # here so they share one DynamicBatcher process # concurrency=8 up to 8 query-shard tasks run simultaneously on the # container, all feeding the same DynamicBatcher queue # idle_ttl=120 keep alive 2 min after the last task finishes # scaledown_ttl=60 scale to zero after 1 min of complete inactivity # {{docs-fragment envs}} colpali_indexer = flyte.TaskEnvironment( name="vidore-colpali-indexer", image=image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="A10G:1"), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for SigLIP image encoding and search. # # Separate from the ColPali environment so each model's warm containers # are managed independently โ€” ColPali and SigLIP experiments can scale # without contending for the same pool of reusable containers. siglip_indexer = flyte.TaskEnvironment( name="vidore-siglip-indexer", image=image, resources=flyte.Resources(cpu=4, memory="8Gi", gpu=1), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for doctr OCR. doctr runs DBNet (detection) + CRNN (recognition) # in batches on GPU โ€” much faster than CPU Tesseract. # No ReusePolicy needed: the result is cached, so this task runs at most once. ocr_engine = flyte.TaskEnvironment( name="vidore-ocr-engine", image=image, resources=flyte.Resources(cpu=4, memory="20Gi", gpu=1), ) # Driver: orchestration, BM25 search, evaluation, and reporting. # depends_on ensures the shared Docker image is built before all environments # try to schedule tasks. driver = flyte.TaskEnvironment( name="vidore-driver", image=image, resources=flyte.Resources(cpu=2, memory="12Gi"), depends_on=[colpali_indexer, siglip_indexer, ocr_engine], ) # {{/docs-fragment envs}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Configuration types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment config_types}} class RetrievalModel(str, enum.Enum): """Retrieval backend to evaluate.""" COLPALI = "colpali-v1.2" # multi-vector patch embeddings, MaxSim SIGLIP = "siglip-so400m" # single-vector global embedding, cosine sim OCR_BM25 = "ocr+bm25" # text extracted by Tesseract, ranked by BM25 class ExperimentConfig(BaseModel): """ All knobs for one retrieval experiment. Passed as a typed Flyte input. Because ExperimentConfig is a Pydantic model, Flyte serialises it alongside every task output โ€” so you can always reconstruct which config produced which metric without maintaining a separate log. """ name: str # human-readable label shown in the comparison table model: RetrievalModel top_k: int = 5 # number of pages to retrieve per query # {{/docs-fragment config_types}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Data types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment data_types}} class PageQuery(BaseModel): """One retrieval query with its ground-truth page.""" query_id: str text: str # e.g. "What was revenue growth in Q3?" relevant_page_id: str # one correct page per query class PageDataset(BaseModel): """ A corpus of document page images paired with text queries. page_ids: unique page identifiers (derived from ViDoRe image filenames). page_files: the same pages stored in Flyte's blob store as JPEG File handles. Tasks read images directly from here; no live HTTP. queries: text questions with ground-truth page IDs for evaluation. """ page_ids: list[str] page_files: list[File] queries: list[PageQuery] class Config: arbitrary_types_allowed = True class RetrievalResult(BaseModel): query_id: str ranked_page_ids: list[str] # ordered best โ†’ worst class Metrics(BaseModel): recall_at_k: float ndcg_at_k: float mrr: float k: int class ExperimentResult(BaseModel): config: ExperimentConfig metrics: Metrics # {{/docs-fragment data_types}} class ComparisonReport(BaseModel): results: list[ExperimentResult] def best_by(self, metric: str = "recall_at_k") -> ExperimentResult: return max(self.results, key=lambda r: getattr(r.metrics, metric)) def summary(self) -> str: header = f"{'Experiment':<30} {'Model':<18} {'Recall@K':>10} {'NDCG@K':>8} {'MRR':>7}" sep = "โ”€" * len(header) rows = [header, sep] for r in sorted(self.results, key=lambda x: -x.metrics.recall_at_k): rows.append( f"{r.config.name:<30} " f"{r.config.model.value:<18} " f"{r.metrics.recall_at_k:>10.3f} " f"{r.metrics.ndcg_at_k:>8.3f} " f"{r.metrics.mrr:>7.3f}" ) return "\n".join(rows) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Cached model loaders # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # These functions are at module level so they are shared across all tasks that # run on the same warm container (via ReusePolicy). lru_cache(maxsize=1) means # the model is loaded from disk/HuggingFace exactly once per container process # and kept in GPU memory for every subsequent task dispatch to that container. @lru_cache(maxsize=1) def _colpali_model(): """Load ColPali-v1.2 into GPU memory and cache the result. device_map= is the correct loading pattern for ColPali's PaliGemma backbone; it handles weight placement via accelerate. torch.compile is skipped โ€” ColPali is GPU-compute-bound and the DynamicBatcher's cross- invocation batching is the primary GPU utilisation mechanism. """ import torch from colpali_engine.models import ColPali, ColPaliProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = ColPali.from_pretrained( "vidore/colpali-v1.2", torch_dtype=torch.bfloat16, device_map=device, ) processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.2") return model, processor, device @lru_cache(maxsize=1) def _siglip_model(): """Load SigLIP SO400M into GPU memory, compile it, and cache the result. torch.compile (mode="reduce-overhead") fuses the vision and text encoder transformer layers into optimised CUDA kernels. As with ColPali, the compilation overhead is paid once per warm container lifetime. """ import torch from transformers import AutoModel, AutoProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModel.from_pretrained("google/siglip-so400m-patch14-224").to(device) if device == "cuda": model = torch.compile(model, mode="reduce-overhead") processor = AutoProcessor.from_pretrained("google/siglip-so400m-patch14-224") return model, processor, device @lru_cache(maxsize=1) def _ocr_model(): """Load the doctr OCR predictor onto GPU and cache it. doctr's ocr_predictor bundles a detection model (DBNet) and a recognition model (CRNN/SAR) into a single callable. pretrained=True downloads both model weights from doctr's model zoo on first use. """ import torch from doctr.models import ocr_predictor predictor = ocr_predictor(pretrained=True) if torch.cuda.is_available(): predictor = predictor.cuda() return predictor # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Search batcher singletons # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One DynamicBatcher per model, shared across all concurrent search task # invocations on the same warm container (concurrency=3). Queries from every # concurrent caller are aggregated into a single GPU batch, maximizing # throughput compared to each invocation running its own forward pass. # # Initialised lazily on the first search call via double-checked locking and # lives for the container's lifetime. The process_fn runs GPU work via # asyncio.to_thread so the aggregation loop can continue collecting queries # from other callers while the GPU processes the current batch. # # File is not hashable so alru_cache cannot be used here; module-level state # with asyncio.Lock is the correct pattern. # # Assumption: index_colpali/index_siglip use cache="auto", so the same corpus # always produces the same index File across all callers on this container. If # the index file ever changed between calls, the batcher would silently continue # using the corpus embeddings loaded from the first call. _colpali_batcher: DynamicBatcher | None = None _colpali_batcher_lock = asyncio.Lock() _siglip_batcher: DynamicBatcher | None = None _siglip_batcher_lock = asyncio.Lock() async def _get_colpali_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level ColPali search batcher, creating it on first call.""" global _colpali_batcher if _colpali_batcher is not None: return _colpali_batcher async with _colpali_batcher_lock: if _colpali_batcher is not None: return _colpali_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, n_patches, dim) index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _colpali_model() corpus_emb = corpus_emb.to(device, dtype=torch.float32) async def colpali_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: query_inputs = processor.process_queries([q.text for q in batch]) query_inputs = {k: v.to(device) for k, v in query_inputs.items()} with torch.no_grad(): query_embs = model(**query_inputs).float() # (B, T, D) query_chunk = 8 n_pages = corpus_emb.shape[0] all_scores = torch.empty(len(batch), n_pages, device=device) for start in range(0, len(batch), query_chunk): chunk = query_embs[start : start + query_chunk] all_scores[start : start + query_chunk] = ( torch.einsum("ctd,pjd->ctpj", chunk, corpus_emb) .max(dim=3).values .sum(dim=1) ) sorted_indices = all_scores.argsort(dim=1, descending=True).cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] # Run GPU work in a thread so the event loop โ€” and the batcher's # aggregation loop โ€” remain unblocked while the GPU is busy. return await asyncio.to_thread(_gpu_work) batcher: DynamicBatcher[PageQuery, list[str]] = DynamicBatcher( process_fn=colpali_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _colpali_batcher = batcher return _colpali_batcher async def _get_siglip_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level SigLIP search batcher, creating it on first call.""" global _siglip_batcher if _siglip_batcher is not None: return _siglip_batcher async with _siglip_batcher_lock: if _siglip_batcher is not None: return _siglip_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, dim), L2-normalised index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _siglip_model() corpus_emb = corpus_emb.to(device) async def siglip_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: text_inputs = processor( text=[q.text for q in batch], return_tensors="pt", padding=True, truncation=True, ).to(device) with torch.no_grad(): text_out = model.text_model(**text_inputs) query_embs = text_out.pooler_output # (B, dim) query_embs = query_embs / query_embs.norm(dim=-1, keepdim=True) scores_matrix = corpus_emb @ query_embs.T # (n_pages, B) sorted_indices = scores_matrix.argsort(dim=0, descending=True).T.cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] return await asyncio.to_thread(_gpu_work) batcher = DynamicBatcher( process_fn=siglip_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _siglip_batcher = batcher return _siglip_batcher # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Helpers # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _batches(items: list, batch_size: int): """Yield successive fixed-size batches from a list.""" for start in range(0, len(items), batch_size): yield items[start : start + batch_size] def _load_image_sync(f: File) -> PILImage.Image: """Blocking download + decode. Intended to be called from a thread pool.""" with f.open_sync("rb") as fh: data = fh.read() return PILImage.open(BytesIO(data)).convert("RGB") async def _load_image(f: File) -> PILImage.Image: """Download and decode a page image in a thread-pool worker. asyncio.to_thread runs _load_image_sync in a real OS thread so that blocking network I/O can overlap with GPU-bound forward passes when images are pre-submitted via loop.run_in_executor before the GPU kernel. """ return await asyncio.to_thread(_load_image_sync, f) async def _load_npz(index_file: File) -> np.lib.npyio.NpzFile: """Download an index File to a local temp path and open with np.load.""" with tempfile.NamedTemporaryFile(suffix=".npz", delete=False) as tmp: async with index_file.open("rb") as fh: tmp.write(bytes(await fh.read())) return np.load(tmp.name) def _dcg(relevances: list[int]) -> float: return sum(rel / math.log2(rank + 2) for rank, rel in enumerate(relevances)) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” data loading # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(cache="auto", retries=3) async def load_vidore_pages(subset: str = "docvqa", max_pages: int = 200) -> PageDataset: """ Load a ViDoRe benchmark subset and store page images in Flyte's blob store. Supports two dataset formats: Legacy (subsampled) โ€” single 'test' split with one row per (query, page) pair; fields: image, query, image_filename. streaming=True reads only the rows requested via islice โ€” no full-shard download. Datasets: vidore/docvqa_test_subsampled, vidore/infovqa_test_subsampled V3 โ€” separate corpus / queries / qrels splits following the BEIR retrieval benchmark format. corpus contains page images; queries contains question text; qrels maps query IDs to relevant corpus page IDs (many-to-many). Datasets: vidore/vidore_v3_finance_en (~2 942 pages, 1 854 queries) The first call uploads page images to Flyte's blob store and caches the PageDataset; every subsequent call with the same arguments returns the cached result instantly. retries=3 guards against transient HuggingFace network failures. Available subsets: "docvqa", "infovqa", "vidore_v3_finance_en" """ from datasets import load_dataset subset_map = { "docvqa": "vidore/docvqa_test_subsampled", "infovqa": "vidore/infovqa_test_subsampled", "vidore_v3_finance_en": "vidore/vidore_v3_finance_en", } dataset_name = subset_map.get(subset, f"vidore/{subset}_test_subsampled") # V3 datasets ship with separate corpus / queries / qrels splits. _V3_SUBSETS = {"vidore_v3_finance_en"} if subset in _V3_SUBSETS: # โ”€โ”€ V3 format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # corpus / queries / qrels are HuggingFace configs (name=), not splits. # corpus uses streaming=True so images are decoded one at a time โ€” # loading all 2 942 rows eagerly would hold gigabytes of PIL images in # the driver's RAM simultaneously. qrels and queries are text-only and # small enough to load fully into memory. corpus_ds = load_dataset(dataset_name, name="corpus", split="test", streaming=True) qrels_ds = load_dataset(dataset_name, name="qrels", split="test") queries_ds = load_dataset(dataset_name, name="queries", split="test") # Normalise field names โ€” V3 follows BEIR convention (hyphenated ids). def _col(ds, *candidates): cols = set(ds.column_names) for c in candidates: if c in cols: return c raise KeyError(f"None of {candidates} found in columns {cols}") corpus_id_col = _col(corpus_ds, "corpus-id", "corpus_id", "id", "_id") query_id_col = _col(queries_ds, "query-id", "query_id", "id", "_id") query_text_col = _col(queries_ds, "query", "text") qrel_qid_col = _col(qrels_ds, "query-id", "query_id") qrel_cid_col = _col(qrels_ds, "corpus-id", "corpus_id") # Slice corpus to max_pages, upload each image to Flyte blob store. page_ids: list[str] = [] page_files: list[File] = [] corpus_id_to_page_id: dict[str, str] = {} for i, row in enumerate(islice(corpus_ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue cid = str(row[corpus_id_col]) page_id = f"{subset}_{i:04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) corpus_id_to_page_id[cid] = page_id page_ids.append(page_id) page_files.append(page_file) # Build query_id โ†’ relevant page_id from qrels (first match wins). # Only keep relevance judgements whose corpus page is in our slice. qrel_map: dict[str, str] = {} for row in qrels_ds: qid = str(row[qrel_qid_col]) cid = str(row[qrel_cid_col]) if cid in corpus_id_to_page_id and qid not in qrel_map: qrel_map[qid] = corpus_id_to_page_id[cid] # Collect queries that have at least one relevant page in our slice. queries: list[PageQuery] = [] for row in queries_ds: qid = str(row[query_id_col]) if qid not in qrel_map: continue queries.append( PageQuery( query_id=qid, text=str(row[query_text_col]), relevant_page_id=qrel_map[qid], ) ) else: # โ”€โ”€ Legacy format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Single 'test' split with one row per (query, page) pair. ds = load_dataset(dataset_name, split="test", streaming=True) page_ids = [] page_files = [] queries = [] seen_pages: dict[str, str] = {} # image_filename โ†’ page_id for i, row in enumerate(islice(ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue filename: str = row.get("image_filename") or f"page_{i}" query_text: str = row.get("query", "") if not query_text: continue # Each unique page is uploaded exactly once; multiple queries may # share the same page (same image_filename). if filename not in seen_pages: page_id = f"{subset}_{len(page_ids):04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) seen_pages[filename] = page_id page_ids.append(page_id) page_files.append(page_file) else: page_id = seen_pages[filename] queries.append( PageQuery( query_id=f"q{i:04d}", text=query_text, relevant_page_id=page_id, ) ) print(f"Loaded {len(page_ids)} unique pages, {len(queries)} queries", flush=True) return PageDataset(page_ids=page_ids, page_files=page_files, queries=queries) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” indexing # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @colpali_indexer.task(cache="auto", retries=2) async def index_colpali(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with ColPali-v1.2 and save the multi-vector index. ColPali skips OCR entirely. It feeds the raw page image into PaliGemma (a vision-language model) and produces one embedding vector per image patch โ€” roughly 1,024 patches per page, each of dimension 128. _colpali_model() is an lru_cache'd loader. On a cold container, it downloads and loads the model once. On a warm container (kept alive by ReusePolicy), it returns the already-loaded model instantly from cache โ€” no repeated ~7 GB download. The index is stored as a .npz file in Flyte's blob store: embeddings โ€” float32, shape (n_pages, n_patches, dim) page_ids โ€” matching page ID strings cache="auto" + retries=2: the result is stored permanently on success; transient failures (e.g. HuggingFace rate limits) are retried twice. """ import torch model, processor, device = _colpali_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 4)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor.process_images(images) inputs = {k: v.to(device) for k, v in inputs.items()} with torch.no_grad(): emb = model(**inputs) # (batch, n_patches, dim) all_embeddings.append(emb.cpu().float().numpy()) print(f"ColPali: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, n_patches, dim) out_path = os.path.join(tempfile.gettempdir(), "colpali_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @siglip_indexer.task(cache="auto", retries=2) async def index_siglip(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with SigLIP SO400M and save the single-vector index. SigLIP (2023) is Google's successor to CLIP, trained with sigmoid loss instead of softmax โ€” avoiding the normalisation bottleneck that limits CLIP's scalability. Produces one global embedding per page. _siglip_model() caches the model across warm container reuses. The index is stored as a .npz file: embeddings โ€” float32, shape (n_pages, dim), L2-normalised page_ids โ€” matching page ID strings """ import torch model, processor, device = _siglip_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 8)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor(images=images, return_tensors="pt", padding=True).to(device) with torch.no_grad(): outputs = model.vision_model(**inputs) emb = outputs.pooler_output # (batch, dim) emb = emb / emb.norm(dim=-1, keepdim=True) # L2 normalise all_embeddings.append(emb.cpu().float().numpy()) print(f"SigLIP: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, dim) out_path = os.path.join(tempfile.gettempdir(), "siglip_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @ocr_engine.task(cache="auto") async def extract_page_texts(page_files: list[File]) -> list[str]: """ OCR every page with doctr on GPU to produce a text-only baseline. doctr bundles DBNet (detection) + CRNN/SAR (recognition) into a single callable predictor. Pages are downloaded in parallel then fed in batches of ocr_batch_size. asyncio.to_thread keeps the event loop unblocked during GPU inference. Result structure: result.pages[i].blocks[j].lines[k].words[l].value Cached: the same corpus is OCR'd at most once across all experiments that use the OCR+BM25 backend. """ import gc predictor = _ocr_model() # Process in batches: download each batch just-in-time so only # ocr_batch_size images are in memory at once instead of all 2 000. ocr_batch_size = 8 total = len(page_files) texts: list[str] = [] for start in range(0, total, ocr_batch_size): batch_files = page_files[start : start + ocr_batch_size] batch_images = list( await asyncio.gather(*[asyncio.to_thread(_load_image_sync, f) for f in batch_files]) ) batch_np = [np.array(img) for img in batch_images] del batch_images result = await asyncio.to_thread(predictor, batch_np) del batch_np for page_output in result.pages: texts.append( "\n".join( " ".join(word.value for word in line.words) for block in page_output.blocks for line in block.lines ) ) del result gc.collect() print(f"OCR: processed {min(start + ocr_batch_size, total)}/{total} pages", flush=True) return texts # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” search # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment search_colpali}} @colpali_indexer.task async def search_colpali( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using ColPali MaxSim late interaction via DynamicBatcher. MaxSim score for page p given query q: score(q, p) = ฮฃ_{t โˆˆ query tokens} max_{j โˆˆ page patches} (q_t ยท p_j) Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_colpali invocations on the same warm container (concurrency=8) into a single GPU batch. This keeps the GPU saturated rather than running one small batch per caller. The batcher's process_fn runs GPU work in asyncio.to_thread, so the aggregation loop stays live while the GPU encodes and scores. """ batcher = await _get_colpali_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] # {{/docs-fragment search_colpali}} @siglip_indexer.task async def search_siglip( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using SigLIP cosine similarity via DynamicBatcher. Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_siglip invocations on the same warm container (concurrency=3) into a single GPU batch. SigLIP's single-vector embeddings make full vectorisation safe โ€” the scores matrix (n_pages x n_queries) is small enough to materialise in one GPU call regardless of batch size. """ batcher = await _get_siglip_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] @driver.task async def search_bm25( page_texts: list[str], page_ids: list[str], queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using BM25 over OCR'd text. The standard keyword-based baseline. No GPU required; strong on text-dense pages, weak on visual content that Tesseract cannot read. """ tokenized = [text.lower().split() for text in page_texts] bm25 = BM25Okapi(tokenized) results: list[RetrievalResult] = [] for q in queries: scores = bm25.get_scores(q.text.lower().split()) ranked = sorted(range(len(page_ids)), key=lambda i: -scores[i])[:top_k] results.append( RetrievalResult( query_id=q.query_id, ranked_page_ids=[page_ids[i] for i in ranked], ) ) return results # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” evaluation # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task async def evaluate( results: list[RetrievalResult], ground_truth: list[PageQuery], k: int, ) -> Metrics: """ Compute Recall@K, NDCG@K, and MRR for a single retrieval model. Recall@K โ€” was the correct page in the top-K results? NDCG@K โ€” normalised discounted cumulative gain; rewards earlier hits. MRR โ€” mean reciprocal rank of the first correct result. All three are averaged over all queries. Higher is better. """ gt_map = {q.query_id: q.relevant_page_id for q in ground_truth} recall_vals, ndcg_vals, mrr_vals = [], [], [] for r in results: relevant = gt_map.get(r.query_id, "") top = r.ranked_page_ids[:k] recall_vals.append(1.0 if relevant in top else 0.0) rels = [1 if pid == relevant else 0 for pid in top] idcg = _dcg([1]) # ideal: correct page at rank 1 ndcg_vals.append(_dcg(rels) / idcg if idcg > 0 else 0.0) rr = 0.0 for rank, pid in enumerate(r.ranked_page_ids, start=1): if pid == relevant: rr = 1.0 / rank break mrr_vals.append(rr) return Metrics( recall_at_k=float(np.mean(recall_vals)), ndcg_at_k=float(np.mean(ndcg_vals)), mrr=float(np.mean(mrr_vals)), k=k, ) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” report # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(report=True) async def generate_report(report: ComparisonReport) -> None: """ Emit an interactive HTML report visible in the Flyte UI. report=True marks this task as a reporting task. Flyte renders the HTML returned via flyte.report.replace.aio() directly in the execution detail page โ€” no separate dashboard or export step required. The report contains: - Summary cards: experiment count, best model, best Recall@K. - Grouped bar chart: Recall@K, NDCG@K, MRR side-by-side per experiment. - Ranked results table with all three metrics. """ sorted_results = sorted(report.results, key=lambda r: -r.metrics.recall_at_k) best = sorted_results[0] labels = [r.config.name for r in sorted_results] recall_vals = [r.metrics.recall_at_k for r in sorted_results] ndcg_vals = [r.metrics.ndcg_at_k for r in sorted_results] mrr_vals = [r.metrics.mrr for r in sorted_results] table_rows = "".join( f""" {r.config.name} {r.config.model.value} {r.metrics.recall_at_k:.3f} {r.metrics.ndcg_at_k:.3f} {r.metrics.mrr:.3f} {r.metrics.k} """ for r in sorted_results ) html = f""" Visual Document Retrieval โ€” Results

Visual Document Retrieval โ€” Experiment Comparison

ViDoRe benchmark · {len(report.results)} experiment(s)

{len(report.results)}
Experiments
{best.config.name}
Best by Recall@K
{best.metrics.recall_at_k:.3f}
Best Recall@{best.metrics.k}
{best.metrics.ndcg_at_k:.3f}
Best NDCG@{best.metrics.k}
{best.metrics.mrr:.3f}
Best MRR

Metrics by Experiment

Ranked Results

{table_rows}
ExperimentModel Recall@KNDCG@KMRRK
""" await flyte.report.replace.aio(html) await flyte.report.flush.aio() # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Experiment orchestration # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment run_experiment}} @driver.task async def run_experiment(config: ExperimentConfig, dataset: PageDataset) -> ExperimentResult: """ End-to-end retrieval pipeline for a single ExperimentConfig. Flyte v2's dynamic execution means this driver task can call GPU tasks (index_colpali, search_colpali) based on the runtime value of config.model โ€” no static DAG wiring required. The if/elif is plain Python; Flyte schedules the selected sub-tasks on the appropriate environment. Caching: two experiments that share the same model and corpus (e.g. ColPali at top_k=5 and top_k=10) will hit the same cached index. GPU work is paid at most once per (model, corpus) pair across all experiments. Search queries are sharded into chunks of SEARCH_SHARD_SIZE and dispatched as concurrent task invocations. All shards land on the single warm container (replicas=1) and feed the same DynamicBatcher simultaneously, keeping the GPU saturated throughout search rather than processing one large sequential batch from a single caller. flyte.group wraps each experiment in a named span in the Flyte UI, making it easy to compare latencies and drill into individual runs. """ SEARCH_SHARD_SIZE = 256 with flyte.group(config.name): if config.model == RetrievalModel.COLPALI: index_file = await index_colpali(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_colpali(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] elif config.model == RetrievalModel.SIGLIP: index_file = await index_siglip(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_siglip(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] else: # RetrievalModel.OCR_BM25 page_texts = await extract_page_texts(dataset.page_files) results = await search_bm25(page_texts, dataset.page_ids, dataset.queries, config.top_k) metrics = await evaluate(results, dataset.queries, config.top_k) return ExperimentResult(config=config, metrics=metrics) # {{/docs-fragment run_experiment}} # {{docs-fragment compare_experiments}} @driver.task async def compare_experiments( configs: list[ExperimentConfig], subset: str = "docvqa", max_pages: int = 200, ) -> ComparisonReport: """ Fan out over all experiment configs and return a ranked comparison table. The dataset is loaded once and shared across all experiments. Each config runs as a concurrent Flyte task via asyncio.gather. Experiments that share a model reuse the cached index โ€” you only pay GPU time for new work. On completion, generate_report emits an interactive Chart.js HTML report visible directly in the Flyte execution detail page. Default dataset: vidore_v3_finance_en (~2 942 corpus pages, 1 854 queries) with max_pages=2 000 to exercise the GPU pipeline at scale. """ dataset = await load_vidore_pages(subset=subset, max_pages=max_pages) # All experiments launch concurrently. Shared cached outputs (same model, # same corpus) are served from cache rather than recomputed. experiment_coros = [run_experiment(config=cfg, dataset=dataset) for cfg in configs] results: list[ExperimentResult] = list(await asyncio.gather(*experiment_coros)) report = ComparisonReport(results=results) print(report.summary()) best = report.best_by("recall_at_k") print(f"\nBest by Recall@{best.metrics.k}: {best.config.name}") # Emit the interactive HTML report in the Flyte UI. await generate_report(report) return report # {{/docs-fragment compare_experiments}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Entry point # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if __name__ == "__main__": flyte.init_from_config() # Define the experiment grid. Each ExperimentConfig is one point in the # design space. Adding a new model or varying top_k is one line here โ€” # no task code changes required. # # ColPali appears twice with different top_k values. The cache ensures # index_colpali runs only once and both experiments share that result. # {{docs-fragment grid}} configs = [ ExperimentConfig(name="colpali-top5", model=RetrievalModel.COLPALI, top_k=5), ExperimentConfig(name="colpali-top10", model=RetrievalModel.COLPALI, top_k=10), ExperimentConfig(name="siglip-top5", model=RetrievalModel.SIGLIP, top_k=5), ExperimentConfig(name="ocr-bm25-top5", model=RetrievalModel.OCR_BM25, top_k=5), ] # {{/docs-fragment grid}} run = flyte.with_runcontext().run( compare_experiments, configs=configs, subset="vidore_v3_finance_en", max_pages=2000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multimodal-retrieval-evaluation/retrieval_eval.py* ## Configuration and data types An experiment is fully described by an `ExperimentConfig`. Because it's a Pydantic model, Flyte serializes it alongside every output. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "colpali-engine>=0.3.1", # "transformers>=4.41", # "sentencepiece>=0.2", # "torch>=2.0", # "pillow>=10", # "datasets>=2.18", # "rank-bm25>=0.2", # "numpy>=1.26", # "python-doctr[torch]>=0.8", # "pydantic>=2.0", # "flyte>=2.0.0", # ] # /// """ Multimodal Retrieval Evaluation Pipeline This tutorial is an experiment framework for benchmarking visual document retrieval approaches on the ViDoRe benchmark. Each experiment is defined by an ExperimentConfig; the pipeline fans them out as concurrent Flyte tasks and returns a ranked comparison table with an interactive HTML report. The corpus is a set of PDF page images; queries are plain-text questions. Each retrieval method must find the page that answers each question โ€” no text is provided to the model, only the raw image. ColPali-v1.2 โ€” patch-level multi-vector embeddings from a VLM (PaliGemma). No OCR. The model produces one vector per image patch (~1024 per page). MaxSim late-interaction scoring finds the best matching patch for each query token. SigLIP-SO400M โ€” single global embedding per page from Google's 2023 CLIP successor. One matrix multiply per query; fast and effective but a single vector cannot localise fine-grained regions. OCR + BM25 โ€” text-only baseline. doctr (GPU OCR) extracts text in batches, BM25 matches keywords. Strong on text-dense pages; fails on charts, tables, and figures where content is visual. """ import asyncio import enum import json import math import os import tempfile from functools import lru_cache from io import BytesIO from itertools import islice import numpy as np from PIL import Image as PILImage from pydantic import BaseModel from rank_bm25 import BM25Okapi from extras import DynamicBatcher import flyte import flyte.report from flyte.io import File # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Environments # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One Docker image for all tasks. The PEP 723 header defines Python deps. # ca-certificates is required for HTTPS calls to HuggingFace and blob stores. # {{docs-fragment image}} image = ( flyte.Image.from_uv_script(__file__, name="vidore-eval-v2") .with_apt_packages("ca-certificates", "libxcb1", "libgl1", "libglib2.0-0") # unionai-reuse installs the unionai-actor-bridge binary required by ReusePolicy. # Without it every reusable container exits with StartError (exit code 128). .with_pip_packages("unionai-reuse>=0.1.11") ) # {{/docs-fragment image}} # GPU environment for ColPali image encoding and search. # # ReusePolicy keeps up to 3 warm GPU containers alive between task calls. # Without it, every task invocation cold-starts a new container and downloads # ColPali-v1.2 (~7 GB) from scratch. With it, the container โ€” and the model # weights already loaded into VRAM โ€” is reused for the next task dispatch. # # replicas=1 single warm container โ€” all concurrent shard calls land # here so they share one DynamicBatcher process # concurrency=8 up to 8 query-shard tasks run simultaneously on the # container, all feeding the same DynamicBatcher queue # idle_ttl=120 keep alive 2 min after the last task finishes # scaledown_ttl=60 scale to zero after 1 min of complete inactivity # {{docs-fragment envs}} colpali_indexer = flyte.TaskEnvironment( name="vidore-colpali-indexer", image=image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="A10G:1"), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for SigLIP image encoding and search. # # Separate from the ColPali environment so each model's warm containers # are managed independently โ€” ColPali and SigLIP experiments can scale # without contending for the same pool of reusable containers. siglip_indexer = flyte.TaskEnvironment( name="vidore-siglip-indexer", image=image, resources=flyte.Resources(cpu=4, memory="8Gi", gpu=1), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for doctr OCR. doctr runs DBNet (detection) + CRNN (recognition) # in batches on GPU โ€” much faster than CPU Tesseract. # No ReusePolicy needed: the result is cached, so this task runs at most once. ocr_engine = flyte.TaskEnvironment( name="vidore-ocr-engine", image=image, resources=flyte.Resources(cpu=4, memory="20Gi", gpu=1), ) # Driver: orchestration, BM25 search, evaluation, and reporting. # depends_on ensures the shared Docker image is built before all environments # try to schedule tasks. driver = flyte.TaskEnvironment( name="vidore-driver", image=image, resources=flyte.Resources(cpu=2, memory="12Gi"), depends_on=[colpali_indexer, siglip_indexer, ocr_engine], ) # {{/docs-fragment envs}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Configuration types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment config_types}} class RetrievalModel(str, enum.Enum): """Retrieval backend to evaluate.""" COLPALI = "colpali-v1.2" # multi-vector patch embeddings, MaxSim SIGLIP = "siglip-so400m" # single-vector global embedding, cosine sim OCR_BM25 = "ocr+bm25" # text extracted by Tesseract, ranked by BM25 class ExperimentConfig(BaseModel): """ All knobs for one retrieval experiment. Passed as a typed Flyte input. Because ExperimentConfig is a Pydantic model, Flyte serialises it alongside every task output โ€” so you can always reconstruct which config produced which metric without maintaining a separate log. """ name: str # human-readable label shown in the comparison table model: RetrievalModel top_k: int = 5 # number of pages to retrieve per query # {{/docs-fragment config_types}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Data types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment data_types}} class PageQuery(BaseModel): """One retrieval query with its ground-truth page.""" query_id: str text: str # e.g. "What was revenue growth in Q3?" relevant_page_id: str # one correct page per query class PageDataset(BaseModel): """ A corpus of document page images paired with text queries. page_ids: unique page identifiers (derived from ViDoRe image filenames). page_files: the same pages stored in Flyte's blob store as JPEG File handles. Tasks read images directly from here; no live HTTP. queries: text questions with ground-truth page IDs for evaluation. """ page_ids: list[str] page_files: list[File] queries: list[PageQuery] class Config: arbitrary_types_allowed = True class RetrievalResult(BaseModel): query_id: str ranked_page_ids: list[str] # ordered best โ†’ worst class Metrics(BaseModel): recall_at_k: float ndcg_at_k: float mrr: float k: int class ExperimentResult(BaseModel): config: ExperimentConfig metrics: Metrics # {{/docs-fragment data_types}} class ComparisonReport(BaseModel): results: list[ExperimentResult] def best_by(self, metric: str = "recall_at_k") -> ExperimentResult: return max(self.results, key=lambda r: getattr(r.metrics, metric)) def summary(self) -> str: header = f"{'Experiment':<30} {'Model':<18} {'Recall@K':>10} {'NDCG@K':>8} {'MRR':>7}" sep = "โ”€" * len(header) rows = [header, sep] for r in sorted(self.results, key=lambda x: -x.metrics.recall_at_k): rows.append( f"{r.config.name:<30} " f"{r.config.model.value:<18} " f"{r.metrics.recall_at_k:>10.3f} " f"{r.metrics.ndcg_at_k:>8.3f} " f"{r.metrics.mrr:>7.3f}" ) return "\n".join(rows) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Cached model loaders # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # These functions are at module level so they are shared across all tasks that # run on the same warm container (via ReusePolicy). lru_cache(maxsize=1) means # the model is loaded from disk/HuggingFace exactly once per container process # and kept in GPU memory for every subsequent task dispatch to that container. @lru_cache(maxsize=1) def _colpali_model(): """Load ColPali-v1.2 into GPU memory and cache the result. device_map= is the correct loading pattern for ColPali's PaliGemma backbone; it handles weight placement via accelerate. torch.compile is skipped โ€” ColPali is GPU-compute-bound and the DynamicBatcher's cross- invocation batching is the primary GPU utilisation mechanism. """ import torch from colpali_engine.models import ColPali, ColPaliProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = ColPali.from_pretrained( "vidore/colpali-v1.2", torch_dtype=torch.bfloat16, device_map=device, ) processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.2") return model, processor, device @lru_cache(maxsize=1) def _siglip_model(): """Load SigLIP SO400M into GPU memory, compile it, and cache the result. torch.compile (mode="reduce-overhead") fuses the vision and text encoder transformer layers into optimised CUDA kernels. As with ColPali, the compilation overhead is paid once per warm container lifetime. """ import torch from transformers import AutoModel, AutoProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModel.from_pretrained("google/siglip-so400m-patch14-224").to(device) if device == "cuda": model = torch.compile(model, mode="reduce-overhead") processor = AutoProcessor.from_pretrained("google/siglip-so400m-patch14-224") return model, processor, device @lru_cache(maxsize=1) def _ocr_model(): """Load the doctr OCR predictor onto GPU and cache it. doctr's ocr_predictor bundles a detection model (DBNet) and a recognition model (CRNN/SAR) into a single callable. pretrained=True downloads both model weights from doctr's model zoo on first use. """ import torch from doctr.models import ocr_predictor predictor = ocr_predictor(pretrained=True) if torch.cuda.is_available(): predictor = predictor.cuda() return predictor # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Search batcher singletons # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One DynamicBatcher per model, shared across all concurrent search task # invocations on the same warm container (concurrency=3). Queries from every # concurrent caller are aggregated into a single GPU batch, maximizing # throughput compared to each invocation running its own forward pass. # # Initialised lazily on the first search call via double-checked locking and # lives for the container's lifetime. The process_fn runs GPU work via # asyncio.to_thread so the aggregation loop can continue collecting queries # from other callers while the GPU processes the current batch. # # File is not hashable so alru_cache cannot be used here; module-level state # with asyncio.Lock is the correct pattern. # # Assumption: index_colpali/index_siglip use cache="auto", so the same corpus # always produces the same index File across all callers on this container. If # the index file ever changed between calls, the batcher would silently continue # using the corpus embeddings loaded from the first call. _colpali_batcher: DynamicBatcher | None = None _colpali_batcher_lock = asyncio.Lock() _siglip_batcher: DynamicBatcher | None = None _siglip_batcher_lock = asyncio.Lock() async def _get_colpali_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level ColPali search batcher, creating it on first call.""" global _colpali_batcher if _colpali_batcher is not None: return _colpali_batcher async with _colpali_batcher_lock: if _colpali_batcher is not None: return _colpali_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, n_patches, dim) index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _colpali_model() corpus_emb = corpus_emb.to(device, dtype=torch.float32) async def colpali_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: query_inputs = processor.process_queries([q.text for q in batch]) query_inputs = {k: v.to(device) for k, v in query_inputs.items()} with torch.no_grad(): query_embs = model(**query_inputs).float() # (B, T, D) query_chunk = 8 n_pages = corpus_emb.shape[0] all_scores = torch.empty(len(batch), n_pages, device=device) for start in range(0, len(batch), query_chunk): chunk = query_embs[start : start + query_chunk] all_scores[start : start + query_chunk] = ( torch.einsum("ctd,pjd->ctpj", chunk, corpus_emb) .max(dim=3).values .sum(dim=1) ) sorted_indices = all_scores.argsort(dim=1, descending=True).cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] # Run GPU work in a thread so the event loop โ€” and the batcher's # aggregation loop โ€” remain unblocked while the GPU is busy. return await asyncio.to_thread(_gpu_work) batcher: DynamicBatcher[PageQuery, list[str]] = DynamicBatcher( process_fn=colpali_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _colpali_batcher = batcher return _colpali_batcher async def _get_siglip_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level SigLIP search batcher, creating it on first call.""" global _siglip_batcher if _siglip_batcher is not None: return _siglip_batcher async with _siglip_batcher_lock: if _siglip_batcher is not None: return _siglip_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, dim), L2-normalised index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _siglip_model() corpus_emb = corpus_emb.to(device) async def siglip_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: text_inputs = processor( text=[q.text for q in batch], return_tensors="pt", padding=True, truncation=True, ).to(device) with torch.no_grad(): text_out = model.text_model(**text_inputs) query_embs = text_out.pooler_output # (B, dim) query_embs = query_embs / query_embs.norm(dim=-1, keepdim=True) scores_matrix = corpus_emb @ query_embs.T # (n_pages, B) sorted_indices = scores_matrix.argsort(dim=0, descending=True).T.cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] return await asyncio.to_thread(_gpu_work) batcher = DynamicBatcher( process_fn=siglip_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _siglip_batcher = batcher return _siglip_batcher # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Helpers # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _batches(items: list, batch_size: int): """Yield successive fixed-size batches from a list.""" for start in range(0, len(items), batch_size): yield items[start : start + batch_size] def _load_image_sync(f: File) -> PILImage.Image: """Blocking download + decode. Intended to be called from a thread pool.""" with f.open_sync("rb") as fh: data = fh.read() return PILImage.open(BytesIO(data)).convert("RGB") async def _load_image(f: File) -> PILImage.Image: """Download and decode a page image in a thread-pool worker. asyncio.to_thread runs _load_image_sync in a real OS thread so that blocking network I/O can overlap with GPU-bound forward passes when images are pre-submitted via loop.run_in_executor before the GPU kernel. """ return await asyncio.to_thread(_load_image_sync, f) async def _load_npz(index_file: File) -> np.lib.npyio.NpzFile: """Download an index File to a local temp path and open with np.load.""" with tempfile.NamedTemporaryFile(suffix=".npz", delete=False) as tmp: async with index_file.open("rb") as fh: tmp.write(bytes(await fh.read())) return np.load(tmp.name) def _dcg(relevances: list[int]) -> float: return sum(rel / math.log2(rank + 2) for rank, rel in enumerate(relevances)) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” data loading # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(cache="auto", retries=3) async def load_vidore_pages(subset: str = "docvqa", max_pages: int = 200) -> PageDataset: """ Load a ViDoRe benchmark subset and store page images in Flyte's blob store. Supports two dataset formats: Legacy (subsampled) โ€” single 'test' split with one row per (query, page) pair; fields: image, query, image_filename. streaming=True reads only the rows requested via islice โ€” no full-shard download. Datasets: vidore/docvqa_test_subsampled, vidore/infovqa_test_subsampled V3 โ€” separate corpus / queries / qrels splits following the BEIR retrieval benchmark format. corpus contains page images; queries contains question text; qrels maps query IDs to relevant corpus page IDs (many-to-many). Datasets: vidore/vidore_v3_finance_en (~2 942 pages, 1 854 queries) The first call uploads page images to Flyte's blob store and caches the PageDataset; every subsequent call with the same arguments returns the cached result instantly. retries=3 guards against transient HuggingFace network failures. Available subsets: "docvqa", "infovqa", "vidore_v3_finance_en" """ from datasets import load_dataset subset_map = { "docvqa": "vidore/docvqa_test_subsampled", "infovqa": "vidore/infovqa_test_subsampled", "vidore_v3_finance_en": "vidore/vidore_v3_finance_en", } dataset_name = subset_map.get(subset, f"vidore/{subset}_test_subsampled") # V3 datasets ship with separate corpus / queries / qrels splits. _V3_SUBSETS = {"vidore_v3_finance_en"} if subset in _V3_SUBSETS: # โ”€โ”€ V3 format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # corpus / queries / qrels are HuggingFace configs (name=), not splits. # corpus uses streaming=True so images are decoded one at a time โ€” # loading all 2 942 rows eagerly would hold gigabytes of PIL images in # the driver's RAM simultaneously. qrels and queries are text-only and # small enough to load fully into memory. corpus_ds = load_dataset(dataset_name, name="corpus", split="test", streaming=True) qrels_ds = load_dataset(dataset_name, name="qrels", split="test") queries_ds = load_dataset(dataset_name, name="queries", split="test") # Normalise field names โ€” V3 follows BEIR convention (hyphenated ids). def _col(ds, *candidates): cols = set(ds.column_names) for c in candidates: if c in cols: return c raise KeyError(f"None of {candidates} found in columns {cols}") corpus_id_col = _col(corpus_ds, "corpus-id", "corpus_id", "id", "_id") query_id_col = _col(queries_ds, "query-id", "query_id", "id", "_id") query_text_col = _col(queries_ds, "query", "text") qrel_qid_col = _col(qrels_ds, "query-id", "query_id") qrel_cid_col = _col(qrels_ds, "corpus-id", "corpus_id") # Slice corpus to max_pages, upload each image to Flyte blob store. page_ids: list[str] = [] page_files: list[File] = [] corpus_id_to_page_id: dict[str, str] = {} for i, row in enumerate(islice(corpus_ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue cid = str(row[corpus_id_col]) page_id = f"{subset}_{i:04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) corpus_id_to_page_id[cid] = page_id page_ids.append(page_id) page_files.append(page_file) # Build query_id โ†’ relevant page_id from qrels (first match wins). # Only keep relevance judgements whose corpus page is in our slice. qrel_map: dict[str, str] = {} for row in qrels_ds: qid = str(row[qrel_qid_col]) cid = str(row[qrel_cid_col]) if cid in corpus_id_to_page_id and qid not in qrel_map: qrel_map[qid] = corpus_id_to_page_id[cid] # Collect queries that have at least one relevant page in our slice. queries: list[PageQuery] = [] for row in queries_ds: qid = str(row[query_id_col]) if qid not in qrel_map: continue queries.append( PageQuery( query_id=qid, text=str(row[query_text_col]), relevant_page_id=qrel_map[qid], ) ) else: # โ”€โ”€ Legacy format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Single 'test' split with one row per (query, page) pair. ds = load_dataset(dataset_name, split="test", streaming=True) page_ids = [] page_files = [] queries = [] seen_pages: dict[str, str] = {} # image_filename โ†’ page_id for i, row in enumerate(islice(ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue filename: str = row.get("image_filename") or f"page_{i}" query_text: str = row.get("query", "") if not query_text: continue # Each unique page is uploaded exactly once; multiple queries may # share the same page (same image_filename). if filename not in seen_pages: page_id = f"{subset}_{len(page_ids):04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) seen_pages[filename] = page_id page_ids.append(page_id) page_files.append(page_file) else: page_id = seen_pages[filename] queries.append( PageQuery( query_id=f"q{i:04d}", text=query_text, relevant_page_id=page_id, ) ) print(f"Loaded {len(page_ids)} unique pages, {len(queries)} queries", flush=True) return PageDataset(page_ids=page_ids, page_files=page_files, queries=queries) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” indexing # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @colpali_indexer.task(cache="auto", retries=2) async def index_colpali(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with ColPali-v1.2 and save the multi-vector index. ColPali skips OCR entirely. It feeds the raw page image into PaliGemma (a vision-language model) and produces one embedding vector per image patch โ€” roughly 1,024 patches per page, each of dimension 128. _colpali_model() is an lru_cache'd loader. On a cold container, it downloads and loads the model once. On a warm container (kept alive by ReusePolicy), it returns the already-loaded model instantly from cache โ€” no repeated ~7 GB download. The index is stored as a .npz file in Flyte's blob store: embeddings โ€” float32, shape (n_pages, n_patches, dim) page_ids โ€” matching page ID strings cache="auto" + retries=2: the result is stored permanently on success; transient failures (e.g. HuggingFace rate limits) are retried twice. """ import torch model, processor, device = _colpali_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 4)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor.process_images(images) inputs = {k: v.to(device) for k, v in inputs.items()} with torch.no_grad(): emb = model(**inputs) # (batch, n_patches, dim) all_embeddings.append(emb.cpu().float().numpy()) print(f"ColPali: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, n_patches, dim) out_path = os.path.join(tempfile.gettempdir(), "colpali_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @siglip_indexer.task(cache="auto", retries=2) async def index_siglip(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with SigLIP SO400M and save the single-vector index. SigLIP (2023) is Google's successor to CLIP, trained with sigmoid loss instead of softmax โ€” avoiding the normalisation bottleneck that limits CLIP's scalability. Produces one global embedding per page. _siglip_model() caches the model across warm container reuses. The index is stored as a .npz file: embeddings โ€” float32, shape (n_pages, dim), L2-normalised page_ids โ€” matching page ID strings """ import torch model, processor, device = _siglip_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 8)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor(images=images, return_tensors="pt", padding=True).to(device) with torch.no_grad(): outputs = model.vision_model(**inputs) emb = outputs.pooler_output # (batch, dim) emb = emb / emb.norm(dim=-1, keepdim=True) # L2 normalise all_embeddings.append(emb.cpu().float().numpy()) print(f"SigLIP: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, dim) out_path = os.path.join(tempfile.gettempdir(), "siglip_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @ocr_engine.task(cache="auto") async def extract_page_texts(page_files: list[File]) -> list[str]: """ OCR every page with doctr on GPU to produce a text-only baseline. doctr bundles DBNet (detection) + CRNN/SAR (recognition) into a single callable predictor. Pages are downloaded in parallel then fed in batches of ocr_batch_size. asyncio.to_thread keeps the event loop unblocked during GPU inference. Result structure: result.pages[i].blocks[j].lines[k].words[l].value Cached: the same corpus is OCR'd at most once across all experiments that use the OCR+BM25 backend. """ import gc predictor = _ocr_model() # Process in batches: download each batch just-in-time so only # ocr_batch_size images are in memory at once instead of all 2 000. ocr_batch_size = 8 total = len(page_files) texts: list[str] = [] for start in range(0, total, ocr_batch_size): batch_files = page_files[start : start + ocr_batch_size] batch_images = list( await asyncio.gather(*[asyncio.to_thread(_load_image_sync, f) for f in batch_files]) ) batch_np = [np.array(img) for img in batch_images] del batch_images result = await asyncio.to_thread(predictor, batch_np) del batch_np for page_output in result.pages: texts.append( "\n".join( " ".join(word.value for word in line.words) for block in page_output.blocks for line in block.lines ) ) del result gc.collect() print(f"OCR: processed {min(start + ocr_batch_size, total)}/{total} pages", flush=True) return texts # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” search # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment search_colpali}} @colpali_indexer.task async def search_colpali( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using ColPali MaxSim late interaction via DynamicBatcher. MaxSim score for page p given query q: score(q, p) = ฮฃ_{t โˆˆ query tokens} max_{j โˆˆ page patches} (q_t ยท p_j) Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_colpali invocations on the same warm container (concurrency=8) into a single GPU batch. This keeps the GPU saturated rather than running one small batch per caller. The batcher's process_fn runs GPU work in asyncio.to_thread, so the aggregation loop stays live while the GPU encodes and scores. """ batcher = await _get_colpali_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] # {{/docs-fragment search_colpali}} @siglip_indexer.task async def search_siglip( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using SigLIP cosine similarity via DynamicBatcher. Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_siglip invocations on the same warm container (concurrency=3) into a single GPU batch. SigLIP's single-vector embeddings make full vectorisation safe โ€” the scores matrix (n_pages x n_queries) is small enough to materialise in one GPU call regardless of batch size. """ batcher = await _get_siglip_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] @driver.task async def search_bm25( page_texts: list[str], page_ids: list[str], queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using BM25 over OCR'd text. The standard keyword-based baseline. No GPU required; strong on text-dense pages, weak on visual content that Tesseract cannot read. """ tokenized = [text.lower().split() for text in page_texts] bm25 = BM25Okapi(tokenized) results: list[RetrievalResult] = [] for q in queries: scores = bm25.get_scores(q.text.lower().split()) ranked = sorted(range(len(page_ids)), key=lambda i: -scores[i])[:top_k] results.append( RetrievalResult( query_id=q.query_id, ranked_page_ids=[page_ids[i] for i in ranked], ) ) return results # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” evaluation # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task async def evaluate( results: list[RetrievalResult], ground_truth: list[PageQuery], k: int, ) -> Metrics: """ Compute Recall@K, NDCG@K, and MRR for a single retrieval model. Recall@K โ€” was the correct page in the top-K results? NDCG@K โ€” normalised discounted cumulative gain; rewards earlier hits. MRR โ€” mean reciprocal rank of the first correct result. All three are averaged over all queries. Higher is better. """ gt_map = {q.query_id: q.relevant_page_id for q in ground_truth} recall_vals, ndcg_vals, mrr_vals = [], [], [] for r in results: relevant = gt_map.get(r.query_id, "") top = r.ranked_page_ids[:k] recall_vals.append(1.0 if relevant in top else 0.0) rels = [1 if pid == relevant else 0 for pid in top] idcg = _dcg([1]) # ideal: correct page at rank 1 ndcg_vals.append(_dcg(rels) / idcg if idcg > 0 else 0.0) rr = 0.0 for rank, pid in enumerate(r.ranked_page_ids, start=1): if pid == relevant: rr = 1.0 / rank break mrr_vals.append(rr) return Metrics( recall_at_k=float(np.mean(recall_vals)), ndcg_at_k=float(np.mean(ndcg_vals)), mrr=float(np.mean(mrr_vals)), k=k, ) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” report # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(report=True) async def generate_report(report: ComparisonReport) -> None: """ Emit an interactive HTML report visible in the Flyte UI. report=True marks this task as a reporting task. Flyte renders the HTML returned via flyte.report.replace.aio() directly in the execution detail page โ€” no separate dashboard or export step required. The report contains: - Summary cards: experiment count, best model, best Recall@K. - Grouped bar chart: Recall@K, NDCG@K, MRR side-by-side per experiment. - Ranked results table with all three metrics. """ sorted_results = sorted(report.results, key=lambda r: -r.metrics.recall_at_k) best = sorted_results[0] labels = [r.config.name for r in sorted_results] recall_vals = [r.metrics.recall_at_k for r in sorted_results] ndcg_vals = [r.metrics.ndcg_at_k for r in sorted_results] mrr_vals = [r.metrics.mrr for r in sorted_results] table_rows = "".join( f""" {r.config.name} {r.config.model.value} {r.metrics.recall_at_k:.3f} {r.metrics.ndcg_at_k:.3f} {r.metrics.mrr:.3f} {r.metrics.k} """ for r in sorted_results ) html = f""" Visual Document Retrieval โ€” Results

Visual Document Retrieval โ€” Experiment Comparison

ViDoRe benchmark · {len(report.results)} experiment(s)

{len(report.results)}
Experiments
{best.config.name}
Best by Recall@K
{best.metrics.recall_at_k:.3f}
Best Recall@{best.metrics.k}
{best.metrics.ndcg_at_k:.3f}
Best NDCG@{best.metrics.k}
{best.metrics.mrr:.3f}
Best MRR

Metrics by Experiment

Ranked Results

{table_rows}
ExperimentModel Recall@KNDCG@KMRRK
""" await flyte.report.replace.aio(html) await flyte.report.flush.aio() # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Experiment orchestration # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment run_experiment}} @driver.task async def run_experiment(config: ExperimentConfig, dataset: PageDataset) -> ExperimentResult: """ End-to-end retrieval pipeline for a single ExperimentConfig. Flyte v2's dynamic execution means this driver task can call GPU tasks (index_colpali, search_colpali) based on the runtime value of config.model โ€” no static DAG wiring required. The if/elif is plain Python; Flyte schedules the selected sub-tasks on the appropriate environment. Caching: two experiments that share the same model and corpus (e.g. ColPali at top_k=5 and top_k=10) will hit the same cached index. GPU work is paid at most once per (model, corpus) pair across all experiments. Search queries are sharded into chunks of SEARCH_SHARD_SIZE and dispatched as concurrent task invocations. All shards land on the single warm container (replicas=1) and feed the same DynamicBatcher simultaneously, keeping the GPU saturated throughout search rather than processing one large sequential batch from a single caller. flyte.group wraps each experiment in a named span in the Flyte UI, making it easy to compare latencies and drill into individual runs. """ SEARCH_SHARD_SIZE = 256 with flyte.group(config.name): if config.model == RetrievalModel.COLPALI: index_file = await index_colpali(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_colpali(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] elif config.model == RetrievalModel.SIGLIP: index_file = await index_siglip(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_siglip(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] else: # RetrievalModel.OCR_BM25 page_texts = await extract_page_texts(dataset.page_files) results = await search_bm25(page_texts, dataset.page_ids, dataset.queries, config.top_k) metrics = await evaluate(results, dataset.queries, config.top_k) return ExperimentResult(config=config, metrics=metrics) # {{/docs-fragment run_experiment}} # {{docs-fragment compare_experiments}} @driver.task async def compare_experiments( configs: list[ExperimentConfig], subset: str = "docvqa", max_pages: int = 200, ) -> ComparisonReport: """ Fan out over all experiment configs and return a ranked comparison table. The dataset is loaded once and shared across all experiments. Each config runs as a concurrent Flyte task via asyncio.gather. Experiments that share a model reuse the cached index โ€” you only pay GPU time for new work. On completion, generate_report emits an interactive Chart.js HTML report visible directly in the Flyte execution detail page. Default dataset: vidore_v3_finance_en (~2 942 corpus pages, 1 854 queries) with max_pages=2 000 to exercise the GPU pipeline at scale. """ dataset = await load_vidore_pages(subset=subset, max_pages=max_pages) # All experiments launch concurrently. Shared cached outputs (same model, # same corpus) are served from cache rather than recomputed. experiment_coros = [run_experiment(config=cfg, dataset=dataset) for cfg in configs] results: list[ExperimentResult] = list(await asyncio.gather(*experiment_coros)) report = ComparisonReport(results=results) print(report.summary()) best = report.best_by("recall_at_k") print(f"\nBest by Recall@{best.metrics.k}: {best.config.name}") # Emit the interactive HTML report in the Flyte UI. await generate_report(report) return report # {{/docs-fragment compare_experiments}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Entry point # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if __name__ == "__main__": flyte.init_from_config() # Define the experiment grid. Each ExperimentConfig is one point in the # design space. Adding a new model or varying top_k is one line here โ€” # no task code changes required. # # ColPali appears twice with different top_k values. The cache ensures # index_colpali runs only once and both experiments share that result. # {{docs-fragment grid}} configs = [ ExperimentConfig(name="colpali-top5", model=RetrievalModel.COLPALI, top_k=5), ExperimentConfig(name="colpali-top10", model=RetrievalModel.COLPALI, top_k=10), ExperimentConfig(name="siglip-top5", model=RetrievalModel.SIGLIP, top_k=5), ExperimentConfig(name="ocr-bm25-top5", model=RetrievalModel.OCR_BM25, top_k=5), ] # {{/docs-fragment grid}} run = flyte.with_runcontext().run( compare_experiments, configs=configs, subset="vidore_v3_finance_en", max_pages=2000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multimodal-retrieval-evaluation/retrieval_eval.py* The corpus, queries, retrieval results, and metrics are likewise typed. Page images are stored as `flyte.io.File` handles in blob storage, so tasks read images directly rather than re-fetching over HTTP. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "colpali-engine>=0.3.1", # "transformers>=4.41", # "sentencepiece>=0.2", # "torch>=2.0", # "pillow>=10", # "datasets>=2.18", # "rank-bm25>=0.2", # "numpy>=1.26", # "python-doctr[torch]>=0.8", # "pydantic>=2.0", # "flyte>=2.0.0", # ] # /// """ Multimodal Retrieval Evaluation Pipeline This tutorial is an experiment framework for benchmarking visual document retrieval approaches on the ViDoRe benchmark. Each experiment is defined by an ExperimentConfig; the pipeline fans them out as concurrent Flyte tasks and returns a ranked comparison table with an interactive HTML report. The corpus is a set of PDF page images; queries are plain-text questions. Each retrieval method must find the page that answers each question โ€” no text is provided to the model, only the raw image. ColPali-v1.2 โ€” patch-level multi-vector embeddings from a VLM (PaliGemma). No OCR. The model produces one vector per image patch (~1024 per page). MaxSim late-interaction scoring finds the best matching patch for each query token. SigLIP-SO400M โ€” single global embedding per page from Google's 2023 CLIP successor. One matrix multiply per query; fast and effective but a single vector cannot localise fine-grained regions. OCR + BM25 โ€” text-only baseline. doctr (GPU OCR) extracts text in batches, BM25 matches keywords. Strong on text-dense pages; fails on charts, tables, and figures where content is visual. """ import asyncio import enum import json import math import os import tempfile from functools import lru_cache from io import BytesIO from itertools import islice import numpy as np from PIL import Image as PILImage from pydantic import BaseModel from rank_bm25 import BM25Okapi from extras import DynamicBatcher import flyte import flyte.report from flyte.io import File # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Environments # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One Docker image for all tasks. The PEP 723 header defines Python deps. # ca-certificates is required for HTTPS calls to HuggingFace and blob stores. # {{docs-fragment image}} image = ( flyte.Image.from_uv_script(__file__, name="vidore-eval-v2") .with_apt_packages("ca-certificates", "libxcb1", "libgl1", "libglib2.0-0") # unionai-reuse installs the unionai-actor-bridge binary required by ReusePolicy. # Without it every reusable container exits with StartError (exit code 128). .with_pip_packages("unionai-reuse>=0.1.11") ) # {{/docs-fragment image}} # GPU environment for ColPali image encoding and search. # # ReusePolicy keeps up to 3 warm GPU containers alive between task calls. # Without it, every task invocation cold-starts a new container and downloads # ColPali-v1.2 (~7 GB) from scratch. With it, the container โ€” and the model # weights already loaded into VRAM โ€” is reused for the next task dispatch. # # replicas=1 single warm container โ€” all concurrent shard calls land # here so they share one DynamicBatcher process # concurrency=8 up to 8 query-shard tasks run simultaneously on the # container, all feeding the same DynamicBatcher queue # idle_ttl=120 keep alive 2 min after the last task finishes # scaledown_ttl=60 scale to zero after 1 min of complete inactivity # {{docs-fragment envs}} colpali_indexer = flyte.TaskEnvironment( name="vidore-colpali-indexer", image=image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="A10G:1"), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for SigLIP image encoding and search. # # Separate from the ColPali environment so each model's warm containers # are managed independently โ€” ColPali and SigLIP experiments can scale # without contending for the same pool of reusable containers. siglip_indexer = flyte.TaskEnvironment( name="vidore-siglip-indexer", image=image, resources=flyte.Resources(cpu=4, memory="8Gi", gpu=1), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for doctr OCR. doctr runs DBNet (detection) + CRNN (recognition) # in batches on GPU โ€” much faster than CPU Tesseract. # No ReusePolicy needed: the result is cached, so this task runs at most once. ocr_engine = flyte.TaskEnvironment( name="vidore-ocr-engine", image=image, resources=flyte.Resources(cpu=4, memory="20Gi", gpu=1), ) # Driver: orchestration, BM25 search, evaluation, and reporting. # depends_on ensures the shared Docker image is built before all environments # try to schedule tasks. driver = flyte.TaskEnvironment( name="vidore-driver", image=image, resources=flyte.Resources(cpu=2, memory="12Gi"), depends_on=[colpali_indexer, siglip_indexer, ocr_engine], ) # {{/docs-fragment envs}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Configuration types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment config_types}} class RetrievalModel(str, enum.Enum): """Retrieval backend to evaluate.""" COLPALI = "colpali-v1.2" # multi-vector patch embeddings, MaxSim SIGLIP = "siglip-so400m" # single-vector global embedding, cosine sim OCR_BM25 = "ocr+bm25" # text extracted by Tesseract, ranked by BM25 class ExperimentConfig(BaseModel): """ All knobs for one retrieval experiment. Passed as a typed Flyte input. Because ExperimentConfig is a Pydantic model, Flyte serialises it alongside every task output โ€” so you can always reconstruct which config produced which metric without maintaining a separate log. """ name: str # human-readable label shown in the comparison table model: RetrievalModel top_k: int = 5 # number of pages to retrieve per query # {{/docs-fragment config_types}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Data types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment data_types}} class PageQuery(BaseModel): """One retrieval query with its ground-truth page.""" query_id: str text: str # e.g. "What was revenue growth in Q3?" relevant_page_id: str # one correct page per query class PageDataset(BaseModel): """ A corpus of document page images paired with text queries. page_ids: unique page identifiers (derived from ViDoRe image filenames). page_files: the same pages stored in Flyte's blob store as JPEG File handles. Tasks read images directly from here; no live HTTP. queries: text questions with ground-truth page IDs for evaluation. """ page_ids: list[str] page_files: list[File] queries: list[PageQuery] class Config: arbitrary_types_allowed = True class RetrievalResult(BaseModel): query_id: str ranked_page_ids: list[str] # ordered best โ†’ worst class Metrics(BaseModel): recall_at_k: float ndcg_at_k: float mrr: float k: int class ExperimentResult(BaseModel): config: ExperimentConfig metrics: Metrics # {{/docs-fragment data_types}} class ComparisonReport(BaseModel): results: list[ExperimentResult] def best_by(self, metric: str = "recall_at_k") -> ExperimentResult: return max(self.results, key=lambda r: getattr(r.metrics, metric)) def summary(self) -> str: header = f"{'Experiment':<30} {'Model':<18} {'Recall@K':>10} {'NDCG@K':>8} {'MRR':>7}" sep = "โ”€" * len(header) rows = [header, sep] for r in sorted(self.results, key=lambda x: -x.metrics.recall_at_k): rows.append( f"{r.config.name:<30} " f"{r.config.model.value:<18} " f"{r.metrics.recall_at_k:>10.3f} " f"{r.metrics.ndcg_at_k:>8.3f} " f"{r.metrics.mrr:>7.3f}" ) return "\n".join(rows) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Cached model loaders # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # These functions are at module level so they are shared across all tasks that # run on the same warm container (via ReusePolicy). lru_cache(maxsize=1) means # the model is loaded from disk/HuggingFace exactly once per container process # and kept in GPU memory for every subsequent task dispatch to that container. @lru_cache(maxsize=1) def _colpali_model(): """Load ColPali-v1.2 into GPU memory and cache the result. device_map= is the correct loading pattern for ColPali's PaliGemma backbone; it handles weight placement via accelerate. torch.compile is skipped โ€” ColPali is GPU-compute-bound and the DynamicBatcher's cross- invocation batching is the primary GPU utilisation mechanism. """ import torch from colpali_engine.models import ColPali, ColPaliProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = ColPali.from_pretrained( "vidore/colpali-v1.2", torch_dtype=torch.bfloat16, device_map=device, ) processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.2") return model, processor, device @lru_cache(maxsize=1) def _siglip_model(): """Load SigLIP SO400M into GPU memory, compile it, and cache the result. torch.compile (mode="reduce-overhead") fuses the vision and text encoder transformer layers into optimised CUDA kernels. As with ColPali, the compilation overhead is paid once per warm container lifetime. """ import torch from transformers import AutoModel, AutoProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModel.from_pretrained("google/siglip-so400m-patch14-224").to(device) if device == "cuda": model = torch.compile(model, mode="reduce-overhead") processor = AutoProcessor.from_pretrained("google/siglip-so400m-patch14-224") return model, processor, device @lru_cache(maxsize=1) def _ocr_model(): """Load the doctr OCR predictor onto GPU and cache it. doctr's ocr_predictor bundles a detection model (DBNet) and a recognition model (CRNN/SAR) into a single callable. pretrained=True downloads both model weights from doctr's model zoo on first use. """ import torch from doctr.models import ocr_predictor predictor = ocr_predictor(pretrained=True) if torch.cuda.is_available(): predictor = predictor.cuda() return predictor # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Search batcher singletons # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One DynamicBatcher per model, shared across all concurrent search task # invocations on the same warm container (concurrency=3). Queries from every # concurrent caller are aggregated into a single GPU batch, maximizing # throughput compared to each invocation running its own forward pass. # # Initialised lazily on the first search call via double-checked locking and # lives for the container's lifetime. The process_fn runs GPU work via # asyncio.to_thread so the aggregation loop can continue collecting queries # from other callers while the GPU processes the current batch. # # File is not hashable so alru_cache cannot be used here; module-level state # with asyncio.Lock is the correct pattern. # # Assumption: index_colpali/index_siglip use cache="auto", so the same corpus # always produces the same index File across all callers on this container. If # the index file ever changed between calls, the batcher would silently continue # using the corpus embeddings loaded from the first call. _colpali_batcher: DynamicBatcher | None = None _colpali_batcher_lock = asyncio.Lock() _siglip_batcher: DynamicBatcher | None = None _siglip_batcher_lock = asyncio.Lock() async def _get_colpali_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level ColPali search batcher, creating it on first call.""" global _colpali_batcher if _colpali_batcher is not None: return _colpali_batcher async with _colpali_batcher_lock: if _colpali_batcher is not None: return _colpali_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, n_patches, dim) index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _colpali_model() corpus_emb = corpus_emb.to(device, dtype=torch.float32) async def colpali_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: query_inputs = processor.process_queries([q.text for q in batch]) query_inputs = {k: v.to(device) for k, v in query_inputs.items()} with torch.no_grad(): query_embs = model(**query_inputs).float() # (B, T, D) query_chunk = 8 n_pages = corpus_emb.shape[0] all_scores = torch.empty(len(batch), n_pages, device=device) for start in range(0, len(batch), query_chunk): chunk = query_embs[start : start + query_chunk] all_scores[start : start + query_chunk] = ( torch.einsum("ctd,pjd->ctpj", chunk, corpus_emb) .max(dim=3).values .sum(dim=1) ) sorted_indices = all_scores.argsort(dim=1, descending=True).cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] # Run GPU work in a thread so the event loop โ€” and the batcher's # aggregation loop โ€” remain unblocked while the GPU is busy. return await asyncio.to_thread(_gpu_work) batcher: DynamicBatcher[PageQuery, list[str]] = DynamicBatcher( process_fn=colpali_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _colpali_batcher = batcher return _colpali_batcher async def _get_siglip_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level SigLIP search batcher, creating it on first call.""" global _siglip_batcher if _siglip_batcher is not None: return _siglip_batcher async with _siglip_batcher_lock: if _siglip_batcher is not None: return _siglip_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, dim), L2-normalised index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _siglip_model() corpus_emb = corpus_emb.to(device) async def siglip_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: text_inputs = processor( text=[q.text for q in batch], return_tensors="pt", padding=True, truncation=True, ).to(device) with torch.no_grad(): text_out = model.text_model(**text_inputs) query_embs = text_out.pooler_output # (B, dim) query_embs = query_embs / query_embs.norm(dim=-1, keepdim=True) scores_matrix = corpus_emb @ query_embs.T # (n_pages, B) sorted_indices = scores_matrix.argsort(dim=0, descending=True).T.cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] return await asyncio.to_thread(_gpu_work) batcher = DynamicBatcher( process_fn=siglip_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _siglip_batcher = batcher return _siglip_batcher # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Helpers # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _batches(items: list, batch_size: int): """Yield successive fixed-size batches from a list.""" for start in range(0, len(items), batch_size): yield items[start : start + batch_size] def _load_image_sync(f: File) -> PILImage.Image: """Blocking download + decode. Intended to be called from a thread pool.""" with f.open_sync("rb") as fh: data = fh.read() return PILImage.open(BytesIO(data)).convert("RGB") async def _load_image(f: File) -> PILImage.Image: """Download and decode a page image in a thread-pool worker. asyncio.to_thread runs _load_image_sync in a real OS thread so that blocking network I/O can overlap with GPU-bound forward passes when images are pre-submitted via loop.run_in_executor before the GPU kernel. """ return await asyncio.to_thread(_load_image_sync, f) async def _load_npz(index_file: File) -> np.lib.npyio.NpzFile: """Download an index File to a local temp path and open with np.load.""" with tempfile.NamedTemporaryFile(suffix=".npz", delete=False) as tmp: async with index_file.open("rb") as fh: tmp.write(bytes(await fh.read())) return np.load(tmp.name) def _dcg(relevances: list[int]) -> float: return sum(rel / math.log2(rank + 2) for rank, rel in enumerate(relevances)) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” data loading # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(cache="auto", retries=3) async def load_vidore_pages(subset: str = "docvqa", max_pages: int = 200) -> PageDataset: """ Load a ViDoRe benchmark subset and store page images in Flyte's blob store. Supports two dataset formats: Legacy (subsampled) โ€” single 'test' split with one row per (query, page) pair; fields: image, query, image_filename. streaming=True reads only the rows requested via islice โ€” no full-shard download. Datasets: vidore/docvqa_test_subsampled, vidore/infovqa_test_subsampled V3 โ€” separate corpus / queries / qrels splits following the BEIR retrieval benchmark format. corpus contains page images; queries contains question text; qrels maps query IDs to relevant corpus page IDs (many-to-many). Datasets: vidore/vidore_v3_finance_en (~2 942 pages, 1 854 queries) The first call uploads page images to Flyte's blob store and caches the PageDataset; every subsequent call with the same arguments returns the cached result instantly. retries=3 guards against transient HuggingFace network failures. Available subsets: "docvqa", "infovqa", "vidore_v3_finance_en" """ from datasets import load_dataset subset_map = { "docvqa": "vidore/docvqa_test_subsampled", "infovqa": "vidore/infovqa_test_subsampled", "vidore_v3_finance_en": "vidore/vidore_v3_finance_en", } dataset_name = subset_map.get(subset, f"vidore/{subset}_test_subsampled") # V3 datasets ship with separate corpus / queries / qrels splits. _V3_SUBSETS = {"vidore_v3_finance_en"} if subset in _V3_SUBSETS: # โ”€โ”€ V3 format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # corpus / queries / qrels are HuggingFace configs (name=), not splits. # corpus uses streaming=True so images are decoded one at a time โ€” # loading all 2 942 rows eagerly would hold gigabytes of PIL images in # the driver's RAM simultaneously. qrels and queries are text-only and # small enough to load fully into memory. corpus_ds = load_dataset(dataset_name, name="corpus", split="test", streaming=True) qrels_ds = load_dataset(dataset_name, name="qrels", split="test") queries_ds = load_dataset(dataset_name, name="queries", split="test") # Normalise field names โ€” V3 follows BEIR convention (hyphenated ids). def _col(ds, *candidates): cols = set(ds.column_names) for c in candidates: if c in cols: return c raise KeyError(f"None of {candidates} found in columns {cols}") corpus_id_col = _col(corpus_ds, "corpus-id", "corpus_id", "id", "_id") query_id_col = _col(queries_ds, "query-id", "query_id", "id", "_id") query_text_col = _col(queries_ds, "query", "text") qrel_qid_col = _col(qrels_ds, "query-id", "query_id") qrel_cid_col = _col(qrels_ds, "corpus-id", "corpus_id") # Slice corpus to max_pages, upload each image to Flyte blob store. page_ids: list[str] = [] page_files: list[File] = [] corpus_id_to_page_id: dict[str, str] = {} for i, row in enumerate(islice(corpus_ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue cid = str(row[corpus_id_col]) page_id = f"{subset}_{i:04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) corpus_id_to_page_id[cid] = page_id page_ids.append(page_id) page_files.append(page_file) # Build query_id โ†’ relevant page_id from qrels (first match wins). # Only keep relevance judgements whose corpus page is in our slice. qrel_map: dict[str, str] = {} for row in qrels_ds: qid = str(row[qrel_qid_col]) cid = str(row[qrel_cid_col]) if cid in corpus_id_to_page_id and qid not in qrel_map: qrel_map[qid] = corpus_id_to_page_id[cid] # Collect queries that have at least one relevant page in our slice. queries: list[PageQuery] = [] for row in queries_ds: qid = str(row[query_id_col]) if qid not in qrel_map: continue queries.append( PageQuery( query_id=qid, text=str(row[query_text_col]), relevant_page_id=qrel_map[qid], ) ) else: # โ”€โ”€ Legacy format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Single 'test' split with one row per (query, page) pair. ds = load_dataset(dataset_name, split="test", streaming=True) page_ids = [] page_files = [] queries = [] seen_pages: dict[str, str] = {} # image_filename โ†’ page_id for i, row in enumerate(islice(ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue filename: str = row.get("image_filename") or f"page_{i}" query_text: str = row.get("query", "") if not query_text: continue # Each unique page is uploaded exactly once; multiple queries may # share the same page (same image_filename). if filename not in seen_pages: page_id = f"{subset}_{len(page_ids):04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) seen_pages[filename] = page_id page_ids.append(page_id) page_files.append(page_file) else: page_id = seen_pages[filename] queries.append( PageQuery( query_id=f"q{i:04d}", text=query_text, relevant_page_id=page_id, ) ) print(f"Loaded {len(page_ids)} unique pages, {len(queries)} queries", flush=True) return PageDataset(page_ids=page_ids, page_files=page_files, queries=queries) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” indexing # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @colpali_indexer.task(cache="auto", retries=2) async def index_colpali(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with ColPali-v1.2 and save the multi-vector index. ColPali skips OCR entirely. It feeds the raw page image into PaliGemma (a vision-language model) and produces one embedding vector per image patch โ€” roughly 1,024 patches per page, each of dimension 128. _colpali_model() is an lru_cache'd loader. On a cold container, it downloads and loads the model once. On a warm container (kept alive by ReusePolicy), it returns the already-loaded model instantly from cache โ€” no repeated ~7 GB download. The index is stored as a .npz file in Flyte's blob store: embeddings โ€” float32, shape (n_pages, n_patches, dim) page_ids โ€” matching page ID strings cache="auto" + retries=2: the result is stored permanently on success; transient failures (e.g. HuggingFace rate limits) are retried twice. """ import torch model, processor, device = _colpali_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 4)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor.process_images(images) inputs = {k: v.to(device) for k, v in inputs.items()} with torch.no_grad(): emb = model(**inputs) # (batch, n_patches, dim) all_embeddings.append(emb.cpu().float().numpy()) print(f"ColPali: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, n_patches, dim) out_path = os.path.join(tempfile.gettempdir(), "colpali_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @siglip_indexer.task(cache="auto", retries=2) async def index_siglip(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with SigLIP SO400M and save the single-vector index. SigLIP (2023) is Google's successor to CLIP, trained with sigmoid loss instead of softmax โ€” avoiding the normalisation bottleneck that limits CLIP's scalability. Produces one global embedding per page. _siglip_model() caches the model across warm container reuses. The index is stored as a .npz file: embeddings โ€” float32, shape (n_pages, dim), L2-normalised page_ids โ€” matching page ID strings """ import torch model, processor, device = _siglip_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 8)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor(images=images, return_tensors="pt", padding=True).to(device) with torch.no_grad(): outputs = model.vision_model(**inputs) emb = outputs.pooler_output # (batch, dim) emb = emb / emb.norm(dim=-1, keepdim=True) # L2 normalise all_embeddings.append(emb.cpu().float().numpy()) print(f"SigLIP: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, dim) out_path = os.path.join(tempfile.gettempdir(), "siglip_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @ocr_engine.task(cache="auto") async def extract_page_texts(page_files: list[File]) -> list[str]: """ OCR every page with doctr on GPU to produce a text-only baseline. doctr bundles DBNet (detection) + CRNN/SAR (recognition) into a single callable predictor. Pages are downloaded in parallel then fed in batches of ocr_batch_size. asyncio.to_thread keeps the event loop unblocked during GPU inference. Result structure: result.pages[i].blocks[j].lines[k].words[l].value Cached: the same corpus is OCR'd at most once across all experiments that use the OCR+BM25 backend. """ import gc predictor = _ocr_model() # Process in batches: download each batch just-in-time so only # ocr_batch_size images are in memory at once instead of all 2 000. ocr_batch_size = 8 total = len(page_files) texts: list[str] = [] for start in range(0, total, ocr_batch_size): batch_files = page_files[start : start + ocr_batch_size] batch_images = list( await asyncio.gather(*[asyncio.to_thread(_load_image_sync, f) for f in batch_files]) ) batch_np = [np.array(img) for img in batch_images] del batch_images result = await asyncio.to_thread(predictor, batch_np) del batch_np for page_output in result.pages: texts.append( "\n".join( " ".join(word.value for word in line.words) for block in page_output.blocks for line in block.lines ) ) del result gc.collect() print(f"OCR: processed {min(start + ocr_batch_size, total)}/{total} pages", flush=True) return texts # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” search # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment search_colpali}} @colpali_indexer.task async def search_colpali( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using ColPali MaxSim late interaction via DynamicBatcher. MaxSim score for page p given query q: score(q, p) = ฮฃ_{t โˆˆ query tokens} max_{j โˆˆ page patches} (q_t ยท p_j) Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_colpali invocations on the same warm container (concurrency=8) into a single GPU batch. This keeps the GPU saturated rather than running one small batch per caller. The batcher's process_fn runs GPU work in asyncio.to_thread, so the aggregation loop stays live while the GPU encodes and scores. """ batcher = await _get_colpali_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] # {{/docs-fragment search_colpali}} @siglip_indexer.task async def search_siglip( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using SigLIP cosine similarity via DynamicBatcher. Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_siglip invocations on the same warm container (concurrency=3) into a single GPU batch. SigLIP's single-vector embeddings make full vectorisation safe โ€” the scores matrix (n_pages x n_queries) is small enough to materialise in one GPU call regardless of batch size. """ batcher = await _get_siglip_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] @driver.task async def search_bm25( page_texts: list[str], page_ids: list[str], queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using BM25 over OCR'd text. The standard keyword-based baseline. No GPU required; strong on text-dense pages, weak on visual content that Tesseract cannot read. """ tokenized = [text.lower().split() for text in page_texts] bm25 = BM25Okapi(tokenized) results: list[RetrievalResult] = [] for q in queries: scores = bm25.get_scores(q.text.lower().split()) ranked = sorted(range(len(page_ids)), key=lambda i: -scores[i])[:top_k] results.append( RetrievalResult( query_id=q.query_id, ranked_page_ids=[page_ids[i] for i in ranked], ) ) return results # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” evaluation # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task async def evaluate( results: list[RetrievalResult], ground_truth: list[PageQuery], k: int, ) -> Metrics: """ Compute Recall@K, NDCG@K, and MRR for a single retrieval model. Recall@K โ€” was the correct page in the top-K results? NDCG@K โ€” normalised discounted cumulative gain; rewards earlier hits. MRR โ€” mean reciprocal rank of the first correct result. All three are averaged over all queries. Higher is better. """ gt_map = {q.query_id: q.relevant_page_id for q in ground_truth} recall_vals, ndcg_vals, mrr_vals = [], [], [] for r in results: relevant = gt_map.get(r.query_id, "") top = r.ranked_page_ids[:k] recall_vals.append(1.0 if relevant in top else 0.0) rels = [1 if pid == relevant else 0 for pid in top] idcg = _dcg([1]) # ideal: correct page at rank 1 ndcg_vals.append(_dcg(rels) / idcg if idcg > 0 else 0.0) rr = 0.0 for rank, pid in enumerate(r.ranked_page_ids, start=1): if pid == relevant: rr = 1.0 / rank break mrr_vals.append(rr) return Metrics( recall_at_k=float(np.mean(recall_vals)), ndcg_at_k=float(np.mean(ndcg_vals)), mrr=float(np.mean(mrr_vals)), k=k, ) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” report # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(report=True) async def generate_report(report: ComparisonReport) -> None: """ Emit an interactive HTML report visible in the Flyte UI. report=True marks this task as a reporting task. Flyte renders the HTML returned via flyte.report.replace.aio() directly in the execution detail page โ€” no separate dashboard or export step required. The report contains: - Summary cards: experiment count, best model, best Recall@K. - Grouped bar chart: Recall@K, NDCG@K, MRR side-by-side per experiment. - Ranked results table with all three metrics. """ sorted_results = sorted(report.results, key=lambda r: -r.metrics.recall_at_k) best = sorted_results[0] labels = [r.config.name for r in sorted_results] recall_vals = [r.metrics.recall_at_k for r in sorted_results] ndcg_vals = [r.metrics.ndcg_at_k for r in sorted_results] mrr_vals = [r.metrics.mrr for r in sorted_results] table_rows = "".join( f""" {r.config.name} {r.config.model.value} {r.metrics.recall_at_k:.3f} {r.metrics.ndcg_at_k:.3f} {r.metrics.mrr:.3f} {r.metrics.k} """ for r in sorted_results ) html = f""" Visual Document Retrieval โ€” Results

Visual Document Retrieval โ€” Experiment Comparison

ViDoRe benchmark · {len(report.results)} experiment(s)

{len(report.results)}
Experiments
{best.config.name}
Best by Recall@K
{best.metrics.recall_at_k:.3f}
Best Recall@{best.metrics.k}
{best.metrics.ndcg_at_k:.3f}
Best NDCG@{best.metrics.k}
{best.metrics.mrr:.3f}
Best MRR

Metrics by Experiment

Ranked Results

{table_rows}
ExperimentModel Recall@KNDCG@KMRRK
""" await flyte.report.replace.aio(html) await flyte.report.flush.aio() # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Experiment orchestration # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment run_experiment}} @driver.task async def run_experiment(config: ExperimentConfig, dataset: PageDataset) -> ExperimentResult: """ End-to-end retrieval pipeline for a single ExperimentConfig. Flyte v2's dynamic execution means this driver task can call GPU tasks (index_colpali, search_colpali) based on the runtime value of config.model โ€” no static DAG wiring required. The if/elif is plain Python; Flyte schedules the selected sub-tasks on the appropriate environment. Caching: two experiments that share the same model and corpus (e.g. ColPali at top_k=5 and top_k=10) will hit the same cached index. GPU work is paid at most once per (model, corpus) pair across all experiments. Search queries are sharded into chunks of SEARCH_SHARD_SIZE and dispatched as concurrent task invocations. All shards land on the single warm container (replicas=1) and feed the same DynamicBatcher simultaneously, keeping the GPU saturated throughout search rather than processing one large sequential batch from a single caller. flyte.group wraps each experiment in a named span in the Flyte UI, making it easy to compare latencies and drill into individual runs. """ SEARCH_SHARD_SIZE = 256 with flyte.group(config.name): if config.model == RetrievalModel.COLPALI: index_file = await index_colpali(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_colpali(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] elif config.model == RetrievalModel.SIGLIP: index_file = await index_siglip(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_siglip(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] else: # RetrievalModel.OCR_BM25 page_texts = await extract_page_texts(dataset.page_files) results = await search_bm25(page_texts, dataset.page_ids, dataset.queries, config.top_k) metrics = await evaluate(results, dataset.queries, config.top_k) return ExperimentResult(config=config, metrics=metrics) # {{/docs-fragment run_experiment}} # {{docs-fragment compare_experiments}} @driver.task async def compare_experiments( configs: list[ExperimentConfig], subset: str = "docvqa", max_pages: int = 200, ) -> ComparisonReport: """ Fan out over all experiment configs and return a ranked comparison table. The dataset is loaded once and shared across all experiments. Each config runs as a concurrent Flyte task via asyncio.gather. Experiments that share a model reuse the cached index โ€” you only pay GPU time for new work. On completion, generate_report emits an interactive Chart.js HTML report visible directly in the Flyte execution detail page. Default dataset: vidore_v3_finance_en (~2 942 corpus pages, 1 854 queries) with max_pages=2 000 to exercise the GPU pipeline at scale. """ dataset = await load_vidore_pages(subset=subset, max_pages=max_pages) # All experiments launch concurrently. Shared cached outputs (same model, # same corpus) are served from cache rather than recomputed. experiment_coros = [run_experiment(config=cfg, dataset=dataset) for cfg in configs] results: list[ExperimentResult] = list(await asyncio.gather(*experiment_coros)) report = ComparisonReport(results=results) print(report.summary()) best = report.best_by("recall_at_k") print(f"\nBest by Recall@{best.metrics.k}: {best.config.name}") # Emit the interactive HTML report in the Flyte UI. await generate_report(report) return report # {{/docs-fragment compare_experiments}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Entry point # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if __name__ == "__main__": flyte.init_from_config() # Define the experiment grid. Each ExperimentConfig is one point in the # design space. Adding a new model or varying top_k is one line here โ€” # no task code changes required. # # ColPali appears twice with different top_k values. The cache ensures # index_colpali runs only once and both experiments share that result. # {{docs-fragment grid}} configs = [ ExperimentConfig(name="colpali-top5", model=RetrievalModel.COLPALI, top_k=5), ExperimentConfig(name="colpali-top10", model=RetrievalModel.COLPALI, top_k=10), ExperimentConfig(name="siglip-top5", model=RetrievalModel.SIGLIP, top_k=5), ExperimentConfig(name="ocr-bm25-top5", model=RetrievalModel.OCR_BM25, top_k=5), ] # {{/docs-fragment grid}} run = flyte.with_runcontext().run( compare_experiments, configs=configs, subset="vidore_v3_finance_en", max_pages=2000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multimodal-retrieval-evaluation/retrieval_eval.py* ## Loading, indexing, and search `load_vidore_pages` downloads a ViDoRe subset and uploads each page image to blob storage (cached, with retries). Indexing tasks (`index_colpali`, `index_siglip`) encode every page into a `.npz` index, and the OCR task (`extract_page_texts`) produces the text baseline. These run on the GPU environments and are cached per corpus. Search uses the `DynamicBatcher` so queries from all concurrent search-task invocations on a warm container are merged into a single GPU batch: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "colpali-engine>=0.3.1", # "transformers>=4.41", # "sentencepiece>=0.2", # "torch>=2.0", # "pillow>=10", # "datasets>=2.18", # "rank-bm25>=0.2", # "numpy>=1.26", # "python-doctr[torch]>=0.8", # "pydantic>=2.0", # "flyte>=2.0.0", # ] # /// """ Multimodal Retrieval Evaluation Pipeline This tutorial is an experiment framework for benchmarking visual document retrieval approaches on the ViDoRe benchmark. Each experiment is defined by an ExperimentConfig; the pipeline fans them out as concurrent Flyte tasks and returns a ranked comparison table with an interactive HTML report. The corpus is a set of PDF page images; queries are plain-text questions. Each retrieval method must find the page that answers each question โ€” no text is provided to the model, only the raw image. ColPali-v1.2 โ€” patch-level multi-vector embeddings from a VLM (PaliGemma). No OCR. The model produces one vector per image patch (~1024 per page). MaxSim late-interaction scoring finds the best matching patch for each query token. SigLIP-SO400M โ€” single global embedding per page from Google's 2023 CLIP successor. One matrix multiply per query; fast and effective but a single vector cannot localise fine-grained regions. OCR + BM25 โ€” text-only baseline. doctr (GPU OCR) extracts text in batches, BM25 matches keywords. Strong on text-dense pages; fails on charts, tables, and figures where content is visual. """ import asyncio import enum import json import math import os import tempfile from functools import lru_cache from io import BytesIO from itertools import islice import numpy as np from PIL import Image as PILImage from pydantic import BaseModel from rank_bm25 import BM25Okapi from extras import DynamicBatcher import flyte import flyte.report from flyte.io import File # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Environments # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One Docker image for all tasks. The PEP 723 header defines Python deps. # ca-certificates is required for HTTPS calls to HuggingFace and blob stores. # {{docs-fragment image}} image = ( flyte.Image.from_uv_script(__file__, name="vidore-eval-v2") .with_apt_packages("ca-certificates", "libxcb1", "libgl1", "libglib2.0-0") # unionai-reuse installs the unionai-actor-bridge binary required by ReusePolicy. # Without it every reusable container exits with StartError (exit code 128). .with_pip_packages("unionai-reuse>=0.1.11") ) # {{/docs-fragment image}} # GPU environment for ColPali image encoding and search. # # ReusePolicy keeps up to 3 warm GPU containers alive between task calls. # Without it, every task invocation cold-starts a new container and downloads # ColPali-v1.2 (~7 GB) from scratch. With it, the container โ€” and the model # weights already loaded into VRAM โ€” is reused for the next task dispatch. # # replicas=1 single warm container โ€” all concurrent shard calls land # here so they share one DynamicBatcher process # concurrency=8 up to 8 query-shard tasks run simultaneously on the # container, all feeding the same DynamicBatcher queue # idle_ttl=120 keep alive 2 min after the last task finishes # scaledown_ttl=60 scale to zero after 1 min of complete inactivity # {{docs-fragment envs}} colpali_indexer = flyte.TaskEnvironment( name="vidore-colpali-indexer", image=image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="A10G:1"), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for SigLIP image encoding and search. # # Separate from the ColPali environment so each model's warm containers # are managed independently โ€” ColPali and SigLIP experiments can scale # without contending for the same pool of reusable containers. siglip_indexer = flyte.TaskEnvironment( name="vidore-siglip-indexer", image=image, resources=flyte.Resources(cpu=4, memory="8Gi", gpu=1), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for doctr OCR. doctr runs DBNet (detection) + CRNN (recognition) # in batches on GPU โ€” much faster than CPU Tesseract. # No ReusePolicy needed: the result is cached, so this task runs at most once. ocr_engine = flyte.TaskEnvironment( name="vidore-ocr-engine", image=image, resources=flyte.Resources(cpu=4, memory="20Gi", gpu=1), ) # Driver: orchestration, BM25 search, evaluation, and reporting. # depends_on ensures the shared Docker image is built before all environments # try to schedule tasks. driver = flyte.TaskEnvironment( name="vidore-driver", image=image, resources=flyte.Resources(cpu=2, memory="12Gi"), depends_on=[colpali_indexer, siglip_indexer, ocr_engine], ) # {{/docs-fragment envs}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Configuration types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment config_types}} class RetrievalModel(str, enum.Enum): """Retrieval backend to evaluate.""" COLPALI = "colpali-v1.2" # multi-vector patch embeddings, MaxSim SIGLIP = "siglip-so400m" # single-vector global embedding, cosine sim OCR_BM25 = "ocr+bm25" # text extracted by Tesseract, ranked by BM25 class ExperimentConfig(BaseModel): """ All knobs for one retrieval experiment. Passed as a typed Flyte input. Because ExperimentConfig is a Pydantic model, Flyte serialises it alongside every task output โ€” so you can always reconstruct which config produced which metric without maintaining a separate log. """ name: str # human-readable label shown in the comparison table model: RetrievalModel top_k: int = 5 # number of pages to retrieve per query # {{/docs-fragment config_types}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Data types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment data_types}} class PageQuery(BaseModel): """One retrieval query with its ground-truth page.""" query_id: str text: str # e.g. "What was revenue growth in Q3?" relevant_page_id: str # one correct page per query class PageDataset(BaseModel): """ A corpus of document page images paired with text queries. page_ids: unique page identifiers (derived from ViDoRe image filenames). page_files: the same pages stored in Flyte's blob store as JPEG File handles. Tasks read images directly from here; no live HTTP. queries: text questions with ground-truth page IDs for evaluation. """ page_ids: list[str] page_files: list[File] queries: list[PageQuery] class Config: arbitrary_types_allowed = True class RetrievalResult(BaseModel): query_id: str ranked_page_ids: list[str] # ordered best โ†’ worst class Metrics(BaseModel): recall_at_k: float ndcg_at_k: float mrr: float k: int class ExperimentResult(BaseModel): config: ExperimentConfig metrics: Metrics # {{/docs-fragment data_types}} class ComparisonReport(BaseModel): results: list[ExperimentResult] def best_by(self, metric: str = "recall_at_k") -> ExperimentResult: return max(self.results, key=lambda r: getattr(r.metrics, metric)) def summary(self) -> str: header = f"{'Experiment':<30} {'Model':<18} {'Recall@K':>10} {'NDCG@K':>8} {'MRR':>7}" sep = "โ”€" * len(header) rows = [header, sep] for r in sorted(self.results, key=lambda x: -x.metrics.recall_at_k): rows.append( f"{r.config.name:<30} " f"{r.config.model.value:<18} " f"{r.metrics.recall_at_k:>10.3f} " f"{r.metrics.ndcg_at_k:>8.3f} " f"{r.metrics.mrr:>7.3f}" ) return "\n".join(rows) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Cached model loaders # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # These functions are at module level so they are shared across all tasks that # run on the same warm container (via ReusePolicy). lru_cache(maxsize=1) means # the model is loaded from disk/HuggingFace exactly once per container process # and kept in GPU memory for every subsequent task dispatch to that container. @lru_cache(maxsize=1) def _colpali_model(): """Load ColPali-v1.2 into GPU memory and cache the result. device_map= is the correct loading pattern for ColPali's PaliGemma backbone; it handles weight placement via accelerate. torch.compile is skipped โ€” ColPali is GPU-compute-bound and the DynamicBatcher's cross- invocation batching is the primary GPU utilisation mechanism. """ import torch from colpali_engine.models import ColPali, ColPaliProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = ColPali.from_pretrained( "vidore/colpali-v1.2", torch_dtype=torch.bfloat16, device_map=device, ) processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.2") return model, processor, device @lru_cache(maxsize=1) def _siglip_model(): """Load SigLIP SO400M into GPU memory, compile it, and cache the result. torch.compile (mode="reduce-overhead") fuses the vision and text encoder transformer layers into optimised CUDA kernels. As with ColPali, the compilation overhead is paid once per warm container lifetime. """ import torch from transformers import AutoModel, AutoProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModel.from_pretrained("google/siglip-so400m-patch14-224").to(device) if device == "cuda": model = torch.compile(model, mode="reduce-overhead") processor = AutoProcessor.from_pretrained("google/siglip-so400m-patch14-224") return model, processor, device @lru_cache(maxsize=1) def _ocr_model(): """Load the doctr OCR predictor onto GPU and cache it. doctr's ocr_predictor bundles a detection model (DBNet) and a recognition model (CRNN/SAR) into a single callable. pretrained=True downloads both model weights from doctr's model zoo on first use. """ import torch from doctr.models import ocr_predictor predictor = ocr_predictor(pretrained=True) if torch.cuda.is_available(): predictor = predictor.cuda() return predictor # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Search batcher singletons # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One DynamicBatcher per model, shared across all concurrent search task # invocations on the same warm container (concurrency=3). Queries from every # concurrent caller are aggregated into a single GPU batch, maximizing # throughput compared to each invocation running its own forward pass. # # Initialised lazily on the first search call via double-checked locking and # lives for the container's lifetime. The process_fn runs GPU work via # asyncio.to_thread so the aggregation loop can continue collecting queries # from other callers while the GPU processes the current batch. # # File is not hashable so alru_cache cannot be used here; module-level state # with asyncio.Lock is the correct pattern. # # Assumption: index_colpali/index_siglip use cache="auto", so the same corpus # always produces the same index File across all callers on this container. If # the index file ever changed between calls, the batcher would silently continue # using the corpus embeddings loaded from the first call. _colpali_batcher: DynamicBatcher | None = None _colpali_batcher_lock = asyncio.Lock() _siglip_batcher: DynamicBatcher | None = None _siglip_batcher_lock = asyncio.Lock() async def _get_colpali_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level ColPali search batcher, creating it on first call.""" global _colpali_batcher if _colpali_batcher is not None: return _colpali_batcher async with _colpali_batcher_lock: if _colpali_batcher is not None: return _colpali_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, n_patches, dim) index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _colpali_model() corpus_emb = corpus_emb.to(device, dtype=torch.float32) async def colpali_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: query_inputs = processor.process_queries([q.text for q in batch]) query_inputs = {k: v.to(device) for k, v in query_inputs.items()} with torch.no_grad(): query_embs = model(**query_inputs).float() # (B, T, D) query_chunk = 8 n_pages = corpus_emb.shape[0] all_scores = torch.empty(len(batch), n_pages, device=device) for start in range(0, len(batch), query_chunk): chunk = query_embs[start : start + query_chunk] all_scores[start : start + query_chunk] = ( torch.einsum("ctd,pjd->ctpj", chunk, corpus_emb) .max(dim=3).values .sum(dim=1) ) sorted_indices = all_scores.argsort(dim=1, descending=True).cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] # Run GPU work in a thread so the event loop โ€” and the batcher's # aggregation loop โ€” remain unblocked while the GPU is busy. return await asyncio.to_thread(_gpu_work) batcher: DynamicBatcher[PageQuery, list[str]] = DynamicBatcher( process_fn=colpali_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _colpali_batcher = batcher return _colpali_batcher async def _get_siglip_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level SigLIP search batcher, creating it on first call.""" global _siglip_batcher if _siglip_batcher is not None: return _siglip_batcher async with _siglip_batcher_lock: if _siglip_batcher is not None: return _siglip_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, dim), L2-normalised index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _siglip_model() corpus_emb = corpus_emb.to(device) async def siglip_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: text_inputs = processor( text=[q.text for q in batch], return_tensors="pt", padding=True, truncation=True, ).to(device) with torch.no_grad(): text_out = model.text_model(**text_inputs) query_embs = text_out.pooler_output # (B, dim) query_embs = query_embs / query_embs.norm(dim=-1, keepdim=True) scores_matrix = corpus_emb @ query_embs.T # (n_pages, B) sorted_indices = scores_matrix.argsort(dim=0, descending=True).T.cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] return await asyncio.to_thread(_gpu_work) batcher = DynamicBatcher( process_fn=siglip_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _siglip_batcher = batcher return _siglip_batcher # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Helpers # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _batches(items: list, batch_size: int): """Yield successive fixed-size batches from a list.""" for start in range(0, len(items), batch_size): yield items[start : start + batch_size] def _load_image_sync(f: File) -> PILImage.Image: """Blocking download + decode. Intended to be called from a thread pool.""" with f.open_sync("rb") as fh: data = fh.read() return PILImage.open(BytesIO(data)).convert("RGB") async def _load_image(f: File) -> PILImage.Image: """Download and decode a page image in a thread-pool worker. asyncio.to_thread runs _load_image_sync in a real OS thread so that blocking network I/O can overlap with GPU-bound forward passes when images are pre-submitted via loop.run_in_executor before the GPU kernel. """ return await asyncio.to_thread(_load_image_sync, f) async def _load_npz(index_file: File) -> np.lib.npyio.NpzFile: """Download an index File to a local temp path and open with np.load.""" with tempfile.NamedTemporaryFile(suffix=".npz", delete=False) as tmp: async with index_file.open("rb") as fh: tmp.write(bytes(await fh.read())) return np.load(tmp.name) def _dcg(relevances: list[int]) -> float: return sum(rel / math.log2(rank + 2) for rank, rel in enumerate(relevances)) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” data loading # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(cache="auto", retries=3) async def load_vidore_pages(subset: str = "docvqa", max_pages: int = 200) -> PageDataset: """ Load a ViDoRe benchmark subset and store page images in Flyte's blob store. Supports two dataset formats: Legacy (subsampled) โ€” single 'test' split with one row per (query, page) pair; fields: image, query, image_filename. streaming=True reads only the rows requested via islice โ€” no full-shard download. Datasets: vidore/docvqa_test_subsampled, vidore/infovqa_test_subsampled V3 โ€” separate corpus / queries / qrels splits following the BEIR retrieval benchmark format. corpus contains page images; queries contains question text; qrels maps query IDs to relevant corpus page IDs (many-to-many). Datasets: vidore/vidore_v3_finance_en (~2 942 pages, 1 854 queries) The first call uploads page images to Flyte's blob store and caches the PageDataset; every subsequent call with the same arguments returns the cached result instantly. retries=3 guards against transient HuggingFace network failures. Available subsets: "docvqa", "infovqa", "vidore_v3_finance_en" """ from datasets import load_dataset subset_map = { "docvqa": "vidore/docvqa_test_subsampled", "infovqa": "vidore/infovqa_test_subsampled", "vidore_v3_finance_en": "vidore/vidore_v3_finance_en", } dataset_name = subset_map.get(subset, f"vidore/{subset}_test_subsampled") # V3 datasets ship with separate corpus / queries / qrels splits. _V3_SUBSETS = {"vidore_v3_finance_en"} if subset in _V3_SUBSETS: # โ”€โ”€ V3 format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # corpus / queries / qrels are HuggingFace configs (name=), not splits. # corpus uses streaming=True so images are decoded one at a time โ€” # loading all 2 942 rows eagerly would hold gigabytes of PIL images in # the driver's RAM simultaneously. qrels and queries are text-only and # small enough to load fully into memory. corpus_ds = load_dataset(dataset_name, name="corpus", split="test", streaming=True) qrels_ds = load_dataset(dataset_name, name="qrels", split="test") queries_ds = load_dataset(dataset_name, name="queries", split="test") # Normalise field names โ€” V3 follows BEIR convention (hyphenated ids). def _col(ds, *candidates): cols = set(ds.column_names) for c in candidates: if c in cols: return c raise KeyError(f"None of {candidates} found in columns {cols}") corpus_id_col = _col(corpus_ds, "corpus-id", "corpus_id", "id", "_id") query_id_col = _col(queries_ds, "query-id", "query_id", "id", "_id") query_text_col = _col(queries_ds, "query", "text") qrel_qid_col = _col(qrels_ds, "query-id", "query_id") qrel_cid_col = _col(qrels_ds, "corpus-id", "corpus_id") # Slice corpus to max_pages, upload each image to Flyte blob store. page_ids: list[str] = [] page_files: list[File] = [] corpus_id_to_page_id: dict[str, str] = {} for i, row in enumerate(islice(corpus_ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue cid = str(row[corpus_id_col]) page_id = f"{subset}_{i:04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) corpus_id_to_page_id[cid] = page_id page_ids.append(page_id) page_files.append(page_file) # Build query_id โ†’ relevant page_id from qrels (first match wins). # Only keep relevance judgements whose corpus page is in our slice. qrel_map: dict[str, str] = {} for row in qrels_ds: qid = str(row[qrel_qid_col]) cid = str(row[qrel_cid_col]) if cid in corpus_id_to_page_id and qid not in qrel_map: qrel_map[qid] = corpus_id_to_page_id[cid] # Collect queries that have at least one relevant page in our slice. queries: list[PageQuery] = [] for row in queries_ds: qid = str(row[query_id_col]) if qid not in qrel_map: continue queries.append( PageQuery( query_id=qid, text=str(row[query_text_col]), relevant_page_id=qrel_map[qid], ) ) else: # โ”€โ”€ Legacy format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Single 'test' split with one row per (query, page) pair. ds = load_dataset(dataset_name, split="test", streaming=True) page_ids = [] page_files = [] queries = [] seen_pages: dict[str, str] = {} # image_filename โ†’ page_id for i, row in enumerate(islice(ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue filename: str = row.get("image_filename") or f"page_{i}" query_text: str = row.get("query", "") if not query_text: continue # Each unique page is uploaded exactly once; multiple queries may # share the same page (same image_filename). if filename not in seen_pages: page_id = f"{subset}_{len(page_ids):04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) seen_pages[filename] = page_id page_ids.append(page_id) page_files.append(page_file) else: page_id = seen_pages[filename] queries.append( PageQuery( query_id=f"q{i:04d}", text=query_text, relevant_page_id=page_id, ) ) print(f"Loaded {len(page_ids)} unique pages, {len(queries)} queries", flush=True) return PageDataset(page_ids=page_ids, page_files=page_files, queries=queries) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” indexing # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @colpali_indexer.task(cache="auto", retries=2) async def index_colpali(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with ColPali-v1.2 and save the multi-vector index. ColPali skips OCR entirely. It feeds the raw page image into PaliGemma (a vision-language model) and produces one embedding vector per image patch โ€” roughly 1,024 patches per page, each of dimension 128. _colpali_model() is an lru_cache'd loader. On a cold container, it downloads and loads the model once. On a warm container (kept alive by ReusePolicy), it returns the already-loaded model instantly from cache โ€” no repeated ~7 GB download. The index is stored as a .npz file in Flyte's blob store: embeddings โ€” float32, shape (n_pages, n_patches, dim) page_ids โ€” matching page ID strings cache="auto" + retries=2: the result is stored permanently on success; transient failures (e.g. HuggingFace rate limits) are retried twice. """ import torch model, processor, device = _colpali_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 4)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor.process_images(images) inputs = {k: v.to(device) for k, v in inputs.items()} with torch.no_grad(): emb = model(**inputs) # (batch, n_patches, dim) all_embeddings.append(emb.cpu().float().numpy()) print(f"ColPali: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, n_patches, dim) out_path = os.path.join(tempfile.gettempdir(), "colpali_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @siglip_indexer.task(cache="auto", retries=2) async def index_siglip(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with SigLIP SO400M and save the single-vector index. SigLIP (2023) is Google's successor to CLIP, trained with sigmoid loss instead of softmax โ€” avoiding the normalisation bottleneck that limits CLIP's scalability. Produces one global embedding per page. _siglip_model() caches the model across warm container reuses. The index is stored as a .npz file: embeddings โ€” float32, shape (n_pages, dim), L2-normalised page_ids โ€” matching page ID strings """ import torch model, processor, device = _siglip_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 8)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor(images=images, return_tensors="pt", padding=True).to(device) with torch.no_grad(): outputs = model.vision_model(**inputs) emb = outputs.pooler_output # (batch, dim) emb = emb / emb.norm(dim=-1, keepdim=True) # L2 normalise all_embeddings.append(emb.cpu().float().numpy()) print(f"SigLIP: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, dim) out_path = os.path.join(tempfile.gettempdir(), "siglip_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @ocr_engine.task(cache="auto") async def extract_page_texts(page_files: list[File]) -> list[str]: """ OCR every page with doctr on GPU to produce a text-only baseline. doctr bundles DBNet (detection) + CRNN/SAR (recognition) into a single callable predictor. Pages are downloaded in parallel then fed in batches of ocr_batch_size. asyncio.to_thread keeps the event loop unblocked during GPU inference. Result structure: result.pages[i].blocks[j].lines[k].words[l].value Cached: the same corpus is OCR'd at most once across all experiments that use the OCR+BM25 backend. """ import gc predictor = _ocr_model() # Process in batches: download each batch just-in-time so only # ocr_batch_size images are in memory at once instead of all 2 000. ocr_batch_size = 8 total = len(page_files) texts: list[str] = [] for start in range(0, total, ocr_batch_size): batch_files = page_files[start : start + ocr_batch_size] batch_images = list( await asyncio.gather(*[asyncio.to_thread(_load_image_sync, f) for f in batch_files]) ) batch_np = [np.array(img) for img in batch_images] del batch_images result = await asyncio.to_thread(predictor, batch_np) del batch_np for page_output in result.pages: texts.append( "\n".join( " ".join(word.value for word in line.words) for block in page_output.blocks for line in block.lines ) ) del result gc.collect() print(f"OCR: processed {min(start + ocr_batch_size, total)}/{total} pages", flush=True) return texts # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” search # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment search_colpali}} @colpali_indexer.task async def search_colpali( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using ColPali MaxSim late interaction via DynamicBatcher. MaxSim score for page p given query q: score(q, p) = ฮฃ_{t โˆˆ query tokens} max_{j โˆˆ page patches} (q_t ยท p_j) Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_colpali invocations on the same warm container (concurrency=8) into a single GPU batch. This keeps the GPU saturated rather than running one small batch per caller. The batcher's process_fn runs GPU work in asyncio.to_thread, so the aggregation loop stays live while the GPU encodes and scores. """ batcher = await _get_colpali_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] # {{/docs-fragment search_colpali}} @siglip_indexer.task async def search_siglip( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using SigLIP cosine similarity via DynamicBatcher. Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_siglip invocations on the same warm container (concurrency=3) into a single GPU batch. SigLIP's single-vector embeddings make full vectorisation safe โ€” the scores matrix (n_pages x n_queries) is small enough to materialise in one GPU call regardless of batch size. """ batcher = await _get_siglip_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] @driver.task async def search_bm25( page_texts: list[str], page_ids: list[str], queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using BM25 over OCR'd text. The standard keyword-based baseline. No GPU required; strong on text-dense pages, weak on visual content that Tesseract cannot read. """ tokenized = [text.lower().split() for text in page_texts] bm25 = BM25Okapi(tokenized) results: list[RetrievalResult] = [] for q in queries: scores = bm25.get_scores(q.text.lower().split()) ranked = sorted(range(len(page_ids)), key=lambda i: -scores[i])[:top_k] results.append( RetrievalResult( query_id=q.query_id, ranked_page_ids=[page_ids[i] for i in ranked], ) ) return results # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” evaluation # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task async def evaluate( results: list[RetrievalResult], ground_truth: list[PageQuery], k: int, ) -> Metrics: """ Compute Recall@K, NDCG@K, and MRR for a single retrieval model. Recall@K โ€” was the correct page in the top-K results? NDCG@K โ€” normalised discounted cumulative gain; rewards earlier hits. MRR โ€” mean reciprocal rank of the first correct result. All three are averaged over all queries. Higher is better. """ gt_map = {q.query_id: q.relevant_page_id for q in ground_truth} recall_vals, ndcg_vals, mrr_vals = [], [], [] for r in results: relevant = gt_map.get(r.query_id, "") top = r.ranked_page_ids[:k] recall_vals.append(1.0 if relevant in top else 0.0) rels = [1 if pid == relevant else 0 for pid in top] idcg = _dcg([1]) # ideal: correct page at rank 1 ndcg_vals.append(_dcg(rels) / idcg if idcg > 0 else 0.0) rr = 0.0 for rank, pid in enumerate(r.ranked_page_ids, start=1): if pid == relevant: rr = 1.0 / rank break mrr_vals.append(rr) return Metrics( recall_at_k=float(np.mean(recall_vals)), ndcg_at_k=float(np.mean(ndcg_vals)), mrr=float(np.mean(mrr_vals)), k=k, ) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” report # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(report=True) async def generate_report(report: ComparisonReport) -> None: """ Emit an interactive HTML report visible in the Flyte UI. report=True marks this task as a reporting task. Flyte renders the HTML returned via flyte.report.replace.aio() directly in the execution detail page โ€” no separate dashboard or export step required. The report contains: - Summary cards: experiment count, best model, best Recall@K. - Grouped bar chart: Recall@K, NDCG@K, MRR side-by-side per experiment. - Ranked results table with all three metrics. """ sorted_results = sorted(report.results, key=lambda r: -r.metrics.recall_at_k) best = sorted_results[0] labels = [r.config.name for r in sorted_results] recall_vals = [r.metrics.recall_at_k for r in sorted_results] ndcg_vals = [r.metrics.ndcg_at_k for r in sorted_results] mrr_vals = [r.metrics.mrr for r in sorted_results] table_rows = "".join( f""" {r.config.name} {r.config.model.value} {r.metrics.recall_at_k:.3f} {r.metrics.ndcg_at_k:.3f} {r.metrics.mrr:.3f} {r.metrics.k} """ for r in sorted_results ) html = f""" Visual Document Retrieval โ€” Results

Visual Document Retrieval โ€” Experiment Comparison

ViDoRe benchmark · {len(report.results)} experiment(s)

{len(report.results)}
Experiments
{best.config.name}
Best by Recall@K
{best.metrics.recall_at_k:.3f}
Best Recall@{best.metrics.k}
{best.metrics.ndcg_at_k:.3f}
Best NDCG@{best.metrics.k}
{best.metrics.mrr:.3f}
Best MRR

Metrics by Experiment

Ranked Results

{table_rows}
ExperimentModel Recall@KNDCG@KMRRK
""" await flyte.report.replace.aio(html) await flyte.report.flush.aio() # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Experiment orchestration # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment run_experiment}} @driver.task async def run_experiment(config: ExperimentConfig, dataset: PageDataset) -> ExperimentResult: """ End-to-end retrieval pipeline for a single ExperimentConfig. Flyte v2's dynamic execution means this driver task can call GPU tasks (index_colpali, search_colpali) based on the runtime value of config.model โ€” no static DAG wiring required. The if/elif is plain Python; Flyte schedules the selected sub-tasks on the appropriate environment. Caching: two experiments that share the same model and corpus (e.g. ColPali at top_k=5 and top_k=10) will hit the same cached index. GPU work is paid at most once per (model, corpus) pair across all experiments. Search queries are sharded into chunks of SEARCH_SHARD_SIZE and dispatched as concurrent task invocations. All shards land on the single warm container (replicas=1) and feed the same DynamicBatcher simultaneously, keeping the GPU saturated throughout search rather than processing one large sequential batch from a single caller. flyte.group wraps each experiment in a named span in the Flyte UI, making it easy to compare latencies and drill into individual runs. """ SEARCH_SHARD_SIZE = 256 with flyte.group(config.name): if config.model == RetrievalModel.COLPALI: index_file = await index_colpali(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_colpali(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] elif config.model == RetrievalModel.SIGLIP: index_file = await index_siglip(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_siglip(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] else: # RetrievalModel.OCR_BM25 page_texts = await extract_page_texts(dataset.page_files) results = await search_bm25(page_texts, dataset.page_ids, dataset.queries, config.top_k) metrics = await evaluate(results, dataset.queries, config.top_k) return ExperimentResult(config=config, metrics=metrics) # {{/docs-fragment run_experiment}} # {{docs-fragment compare_experiments}} @driver.task async def compare_experiments( configs: list[ExperimentConfig], subset: str = "docvqa", max_pages: int = 200, ) -> ComparisonReport: """ Fan out over all experiment configs and return a ranked comparison table. The dataset is loaded once and shared across all experiments. Each config runs as a concurrent Flyte task via asyncio.gather. Experiments that share a model reuse the cached index โ€” you only pay GPU time for new work. On completion, generate_report emits an interactive Chart.js HTML report visible directly in the Flyte execution detail page. Default dataset: vidore_v3_finance_en (~2 942 corpus pages, 1 854 queries) with max_pages=2 000 to exercise the GPU pipeline at scale. """ dataset = await load_vidore_pages(subset=subset, max_pages=max_pages) # All experiments launch concurrently. Shared cached outputs (same model, # same corpus) are served from cache rather than recomputed. experiment_coros = [run_experiment(config=cfg, dataset=dataset) for cfg in configs] results: list[ExperimentResult] = list(await asyncio.gather(*experiment_coros)) report = ComparisonReport(results=results) print(report.summary()) best = report.best_by("recall_at_k") print(f"\nBest by Recall@{best.metrics.k}: {best.config.name}") # Emit the interactive HTML report in the Flyte UI. await generate_report(report) return report # {{/docs-fragment compare_experiments}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Entry point # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if __name__ == "__main__": flyte.init_from_config() # Define the experiment grid. Each ExperimentConfig is one point in the # design space. Adding a new model or varying top_k is one line here โ€” # no task code changes required. # # ColPali appears twice with different top_k values. The cache ensures # index_colpali runs only once and both experiments share that result. # {{docs-fragment grid}} configs = [ ExperimentConfig(name="colpali-top5", model=RetrievalModel.COLPALI, top_k=5), ExperimentConfig(name="colpali-top10", model=RetrievalModel.COLPALI, top_k=10), ExperimentConfig(name="siglip-top5", model=RetrievalModel.SIGLIP, top_k=5), ExperimentConfig(name="ocr-bm25-top5", model=RetrievalModel.OCR_BM25, top_k=5), ] # {{/docs-fragment grid}} run = flyte.with_runcontext().run( compare_experiments, configs=configs, subset="vidore_v3_finance_en", max_pages=2000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multimodal-retrieval-evaluation/retrieval_eval.py* > [!NOTE] > The `DynamicBatcher` implementation lives in the `extras/` package next to the example. Run the script from the example directory so the import resolves. ## Run one experiment `run_experiment` selects the right index/search path based on the runtime value of `config.model`. Flyte v2's dynamic execution means there's no static DAG to wire up. `flyte.group` wraps each experiment in a named span in the UI. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "colpali-engine>=0.3.1", # "transformers>=4.41", # "sentencepiece>=0.2", # "torch>=2.0", # "pillow>=10", # "datasets>=2.18", # "rank-bm25>=0.2", # "numpy>=1.26", # "python-doctr[torch]>=0.8", # "pydantic>=2.0", # "flyte>=2.0.0", # ] # /// """ Multimodal Retrieval Evaluation Pipeline This tutorial is an experiment framework for benchmarking visual document retrieval approaches on the ViDoRe benchmark. Each experiment is defined by an ExperimentConfig; the pipeline fans them out as concurrent Flyte tasks and returns a ranked comparison table with an interactive HTML report. The corpus is a set of PDF page images; queries are plain-text questions. Each retrieval method must find the page that answers each question โ€” no text is provided to the model, only the raw image. ColPali-v1.2 โ€” patch-level multi-vector embeddings from a VLM (PaliGemma). No OCR. The model produces one vector per image patch (~1024 per page). MaxSim late-interaction scoring finds the best matching patch for each query token. SigLIP-SO400M โ€” single global embedding per page from Google's 2023 CLIP successor. One matrix multiply per query; fast and effective but a single vector cannot localise fine-grained regions. OCR + BM25 โ€” text-only baseline. doctr (GPU OCR) extracts text in batches, BM25 matches keywords. Strong on text-dense pages; fails on charts, tables, and figures where content is visual. """ import asyncio import enum import json import math import os import tempfile from functools import lru_cache from io import BytesIO from itertools import islice import numpy as np from PIL import Image as PILImage from pydantic import BaseModel from rank_bm25 import BM25Okapi from extras import DynamicBatcher import flyte import flyte.report from flyte.io import File # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Environments # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One Docker image for all tasks. The PEP 723 header defines Python deps. # ca-certificates is required for HTTPS calls to HuggingFace and blob stores. # {{docs-fragment image}} image = ( flyte.Image.from_uv_script(__file__, name="vidore-eval-v2") .with_apt_packages("ca-certificates", "libxcb1", "libgl1", "libglib2.0-0") # unionai-reuse installs the unionai-actor-bridge binary required by ReusePolicy. # Without it every reusable container exits with StartError (exit code 128). .with_pip_packages("unionai-reuse>=0.1.11") ) # {{/docs-fragment image}} # GPU environment for ColPali image encoding and search. # # ReusePolicy keeps up to 3 warm GPU containers alive between task calls. # Without it, every task invocation cold-starts a new container and downloads # ColPali-v1.2 (~7 GB) from scratch. With it, the container โ€” and the model # weights already loaded into VRAM โ€” is reused for the next task dispatch. # # replicas=1 single warm container โ€” all concurrent shard calls land # here so they share one DynamicBatcher process # concurrency=8 up to 8 query-shard tasks run simultaneously on the # container, all feeding the same DynamicBatcher queue # idle_ttl=120 keep alive 2 min after the last task finishes # scaledown_ttl=60 scale to zero after 1 min of complete inactivity # {{docs-fragment envs}} colpali_indexer = flyte.TaskEnvironment( name="vidore-colpali-indexer", image=image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="A10G:1"), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for SigLIP image encoding and search. # # Separate from the ColPali environment so each model's warm containers # are managed independently โ€” ColPali and SigLIP experiments can scale # without contending for the same pool of reusable containers. siglip_indexer = flyte.TaskEnvironment( name="vidore-siglip-indexer", image=image, resources=flyte.Resources(cpu=4, memory="8Gi", gpu=1), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for doctr OCR. doctr runs DBNet (detection) + CRNN (recognition) # in batches on GPU โ€” much faster than CPU Tesseract. # No ReusePolicy needed: the result is cached, so this task runs at most once. ocr_engine = flyte.TaskEnvironment( name="vidore-ocr-engine", image=image, resources=flyte.Resources(cpu=4, memory="20Gi", gpu=1), ) # Driver: orchestration, BM25 search, evaluation, and reporting. # depends_on ensures the shared Docker image is built before all environments # try to schedule tasks. driver = flyte.TaskEnvironment( name="vidore-driver", image=image, resources=flyte.Resources(cpu=2, memory="12Gi"), depends_on=[colpali_indexer, siglip_indexer, ocr_engine], ) # {{/docs-fragment envs}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Configuration types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment config_types}} class RetrievalModel(str, enum.Enum): """Retrieval backend to evaluate.""" COLPALI = "colpali-v1.2" # multi-vector patch embeddings, MaxSim SIGLIP = "siglip-so400m" # single-vector global embedding, cosine sim OCR_BM25 = "ocr+bm25" # text extracted by Tesseract, ranked by BM25 class ExperimentConfig(BaseModel): """ All knobs for one retrieval experiment. Passed as a typed Flyte input. Because ExperimentConfig is a Pydantic model, Flyte serialises it alongside every task output โ€” so you can always reconstruct which config produced which metric without maintaining a separate log. """ name: str # human-readable label shown in the comparison table model: RetrievalModel top_k: int = 5 # number of pages to retrieve per query # {{/docs-fragment config_types}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Data types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment data_types}} class PageQuery(BaseModel): """One retrieval query with its ground-truth page.""" query_id: str text: str # e.g. "What was revenue growth in Q3?" relevant_page_id: str # one correct page per query class PageDataset(BaseModel): """ A corpus of document page images paired with text queries. page_ids: unique page identifiers (derived from ViDoRe image filenames). page_files: the same pages stored in Flyte's blob store as JPEG File handles. Tasks read images directly from here; no live HTTP. queries: text questions with ground-truth page IDs for evaluation. """ page_ids: list[str] page_files: list[File] queries: list[PageQuery] class Config: arbitrary_types_allowed = True class RetrievalResult(BaseModel): query_id: str ranked_page_ids: list[str] # ordered best โ†’ worst class Metrics(BaseModel): recall_at_k: float ndcg_at_k: float mrr: float k: int class ExperimentResult(BaseModel): config: ExperimentConfig metrics: Metrics # {{/docs-fragment data_types}} class ComparisonReport(BaseModel): results: list[ExperimentResult] def best_by(self, metric: str = "recall_at_k") -> ExperimentResult: return max(self.results, key=lambda r: getattr(r.metrics, metric)) def summary(self) -> str: header = f"{'Experiment':<30} {'Model':<18} {'Recall@K':>10} {'NDCG@K':>8} {'MRR':>7}" sep = "โ”€" * len(header) rows = [header, sep] for r in sorted(self.results, key=lambda x: -x.metrics.recall_at_k): rows.append( f"{r.config.name:<30} " f"{r.config.model.value:<18} " f"{r.metrics.recall_at_k:>10.3f} " f"{r.metrics.ndcg_at_k:>8.3f} " f"{r.metrics.mrr:>7.3f}" ) return "\n".join(rows) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Cached model loaders # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # These functions are at module level so they are shared across all tasks that # run on the same warm container (via ReusePolicy). lru_cache(maxsize=1) means # the model is loaded from disk/HuggingFace exactly once per container process # and kept in GPU memory for every subsequent task dispatch to that container. @lru_cache(maxsize=1) def _colpali_model(): """Load ColPali-v1.2 into GPU memory and cache the result. device_map= is the correct loading pattern for ColPali's PaliGemma backbone; it handles weight placement via accelerate. torch.compile is skipped โ€” ColPali is GPU-compute-bound and the DynamicBatcher's cross- invocation batching is the primary GPU utilisation mechanism. """ import torch from colpali_engine.models import ColPali, ColPaliProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = ColPali.from_pretrained( "vidore/colpali-v1.2", torch_dtype=torch.bfloat16, device_map=device, ) processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.2") return model, processor, device @lru_cache(maxsize=1) def _siglip_model(): """Load SigLIP SO400M into GPU memory, compile it, and cache the result. torch.compile (mode="reduce-overhead") fuses the vision and text encoder transformer layers into optimised CUDA kernels. As with ColPali, the compilation overhead is paid once per warm container lifetime. """ import torch from transformers import AutoModel, AutoProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModel.from_pretrained("google/siglip-so400m-patch14-224").to(device) if device == "cuda": model = torch.compile(model, mode="reduce-overhead") processor = AutoProcessor.from_pretrained("google/siglip-so400m-patch14-224") return model, processor, device @lru_cache(maxsize=1) def _ocr_model(): """Load the doctr OCR predictor onto GPU and cache it. doctr's ocr_predictor bundles a detection model (DBNet) and a recognition model (CRNN/SAR) into a single callable. pretrained=True downloads both model weights from doctr's model zoo on first use. """ import torch from doctr.models import ocr_predictor predictor = ocr_predictor(pretrained=True) if torch.cuda.is_available(): predictor = predictor.cuda() return predictor # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Search batcher singletons # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One DynamicBatcher per model, shared across all concurrent search task # invocations on the same warm container (concurrency=3). Queries from every # concurrent caller are aggregated into a single GPU batch, maximizing # throughput compared to each invocation running its own forward pass. # # Initialised lazily on the first search call via double-checked locking and # lives for the container's lifetime. The process_fn runs GPU work via # asyncio.to_thread so the aggregation loop can continue collecting queries # from other callers while the GPU processes the current batch. # # File is not hashable so alru_cache cannot be used here; module-level state # with asyncio.Lock is the correct pattern. # # Assumption: index_colpali/index_siglip use cache="auto", so the same corpus # always produces the same index File across all callers on this container. If # the index file ever changed between calls, the batcher would silently continue # using the corpus embeddings loaded from the first call. _colpali_batcher: DynamicBatcher | None = None _colpali_batcher_lock = asyncio.Lock() _siglip_batcher: DynamicBatcher | None = None _siglip_batcher_lock = asyncio.Lock() async def _get_colpali_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level ColPali search batcher, creating it on first call.""" global _colpali_batcher if _colpali_batcher is not None: return _colpali_batcher async with _colpali_batcher_lock: if _colpali_batcher is not None: return _colpali_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, n_patches, dim) index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _colpali_model() corpus_emb = corpus_emb.to(device, dtype=torch.float32) async def colpali_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: query_inputs = processor.process_queries([q.text for q in batch]) query_inputs = {k: v.to(device) for k, v in query_inputs.items()} with torch.no_grad(): query_embs = model(**query_inputs).float() # (B, T, D) query_chunk = 8 n_pages = corpus_emb.shape[0] all_scores = torch.empty(len(batch), n_pages, device=device) for start in range(0, len(batch), query_chunk): chunk = query_embs[start : start + query_chunk] all_scores[start : start + query_chunk] = ( torch.einsum("ctd,pjd->ctpj", chunk, corpus_emb) .max(dim=3).values .sum(dim=1) ) sorted_indices = all_scores.argsort(dim=1, descending=True).cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] # Run GPU work in a thread so the event loop โ€” and the batcher's # aggregation loop โ€” remain unblocked while the GPU is busy. return await asyncio.to_thread(_gpu_work) batcher: DynamicBatcher[PageQuery, list[str]] = DynamicBatcher( process_fn=colpali_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _colpali_batcher = batcher return _colpali_batcher async def _get_siglip_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level SigLIP search batcher, creating it on first call.""" global _siglip_batcher if _siglip_batcher is not None: return _siglip_batcher async with _siglip_batcher_lock: if _siglip_batcher is not None: return _siglip_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, dim), L2-normalised index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _siglip_model() corpus_emb = corpus_emb.to(device) async def siglip_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: text_inputs = processor( text=[q.text for q in batch], return_tensors="pt", padding=True, truncation=True, ).to(device) with torch.no_grad(): text_out = model.text_model(**text_inputs) query_embs = text_out.pooler_output # (B, dim) query_embs = query_embs / query_embs.norm(dim=-1, keepdim=True) scores_matrix = corpus_emb @ query_embs.T # (n_pages, B) sorted_indices = scores_matrix.argsort(dim=0, descending=True).T.cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] return await asyncio.to_thread(_gpu_work) batcher = DynamicBatcher( process_fn=siglip_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _siglip_batcher = batcher return _siglip_batcher # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Helpers # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _batches(items: list, batch_size: int): """Yield successive fixed-size batches from a list.""" for start in range(0, len(items), batch_size): yield items[start : start + batch_size] def _load_image_sync(f: File) -> PILImage.Image: """Blocking download + decode. Intended to be called from a thread pool.""" with f.open_sync("rb") as fh: data = fh.read() return PILImage.open(BytesIO(data)).convert("RGB") async def _load_image(f: File) -> PILImage.Image: """Download and decode a page image in a thread-pool worker. asyncio.to_thread runs _load_image_sync in a real OS thread so that blocking network I/O can overlap with GPU-bound forward passes when images are pre-submitted via loop.run_in_executor before the GPU kernel. """ return await asyncio.to_thread(_load_image_sync, f) async def _load_npz(index_file: File) -> np.lib.npyio.NpzFile: """Download an index File to a local temp path and open with np.load.""" with tempfile.NamedTemporaryFile(suffix=".npz", delete=False) as tmp: async with index_file.open("rb") as fh: tmp.write(bytes(await fh.read())) return np.load(tmp.name) def _dcg(relevances: list[int]) -> float: return sum(rel / math.log2(rank + 2) for rank, rel in enumerate(relevances)) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” data loading # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(cache="auto", retries=3) async def load_vidore_pages(subset: str = "docvqa", max_pages: int = 200) -> PageDataset: """ Load a ViDoRe benchmark subset and store page images in Flyte's blob store. Supports two dataset formats: Legacy (subsampled) โ€” single 'test' split with one row per (query, page) pair; fields: image, query, image_filename. streaming=True reads only the rows requested via islice โ€” no full-shard download. Datasets: vidore/docvqa_test_subsampled, vidore/infovqa_test_subsampled V3 โ€” separate corpus / queries / qrels splits following the BEIR retrieval benchmark format. corpus contains page images; queries contains question text; qrels maps query IDs to relevant corpus page IDs (many-to-many). Datasets: vidore/vidore_v3_finance_en (~2 942 pages, 1 854 queries) The first call uploads page images to Flyte's blob store and caches the PageDataset; every subsequent call with the same arguments returns the cached result instantly. retries=3 guards against transient HuggingFace network failures. Available subsets: "docvqa", "infovqa", "vidore_v3_finance_en" """ from datasets import load_dataset subset_map = { "docvqa": "vidore/docvqa_test_subsampled", "infovqa": "vidore/infovqa_test_subsampled", "vidore_v3_finance_en": "vidore/vidore_v3_finance_en", } dataset_name = subset_map.get(subset, f"vidore/{subset}_test_subsampled") # V3 datasets ship with separate corpus / queries / qrels splits. _V3_SUBSETS = {"vidore_v3_finance_en"} if subset in _V3_SUBSETS: # โ”€โ”€ V3 format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # corpus / queries / qrels are HuggingFace configs (name=), not splits. # corpus uses streaming=True so images are decoded one at a time โ€” # loading all 2 942 rows eagerly would hold gigabytes of PIL images in # the driver's RAM simultaneously. qrels and queries are text-only and # small enough to load fully into memory. corpus_ds = load_dataset(dataset_name, name="corpus", split="test", streaming=True) qrels_ds = load_dataset(dataset_name, name="qrels", split="test") queries_ds = load_dataset(dataset_name, name="queries", split="test") # Normalise field names โ€” V3 follows BEIR convention (hyphenated ids). def _col(ds, *candidates): cols = set(ds.column_names) for c in candidates: if c in cols: return c raise KeyError(f"None of {candidates} found in columns {cols}") corpus_id_col = _col(corpus_ds, "corpus-id", "corpus_id", "id", "_id") query_id_col = _col(queries_ds, "query-id", "query_id", "id", "_id") query_text_col = _col(queries_ds, "query", "text") qrel_qid_col = _col(qrels_ds, "query-id", "query_id") qrel_cid_col = _col(qrels_ds, "corpus-id", "corpus_id") # Slice corpus to max_pages, upload each image to Flyte blob store. page_ids: list[str] = [] page_files: list[File] = [] corpus_id_to_page_id: dict[str, str] = {} for i, row in enumerate(islice(corpus_ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue cid = str(row[corpus_id_col]) page_id = f"{subset}_{i:04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) corpus_id_to_page_id[cid] = page_id page_ids.append(page_id) page_files.append(page_file) # Build query_id โ†’ relevant page_id from qrels (first match wins). # Only keep relevance judgements whose corpus page is in our slice. qrel_map: dict[str, str] = {} for row in qrels_ds: qid = str(row[qrel_qid_col]) cid = str(row[qrel_cid_col]) if cid in corpus_id_to_page_id and qid not in qrel_map: qrel_map[qid] = corpus_id_to_page_id[cid] # Collect queries that have at least one relevant page in our slice. queries: list[PageQuery] = [] for row in queries_ds: qid = str(row[query_id_col]) if qid not in qrel_map: continue queries.append( PageQuery( query_id=qid, text=str(row[query_text_col]), relevant_page_id=qrel_map[qid], ) ) else: # โ”€โ”€ Legacy format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Single 'test' split with one row per (query, page) pair. ds = load_dataset(dataset_name, split="test", streaming=True) page_ids = [] page_files = [] queries = [] seen_pages: dict[str, str] = {} # image_filename โ†’ page_id for i, row in enumerate(islice(ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue filename: str = row.get("image_filename") or f"page_{i}" query_text: str = row.get("query", "") if not query_text: continue # Each unique page is uploaded exactly once; multiple queries may # share the same page (same image_filename). if filename not in seen_pages: page_id = f"{subset}_{len(page_ids):04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) seen_pages[filename] = page_id page_ids.append(page_id) page_files.append(page_file) else: page_id = seen_pages[filename] queries.append( PageQuery( query_id=f"q{i:04d}", text=query_text, relevant_page_id=page_id, ) ) print(f"Loaded {len(page_ids)} unique pages, {len(queries)} queries", flush=True) return PageDataset(page_ids=page_ids, page_files=page_files, queries=queries) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” indexing # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @colpali_indexer.task(cache="auto", retries=2) async def index_colpali(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with ColPali-v1.2 and save the multi-vector index. ColPali skips OCR entirely. It feeds the raw page image into PaliGemma (a vision-language model) and produces one embedding vector per image patch โ€” roughly 1,024 patches per page, each of dimension 128. _colpali_model() is an lru_cache'd loader. On a cold container, it downloads and loads the model once. On a warm container (kept alive by ReusePolicy), it returns the already-loaded model instantly from cache โ€” no repeated ~7 GB download. The index is stored as a .npz file in Flyte's blob store: embeddings โ€” float32, shape (n_pages, n_patches, dim) page_ids โ€” matching page ID strings cache="auto" + retries=2: the result is stored permanently on success; transient failures (e.g. HuggingFace rate limits) are retried twice. """ import torch model, processor, device = _colpali_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 4)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor.process_images(images) inputs = {k: v.to(device) for k, v in inputs.items()} with torch.no_grad(): emb = model(**inputs) # (batch, n_patches, dim) all_embeddings.append(emb.cpu().float().numpy()) print(f"ColPali: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, n_patches, dim) out_path = os.path.join(tempfile.gettempdir(), "colpali_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @siglip_indexer.task(cache="auto", retries=2) async def index_siglip(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with SigLIP SO400M and save the single-vector index. SigLIP (2023) is Google's successor to CLIP, trained with sigmoid loss instead of softmax โ€” avoiding the normalisation bottleneck that limits CLIP's scalability. Produces one global embedding per page. _siglip_model() caches the model across warm container reuses. The index is stored as a .npz file: embeddings โ€” float32, shape (n_pages, dim), L2-normalised page_ids โ€” matching page ID strings """ import torch model, processor, device = _siglip_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 8)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor(images=images, return_tensors="pt", padding=True).to(device) with torch.no_grad(): outputs = model.vision_model(**inputs) emb = outputs.pooler_output # (batch, dim) emb = emb / emb.norm(dim=-1, keepdim=True) # L2 normalise all_embeddings.append(emb.cpu().float().numpy()) print(f"SigLIP: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, dim) out_path = os.path.join(tempfile.gettempdir(), "siglip_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @ocr_engine.task(cache="auto") async def extract_page_texts(page_files: list[File]) -> list[str]: """ OCR every page with doctr on GPU to produce a text-only baseline. doctr bundles DBNet (detection) + CRNN/SAR (recognition) into a single callable predictor. Pages are downloaded in parallel then fed in batches of ocr_batch_size. asyncio.to_thread keeps the event loop unblocked during GPU inference. Result structure: result.pages[i].blocks[j].lines[k].words[l].value Cached: the same corpus is OCR'd at most once across all experiments that use the OCR+BM25 backend. """ import gc predictor = _ocr_model() # Process in batches: download each batch just-in-time so only # ocr_batch_size images are in memory at once instead of all 2 000. ocr_batch_size = 8 total = len(page_files) texts: list[str] = [] for start in range(0, total, ocr_batch_size): batch_files = page_files[start : start + ocr_batch_size] batch_images = list( await asyncio.gather(*[asyncio.to_thread(_load_image_sync, f) for f in batch_files]) ) batch_np = [np.array(img) for img in batch_images] del batch_images result = await asyncio.to_thread(predictor, batch_np) del batch_np for page_output in result.pages: texts.append( "\n".join( " ".join(word.value for word in line.words) for block in page_output.blocks for line in block.lines ) ) del result gc.collect() print(f"OCR: processed {min(start + ocr_batch_size, total)}/{total} pages", flush=True) return texts # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” search # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment search_colpali}} @colpali_indexer.task async def search_colpali( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using ColPali MaxSim late interaction via DynamicBatcher. MaxSim score for page p given query q: score(q, p) = ฮฃ_{t โˆˆ query tokens} max_{j โˆˆ page patches} (q_t ยท p_j) Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_colpali invocations on the same warm container (concurrency=8) into a single GPU batch. This keeps the GPU saturated rather than running one small batch per caller. The batcher's process_fn runs GPU work in asyncio.to_thread, so the aggregation loop stays live while the GPU encodes and scores. """ batcher = await _get_colpali_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] # {{/docs-fragment search_colpali}} @siglip_indexer.task async def search_siglip( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using SigLIP cosine similarity via DynamicBatcher. Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_siglip invocations on the same warm container (concurrency=3) into a single GPU batch. SigLIP's single-vector embeddings make full vectorisation safe โ€” the scores matrix (n_pages x n_queries) is small enough to materialise in one GPU call regardless of batch size. """ batcher = await _get_siglip_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] @driver.task async def search_bm25( page_texts: list[str], page_ids: list[str], queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using BM25 over OCR'd text. The standard keyword-based baseline. No GPU required; strong on text-dense pages, weak on visual content that Tesseract cannot read. """ tokenized = [text.lower().split() for text in page_texts] bm25 = BM25Okapi(tokenized) results: list[RetrievalResult] = [] for q in queries: scores = bm25.get_scores(q.text.lower().split()) ranked = sorted(range(len(page_ids)), key=lambda i: -scores[i])[:top_k] results.append( RetrievalResult( query_id=q.query_id, ranked_page_ids=[page_ids[i] for i in ranked], ) ) return results # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” evaluation # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task async def evaluate( results: list[RetrievalResult], ground_truth: list[PageQuery], k: int, ) -> Metrics: """ Compute Recall@K, NDCG@K, and MRR for a single retrieval model. Recall@K โ€” was the correct page in the top-K results? NDCG@K โ€” normalised discounted cumulative gain; rewards earlier hits. MRR โ€” mean reciprocal rank of the first correct result. All three are averaged over all queries. Higher is better. """ gt_map = {q.query_id: q.relevant_page_id for q in ground_truth} recall_vals, ndcg_vals, mrr_vals = [], [], [] for r in results: relevant = gt_map.get(r.query_id, "") top = r.ranked_page_ids[:k] recall_vals.append(1.0 if relevant in top else 0.0) rels = [1 if pid == relevant else 0 for pid in top] idcg = _dcg([1]) # ideal: correct page at rank 1 ndcg_vals.append(_dcg(rels) / idcg if idcg > 0 else 0.0) rr = 0.0 for rank, pid in enumerate(r.ranked_page_ids, start=1): if pid == relevant: rr = 1.0 / rank break mrr_vals.append(rr) return Metrics( recall_at_k=float(np.mean(recall_vals)), ndcg_at_k=float(np.mean(ndcg_vals)), mrr=float(np.mean(mrr_vals)), k=k, ) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” report # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(report=True) async def generate_report(report: ComparisonReport) -> None: """ Emit an interactive HTML report visible in the Flyte UI. report=True marks this task as a reporting task. Flyte renders the HTML returned via flyte.report.replace.aio() directly in the execution detail page โ€” no separate dashboard or export step required. The report contains: - Summary cards: experiment count, best model, best Recall@K. - Grouped bar chart: Recall@K, NDCG@K, MRR side-by-side per experiment. - Ranked results table with all three metrics. """ sorted_results = sorted(report.results, key=lambda r: -r.metrics.recall_at_k) best = sorted_results[0] labels = [r.config.name for r in sorted_results] recall_vals = [r.metrics.recall_at_k for r in sorted_results] ndcg_vals = [r.metrics.ndcg_at_k for r in sorted_results] mrr_vals = [r.metrics.mrr for r in sorted_results] table_rows = "".join( f""" {r.config.name} {r.config.model.value} {r.metrics.recall_at_k:.3f} {r.metrics.ndcg_at_k:.3f} {r.metrics.mrr:.3f} {r.metrics.k} """ for r in sorted_results ) html = f""" Visual Document Retrieval โ€” Results

Visual Document Retrieval โ€” Experiment Comparison

ViDoRe benchmark · {len(report.results)} experiment(s)

{len(report.results)}
Experiments
{best.config.name}
Best by Recall@K
{best.metrics.recall_at_k:.3f}
Best Recall@{best.metrics.k}
{best.metrics.ndcg_at_k:.3f}
Best NDCG@{best.metrics.k}
{best.metrics.mrr:.3f}
Best MRR

Metrics by Experiment

Ranked Results

{table_rows}
ExperimentModel Recall@KNDCG@KMRRK
""" await flyte.report.replace.aio(html) await flyte.report.flush.aio() # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Experiment orchestration # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment run_experiment}} @driver.task async def run_experiment(config: ExperimentConfig, dataset: PageDataset) -> ExperimentResult: """ End-to-end retrieval pipeline for a single ExperimentConfig. Flyte v2's dynamic execution means this driver task can call GPU tasks (index_colpali, search_colpali) based on the runtime value of config.model โ€” no static DAG wiring required. The if/elif is plain Python; Flyte schedules the selected sub-tasks on the appropriate environment. Caching: two experiments that share the same model and corpus (e.g. ColPali at top_k=5 and top_k=10) will hit the same cached index. GPU work is paid at most once per (model, corpus) pair across all experiments. Search queries are sharded into chunks of SEARCH_SHARD_SIZE and dispatched as concurrent task invocations. All shards land on the single warm container (replicas=1) and feed the same DynamicBatcher simultaneously, keeping the GPU saturated throughout search rather than processing one large sequential batch from a single caller. flyte.group wraps each experiment in a named span in the Flyte UI, making it easy to compare latencies and drill into individual runs. """ SEARCH_SHARD_SIZE = 256 with flyte.group(config.name): if config.model == RetrievalModel.COLPALI: index_file = await index_colpali(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_colpali(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] elif config.model == RetrievalModel.SIGLIP: index_file = await index_siglip(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_siglip(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] else: # RetrievalModel.OCR_BM25 page_texts = await extract_page_texts(dataset.page_files) results = await search_bm25(page_texts, dataset.page_ids, dataset.queries, config.top_k) metrics = await evaluate(results, dataset.queries, config.top_k) return ExperimentResult(config=config, metrics=metrics) # {{/docs-fragment run_experiment}} # {{docs-fragment compare_experiments}} @driver.task async def compare_experiments( configs: list[ExperimentConfig], subset: str = "docvqa", max_pages: int = 200, ) -> ComparisonReport: """ Fan out over all experiment configs and return a ranked comparison table. The dataset is loaded once and shared across all experiments. Each config runs as a concurrent Flyte task via asyncio.gather. Experiments that share a model reuse the cached index โ€” you only pay GPU time for new work. On completion, generate_report emits an interactive Chart.js HTML report visible directly in the Flyte execution detail page. Default dataset: vidore_v3_finance_en (~2 942 corpus pages, 1 854 queries) with max_pages=2 000 to exercise the GPU pipeline at scale. """ dataset = await load_vidore_pages(subset=subset, max_pages=max_pages) # All experiments launch concurrently. Shared cached outputs (same model, # same corpus) are served from cache rather than recomputed. experiment_coros = [run_experiment(config=cfg, dataset=dataset) for cfg in configs] results: list[ExperimentResult] = list(await asyncio.gather(*experiment_coros)) report = ComparisonReport(results=results) print(report.summary()) best = report.best_by("recall_at_k") print(f"\nBest by Recall@{best.metrics.k}: {best.config.name}") # Emit the interactive HTML report in the Flyte UI. await generate_report(report) return report # {{/docs-fragment compare_experiments}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Entry point # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if __name__ == "__main__": flyte.init_from_config() # Define the experiment grid. Each ExperimentConfig is one point in the # design space. Adding a new model or varying top_k is one line here โ€” # no task code changes required. # # ColPali appears twice with different top_k values. The cache ensures # index_colpali runs only once and both experiments share that result. # {{docs-fragment grid}} configs = [ ExperimentConfig(name="colpali-top5", model=RetrievalModel.COLPALI, top_k=5), ExperimentConfig(name="colpali-top10", model=RetrievalModel.COLPALI, top_k=10), ExperimentConfig(name="siglip-top5", model=RetrievalModel.SIGLIP, top_k=5), ExperimentConfig(name="ocr-bm25-top5", model=RetrievalModel.OCR_BM25, top_k=5), ] # {{/docs-fragment grid}} run = flyte.with_runcontext().run( compare_experiments, configs=configs, subset="vidore_v3_finance_en", max_pages=2000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multimodal-retrieval-evaluation/retrieval_eval.py* ## Compare experiments The driver loads the dataset once, fans out across all configs with `asyncio.gather`, and emits an interactive Chart.js report in the Flyte UI. Experiments sharing a model reuse the cached index, so you only pay GPU time for new work. ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "colpali-engine>=0.3.1", # "transformers>=4.41", # "sentencepiece>=0.2", # "torch>=2.0", # "pillow>=10", # "datasets>=2.18", # "rank-bm25>=0.2", # "numpy>=1.26", # "python-doctr[torch]>=0.8", # "pydantic>=2.0", # "flyte>=2.0.0", # ] # /// """ Multimodal Retrieval Evaluation Pipeline This tutorial is an experiment framework for benchmarking visual document retrieval approaches on the ViDoRe benchmark. Each experiment is defined by an ExperimentConfig; the pipeline fans them out as concurrent Flyte tasks and returns a ranked comparison table with an interactive HTML report. The corpus is a set of PDF page images; queries are plain-text questions. Each retrieval method must find the page that answers each question โ€” no text is provided to the model, only the raw image. ColPali-v1.2 โ€” patch-level multi-vector embeddings from a VLM (PaliGemma). No OCR. The model produces one vector per image patch (~1024 per page). MaxSim late-interaction scoring finds the best matching patch for each query token. SigLIP-SO400M โ€” single global embedding per page from Google's 2023 CLIP successor. One matrix multiply per query; fast and effective but a single vector cannot localise fine-grained regions. OCR + BM25 โ€” text-only baseline. doctr (GPU OCR) extracts text in batches, BM25 matches keywords. Strong on text-dense pages; fails on charts, tables, and figures where content is visual. """ import asyncio import enum import json import math import os import tempfile from functools import lru_cache from io import BytesIO from itertools import islice import numpy as np from PIL import Image as PILImage from pydantic import BaseModel from rank_bm25 import BM25Okapi from extras import DynamicBatcher import flyte import flyte.report from flyte.io import File # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Environments # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One Docker image for all tasks. The PEP 723 header defines Python deps. # ca-certificates is required for HTTPS calls to HuggingFace and blob stores. # {{docs-fragment image}} image = ( flyte.Image.from_uv_script(__file__, name="vidore-eval-v2") .with_apt_packages("ca-certificates", "libxcb1", "libgl1", "libglib2.0-0") # unionai-reuse installs the unionai-actor-bridge binary required by ReusePolicy. # Without it every reusable container exits with StartError (exit code 128). .with_pip_packages("unionai-reuse>=0.1.11") ) # {{/docs-fragment image}} # GPU environment for ColPali image encoding and search. # # ReusePolicy keeps up to 3 warm GPU containers alive between task calls. # Without it, every task invocation cold-starts a new container and downloads # ColPali-v1.2 (~7 GB) from scratch. With it, the container โ€” and the model # weights already loaded into VRAM โ€” is reused for the next task dispatch. # # replicas=1 single warm container โ€” all concurrent shard calls land # here so they share one DynamicBatcher process # concurrency=8 up to 8 query-shard tasks run simultaneously on the # container, all feeding the same DynamicBatcher queue # idle_ttl=120 keep alive 2 min after the last task finishes # scaledown_ttl=60 scale to zero after 1 min of complete inactivity # {{docs-fragment envs}} colpali_indexer = flyte.TaskEnvironment( name="vidore-colpali-indexer", image=image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="A10G:1"), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for SigLIP image encoding and search. # # Separate from the ColPali environment so each model's warm containers # are managed independently โ€” ColPali and SigLIP experiments can scale # without contending for the same pool of reusable containers. siglip_indexer = flyte.TaskEnvironment( name="vidore-siglip-indexer", image=image, resources=flyte.Resources(cpu=4, memory="8Gi", gpu=1), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for doctr OCR. doctr runs DBNet (detection) + CRNN (recognition) # in batches on GPU โ€” much faster than CPU Tesseract. # No ReusePolicy needed: the result is cached, so this task runs at most once. ocr_engine = flyte.TaskEnvironment( name="vidore-ocr-engine", image=image, resources=flyte.Resources(cpu=4, memory="20Gi", gpu=1), ) # Driver: orchestration, BM25 search, evaluation, and reporting. # depends_on ensures the shared Docker image is built before all environments # try to schedule tasks. driver = flyte.TaskEnvironment( name="vidore-driver", image=image, resources=flyte.Resources(cpu=2, memory="12Gi"), depends_on=[colpali_indexer, siglip_indexer, ocr_engine], ) # {{/docs-fragment envs}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Configuration types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment config_types}} class RetrievalModel(str, enum.Enum): """Retrieval backend to evaluate.""" COLPALI = "colpali-v1.2" # multi-vector patch embeddings, MaxSim SIGLIP = "siglip-so400m" # single-vector global embedding, cosine sim OCR_BM25 = "ocr+bm25" # text extracted by Tesseract, ranked by BM25 class ExperimentConfig(BaseModel): """ All knobs for one retrieval experiment. Passed as a typed Flyte input. Because ExperimentConfig is a Pydantic model, Flyte serialises it alongside every task output โ€” so you can always reconstruct which config produced which metric without maintaining a separate log. """ name: str # human-readable label shown in the comparison table model: RetrievalModel top_k: int = 5 # number of pages to retrieve per query # {{/docs-fragment config_types}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Data types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment data_types}} class PageQuery(BaseModel): """One retrieval query with its ground-truth page.""" query_id: str text: str # e.g. "What was revenue growth in Q3?" relevant_page_id: str # one correct page per query class PageDataset(BaseModel): """ A corpus of document page images paired with text queries. page_ids: unique page identifiers (derived from ViDoRe image filenames). page_files: the same pages stored in Flyte's blob store as JPEG File handles. Tasks read images directly from here; no live HTTP. queries: text questions with ground-truth page IDs for evaluation. """ page_ids: list[str] page_files: list[File] queries: list[PageQuery] class Config: arbitrary_types_allowed = True class RetrievalResult(BaseModel): query_id: str ranked_page_ids: list[str] # ordered best โ†’ worst class Metrics(BaseModel): recall_at_k: float ndcg_at_k: float mrr: float k: int class ExperimentResult(BaseModel): config: ExperimentConfig metrics: Metrics # {{/docs-fragment data_types}} class ComparisonReport(BaseModel): results: list[ExperimentResult] def best_by(self, metric: str = "recall_at_k") -> ExperimentResult: return max(self.results, key=lambda r: getattr(r.metrics, metric)) def summary(self) -> str: header = f"{'Experiment':<30} {'Model':<18} {'Recall@K':>10} {'NDCG@K':>8} {'MRR':>7}" sep = "โ”€" * len(header) rows = [header, sep] for r in sorted(self.results, key=lambda x: -x.metrics.recall_at_k): rows.append( f"{r.config.name:<30} " f"{r.config.model.value:<18} " f"{r.metrics.recall_at_k:>10.3f} " f"{r.metrics.ndcg_at_k:>8.3f} " f"{r.metrics.mrr:>7.3f}" ) return "\n".join(rows) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Cached model loaders # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # These functions are at module level so they are shared across all tasks that # run on the same warm container (via ReusePolicy). lru_cache(maxsize=1) means # the model is loaded from disk/HuggingFace exactly once per container process # and kept in GPU memory for every subsequent task dispatch to that container. @lru_cache(maxsize=1) def _colpali_model(): """Load ColPali-v1.2 into GPU memory and cache the result. device_map= is the correct loading pattern for ColPali's PaliGemma backbone; it handles weight placement via accelerate. torch.compile is skipped โ€” ColPali is GPU-compute-bound and the DynamicBatcher's cross- invocation batching is the primary GPU utilisation mechanism. """ import torch from colpali_engine.models import ColPali, ColPaliProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = ColPali.from_pretrained( "vidore/colpali-v1.2", torch_dtype=torch.bfloat16, device_map=device, ) processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.2") return model, processor, device @lru_cache(maxsize=1) def _siglip_model(): """Load SigLIP SO400M into GPU memory, compile it, and cache the result. torch.compile (mode="reduce-overhead") fuses the vision and text encoder transformer layers into optimised CUDA kernels. As with ColPali, the compilation overhead is paid once per warm container lifetime. """ import torch from transformers import AutoModel, AutoProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModel.from_pretrained("google/siglip-so400m-patch14-224").to(device) if device == "cuda": model = torch.compile(model, mode="reduce-overhead") processor = AutoProcessor.from_pretrained("google/siglip-so400m-patch14-224") return model, processor, device @lru_cache(maxsize=1) def _ocr_model(): """Load the doctr OCR predictor onto GPU and cache it. doctr's ocr_predictor bundles a detection model (DBNet) and a recognition model (CRNN/SAR) into a single callable. pretrained=True downloads both model weights from doctr's model zoo on first use. """ import torch from doctr.models import ocr_predictor predictor = ocr_predictor(pretrained=True) if torch.cuda.is_available(): predictor = predictor.cuda() return predictor # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Search batcher singletons # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One DynamicBatcher per model, shared across all concurrent search task # invocations on the same warm container (concurrency=3). Queries from every # concurrent caller are aggregated into a single GPU batch, maximizing # throughput compared to each invocation running its own forward pass. # # Initialised lazily on the first search call via double-checked locking and # lives for the container's lifetime. The process_fn runs GPU work via # asyncio.to_thread so the aggregation loop can continue collecting queries # from other callers while the GPU processes the current batch. # # File is not hashable so alru_cache cannot be used here; module-level state # with asyncio.Lock is the correct pattern. # # Assumption: index_colpali/index_siglip use cache="auto", so the same corpus # always produces the same index File across all callers on this container. If # the index file ever changed between calls, the batcher would silently continue # using the corpus embeddings loaded from the first call. _colpali_batcher: DynamicBatcher | None = None _colpali_batcher_lock = asyncio.Lock() _siglip_batcher: DynamicBatcher | None = None _siglip_batcher_lock = asyncio.Lock() async def _get_colpali_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level ColPali search batcher, creating it on first call.""" global _colpali_batcher if _colpali_batcher is not None: return _colpali_batcher async with _colpali_batcher_lock: if _colpali_batcher is not None: return _colpali_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, n_patches, dim) index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _colpali_model() corpus_emb = corpus_emb.to(device, dtype=torch.float32) async def colpali_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: query_inputs = processor.process_queries([q.text for q in batch]) query_inputs = {k: v.to(device) for k, v in query_inputs.items()} with torch.no_grad(): query_embs = model(**query_inputs).float() # (B, T, D) query_chunk = 8 n_pages = corpus_emb.shape[0] all_scores = torch.empty(len(batch), n_pages, device=device) for start in range(0, len(batch), query_chunk): chunk = query_embs[start : start + query_chunk] all_scores[start : start + query_chunk] = ( torch.einsum("ctd,pjd->ctpj", chunk, corpus_emb) .max(dim=3).values .sum(dim=1) ) sorted_indices = all_scores.argsort(dim=1, descending=True).cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] # Run GPU work in a thread so the event loop โ€” and the batcher's # aggregation loop โ€” remain unblocked while the GPU is busy. return await asyncio.to_thread(_gpu_work) batcher: DynamicBatcher[PageQuery, list[str]] = DynamicBatcher( process_fn=colpali_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _colpali_batcher = batcher return _colpali_batcher async def _get_siglip_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level SigLIP search batcher, creating it on first call.""" global _siglip_batcher if _siglip_batcher is not None: return _siglip_batcher async with _siglip_batcher_lock: if _siglip_batcher is not None: return _siglip_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, dim), L2-normalised index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _siglip_model() corpus_emb = corpus_emb.to(device) async def siglip_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: text_inputs = processor( text=[q.text for q in batch], return_tensors="pt", padding=True, truncation=True, ).to(device) with torch.no_grad(): text_out = model.text_model(**text_inputs) query_embs = text_out.pooler_output # (B, dim) query_embs = query_embs / query_embs.norm(dim=-1, keepdim=True) scores_matrix = corpus_emb @ query_embs.T # (n_pages, B) sorted_indices = scores_matrix.argsort(dim=0, descending=True).T.cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] return await asyncio.to_thread(_gpu_work) batcher = DynamicBatcher( process_fn=siglip_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _siglip_batcher = batcher return _siglip_batcher # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Helpers # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _batches(items: list, batch_size: int): """Yield successive fixed-size batches from a list.""" for start in range(0, len(items), batch_size): yield items[start : start + batch_size] def _load_image_sync(f: File) -> PILImage.Image: """Blocking download + decode. Intended to be called from a thread pool.""" with f.open_sync("rb") as fh: data = fh.read() return PILImage.open(BytesIO(data)).convert("RGB") async def _load_image(f: File) -> PILImage.Image: """Download and decode a page image in a thread-pool worker. asyncio.to_thread runs _load_image_sync in a real OS thread so that blocking network I/O can overlap with GPU-bound forward passes when images are pre-submitted via loop.run_in_executor before the GPU kernel. """ return await asyncio.to_thread(_load_image_sync, f) async def _load_npz(index_file: File) -> np.lib.npyio.NpzFile: """Download an index File to a local temp path and open with np.load.""" with tempfile.NamedTemporaryFile(suffix=".npz", delete=False) as tmp: async with index_file.open("rb") as fh: tmp.write(bytes(await fh.read())) return np.load(tmp.name) def _dcg(relevances: list[int]) -> float: return sum(rel / math.log2(rank + 2) for rank, rel in enumerate(relevances)) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” data loading # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(cache="auto", retries=3) async def load_vidore_pages(subset: str = "docvqa", max_pages: int = 200) -> PageDataset: """ Load a ViDoRe benchmark subset and store page images in Flyte's blob store. Supports two dataset formats: Legacy (subsampled) โ€” single 'test' split with one row per (query, page) pair; fields: image, query, image_filename. streaming=True reads only the rows requested via islice โ€” no full-shard download. Datasets: vidore/docvqa_test_subsampled, vidore/infovqa_test_subsampled V3 โ€” separate corpus / queries / qrels splits following the BEIR retrieval benchmark format. corpus contains page images; queries contains question text; qrels maps query IDs to relevant corpus page IDs (many-to-many). Datasets: vidore/vidore_v3_finance_en (~2 942 pages, 1 854 queries) The first call uploads page images to Flyte's blob store and caches the PageDataset; every subsequent call with the same arguments returns the cached result instantly. retries=3 guards against transient HuggingFace network failures. Available subsets: "docvqa", "infovqa", "vidore_v3_finance_en" """ from datasets import load_dataset subset_map = { "docvqa": "vidore/docvqa_test_subsampled", "infovqa": "vidore/infovqa_test_subsampled", "vidore_v3_finance_en": "vidore/vidore_v3_finance_en", } dataset_name = subset_map.get(subset, f"vidore/{subset}_test_subsampled") # V3 datasets ship with separate corpus / queries / qrels splits. _V3_SUBSETS = {"vidore_v3_finance_en"} if subset in _V3_SUBSETS: # โ”€โ”€ V3 format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # corpus / queries / qrels are HuggingFace configs (name=), not splits. # corpus uses streaming=True so images are decoded one at a time โ€” # loading all 2 942 rows eagerly would hold gigabytes of PIL images in # the driver's RAM simultaneously. qrels and queries are text-only and # small enough to load fully into memory. corpus_ds = load_dataset(dataset_name, name="corpus", split="test", streaming=True) qrels_ds = load_dataset(dataset_name, name="qrels", split="test") queries_ds = load_dataset(dataset_name, name="queries", split="test") # Normalise field names โ€” V3 follows BEIR convention (hyphenated ids). def _col(ds, *candidates): cols = set(ds.column_names) for c in candidates: if c in cols: return c raise KeyError(f"None of {candidates} found in columns {cols}") corpus_id_col = _col(corpus_ds, "corpus-id", "corpus_id", "id", "_id") query_id_col = _col(queries_ds, "query-id", "query_id", "id", "_id") query_text_col = _col(queries_ds, "query", "text") qrel_qid_col = _col(qrels_ds, "query-id", "query_id") qrel_cid_col = _col(qrels_ds, "corpus-id", "corpus_id") # Slice corpus to max_pages, upload each image to Flyte blob store. page_ids: list[str] = [] page_files: list[File] = [] corpus_id_to_page_id: dict[str, str] = {} for i, row in enumerate(islice(corpus_ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue cid = str(row[corpus_id_col]) page_id = f"{subset}_{i:04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) corpus_id_to_page_id[cid] = page_id page_ids.append(page_id) page_files.append(page_file) # Build query_id โ†’ relevant page_id from qrels (first match wins). # Only keep relevance judgements whose corpus page is in our slice. qrel_map: dict[str, str] = {} for row in qrels_ds: qid = str(row[qrel_qid_col]) cid = str(row[qrel_cid_col]) if cid in corpus_id_to_page_id and qid not in qrel_map: qrel_map[qid] = corpus_id_to_page_id[cid] # Collect queries that have at least one relevant page in our slice. queries: list[PageQuery] = [] for row in queries_ds: qid = str(row[query_id_col]) if qid not in qrel_map: continue queries.append( PageQuery( query_id=qid, text=str(row[query_text_col]), relevant_page_id=qrel_map[qid], ) ) else: # โ”€โ”€ Legacy format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Single 'test' split with one row per (query, page) pair. ds = load_dataset(dataset_name, split="test", streaming=True) page_ids = [] page_files = [] queries = [] seen_pages: dict[str, str] = {} # image_filename โ†’ page_id for i, row in enumerate(islice(ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue filename: str = row.get("image_filename") or f"page_{i}" query_text: str = row.get("query", "") if not query_text: continue # Each unique page is uploaded exactly once; multiple queries may # share the same page (same image_filename). if filename not in seen_pages: page_id = f"{subset}_{len(page_ids):04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) seen_pages[filename] = page_id page_ids.append(page_id) page_files.append(page_file) else: page_id = seen_pages[filename] queries.append( PageQuery( query_id=f"q{i:04d}", text=query_text, relevant_page_id=page_id, ) ) print(f"Loaded {len(page_ids)} unique pages, {len(queries)} queries", flush=True) return PageDataset(page_ids=page_ids, page_files=page_files, queries=queries) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” indexing # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @colpali_indexer.task(cache="auto", retries=2) async def index_colpali(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with ColPali-v1.2 and save the multi-vector index. ColPali skips OCR entirely. It feeds the raw page image into PaliGemma (a vision-language model) and produces one embedding vector per image patch โ€” roughly 1,024 patches per page, each of dimension 128. _colpali_model() is an lru_cache'd loader. On a cold container, it downloads and loads the model once. On a warm container (kept alive by ReusePolicy), it returns the already-loaded model instantly from cache โ€” no repeated ~7 GB download. The index is stored as a .npz file in Flyte's blob store: embeddings โ€” float32, shape (n_pages, n_patches, dim) page_ids โ€” matching page ID strings cache="auto" + retries=2: the result is stored permanently on success; transient failures (e.g. HuggingFace rate limits) are retried twice. """ import torch model, processor, device = _colpali_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 4)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor.process_images(images) inputs = {k: v.to(device) for k, v in inputs.items()} with torch.no_grad(): emb = model(**inputs) # (batch, n_patches, dim) all_embeddings.append(emb.cpu().float().numpy()) print(f"ColPali: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, n_patches, dim) out_path = os.path.join(tempfile.gettempdir(), "colpali_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @siglip_indexer.task(cache="auto", retries=2) async def index_siglip(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with SigLIP SO400M and save the single-vector index. SigLIP (2023) is Google's successor to CLIP, trained with sigmoid loss instead of softmax โ€” avoiding the normalisation bottleneck that limits CLIP's scalability. Produces one global embedding per page. _siglip_model() caches the model across warm container reuses. The index is stored as a .npz file: embeddings โ€” float32, shape (n_pages, dim), L2-normalised page_ids โ€” matching page ID strings """ import torch model, processor, device = _siglip_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 8)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor(images=images, return_tensors="pt", padding=True).to(device) with torch.no_grad(): outputs = model.vision_model(**inputs) emb = outputs.pooler_output # (batch, dim) emb = emb / emb.norm(dim=-1, keepdim=True) # L2 normalise all_embeddings.append(emb.cpu().float().numpy()) print(f"SigLIP: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, dim) out_path = os.path.join(tempfile.gettempdir(), "siglip_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @ocr_engine.task(cache="auto") async def extract_page_texts(page_files: list[File]) -> list[str]: """ OCR every page with doctr on GPU to produce a text-only baseline. doctr bundles DBNet (detection) + CRNN/SAR (recognition) into a single callable predictor. Pages are downloaded in parallel then fed in batches of ocr_batch_size. asyncio.to_thread keeps the event loop unblocked during GPU inference. Result structure: result.pages[i].blocks[j].lines[k].words[l].value Cached: the same corpus is OCR'd at most once across all experiments that use the OCR+BM25 backend. """ import gc predictor = _ocr_model() # Process in batches: download each batch just-in-time so only # ocr_batch_size images are in memory at once instead of all 2 000. ocr_batch_size = 8 total = len(page_files) texts: list[str] = [] for start in range(0, total, ocr_batch_size): batch_files = page_files[start : start + ocr_batch_size] batch_images = list( await asyncio.gather(*[asyncio.to_thread(_load_image_sync, f) for f in batch_files]) ) batch_np = [np.array(img) for img in batch_images] del batch_images result = await asyncio.to_thread(predictor, batch_np) del batch_np for page_output in result.pages: texts.append( "\n".join( " ".join(word.value for word in line.words) for block in page_output.blocks for line in block.lines ) ) del result gc.collect() print(f"OCR: processed {min(start + ocr_batch_size, total)}/{total} pages", flush=True) return texts # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” search # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment search_colpali}} @colpali_indexer.task async def search_colpali( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using ColPali MaxSim late interaction via DynamicBatcher. MaxSim score for page p given query q: score(q, p) = ฮฃ_{t โˆˆ query tokens} max_{j โˆˆ page patches} (q_t ยท p_j) Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_colpali invocations on the same warm container (concurrency=8) into a single GPU batch. This keeps the GPU saturated rather than running one small batch per caller. The batcher's process_fn runs GPU work in asyncio.to_thread, so the aggregation loop stays live while the GPU encodes and scores. """ batcher = await _get_colpali_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] # {{/docs-fragment search_colpali}} @siglip_indexer.task async def search_siglip( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using SigLIP cosine similarity via DynamicBatcher. Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_siglip invocations on the same warm container (concurrency=3) into a single GPU batch. SigLIP's single-vector embeddings make full vectorisation safe โ€” the scores matrix (n_pages x n_queries) is small enough to materialise in one GPU call regardless of batch size. """ batcher = await _get_siglip_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] @driver.task async def search_bm25( page_texts: list[str], page_ids: list[str], queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using BM25 over OCR'd text. The standard keyword-based baseline. No GPU required; strong on text-dense pages, weak on visual content that Tesseract cannot read. """ tokenized = [text.lower().split() for text in page_texts] bm25 = BM25Okapi(tokenized) results: list[RetrievalResult] = [] for q in queries: scores = bm25.get_scores(q.text.lower().split()) ranked = sorted(range(len(page_ids)), key=lambda i: -scores[i])[:top_k] results.append( RetrievalResult( query_id=q.query_id, ranked_page_ids=[page_ids[i] for i in ranked], ) ) return results # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” evaluation # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task async def evaluate( results: list[RetrievalResult], ground_truth: list[PageQuery], k: int, ) -> Metrics: """ Compute Recall@K, NDCG@K, and MRR for a single retrieval model. Recall@K โ€” was the correct page in the top-K results? NDCG@K โ€” normalised discounted cumulative gain; rewards earlier hits. MRR โ€” mean reciprocal rank of the first correct result. All three are averaged over all queries. Higher is better. """ gt_map = {q.query_id: q.relevant_page_id for q in ground_truth} recall_vals, ndcg_vals, mrr_vals = [], [], [] for r in results: relevant = gt_map.get(r.query_id, "") top = r.ranked_page_ids[:k] recall_vals.append(1.0 if relevant in top else 0.0) rels = [1 if pid == relevant else 0 for pid in top] idcg = _dcg([1]) # ideal: correct page at rank 1 ndcg_vals.append(_dcg(rels) / idcg if idcg > 0 else 0.0) rr = 0.0 for rank, pid in enumerate(r.ranked_page_ids, start=1): if pid == relevant: rr = 1.0 / rank break mrr_vals.append(rr) return Metrics( recall_at_k=float(np.mean(recall_vals)), ndcg_at_k=float(np.mean(ndcg_vals)), mrr=float(np.mean(mrr_vals)), k=k, ) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” report # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(report=True) async def generate_report(report: ComparisonReport) -> None: """ Emit an interactive HTML report visible in the Flyte UI. report=True marks this task as a reporting task. Flyte renders the HTML returned via flyte.report.replace.aio() directly in the execution detail page โ€” no separate dashboard or export step required. The report contains: - Summary cards: experiment count, best model, best Recall@K. - Grouped bar chart: Recall@K, NDCG@K, MRR side-by-side per experiment. - Ranked results table with all three metrics. """ sorted_results = sorted(report.results, key=lambda r: -r.metrics.recall_at_k) best = sorted_results[0] labels = [r.config.name for r in sorted_results] recall_vals = [r.metrics.recall_at_k for r in sorted_results] ndcg_vals = [r.metrics.ndcg_at_k for r in sorted_results] mrr_vals = [r.metrics.mrr for r in sorted_results] table_rows = "".join( f""" {r.config.name} {r.config.model.value} {r.metrics.recall_at_k:.3f} {r.metrics.ndcg_at_k:.3f} {r.metrics.mrr:.3f} {r.metrics.k} """ for r in sorted_results ) html = f""" Visual Document Retrieval โ€” Results

Visual Document Retrieval โ€” Experiment Comparison

ViDoRe benchmark · {len(report.results)} experiment(s)

{len(report.results)}
Experiments
{best.config.name}
Best by Recall@K
{best.metrics.recall_at_k:.3f}
Best Recall@{best.metrics.k}
{best.metrics.ndcg_at_k:.3f}
Best NDCG@{best.metrics.k}
{best.metrics.mrr:.3f}
Best MRR

Metrics by Experiment

Ranked Results

{table_rows}
ExperimentModel Recall@KNDCG@KMRRK
""" await flyte.report.replace.aio(html) await flyte.report.flush.aio() # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Experiment orchestration # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment run_experiment}} @driver.task async def run_experiment(config: ExperimentConfig, dataset: PageDataset) -> ExperimentResult: """ End-to-end retrieval pipeline for a single ExperimentConfig. Flyte v2's dynamic execution means this driver task can call GPU tasks (index_colpali, search_colpali) based on the runtime value of config.model โ€” no static DAG wiring required. The if/elif is plain Python; Flyte schedules the selected sub-tasks on the appropriate environment. Caching: two experiments that share the same model and corpus (e.g. ColPali at top_k=5 and top_k=10) will hit the same cached index. GPU work is paid at most once per (model, corpus) pair across all experiments. Search queries are sharded into chunks of SEARCH_SHARD_SIZE and dispatched as concurrent task invocations. All shards land on the single warm container (replicas=1) and feed the same DynamicBatcher simultaneously, keeping the GPU saturated throughout search rather than processing one large sequential batch from a single caller. flyte.group wraps each experiment in a named span in the Flyte UI, making it easy to compare latencies and drill into individual runs. """ SEARCH_SHARD_SIZE = 256 with flyte.group(config.name): if config.model == RetrievalModel.COLPALI: index_file = await index_colpali(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_colpali(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] elif config.model == RetrievalModel.SIGLIP: index_file = await index_siglip(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_siglip(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] else: # RetrievalModel.OCR_BM25 page_texts = await extract_page_texts(dataset.page_files) results = await search_bm25(page_texts, dataset.page_ids, dataset.queries, config.top_k) metrics = await evaluate(results, dataset.queries, config.top_k) return ExperimentResult(config=config, metrics=metrics) # {{/docs-fragment run_experiment}} # {{docs-fragment compare_experiments}} @driver.task async def compare_experiments( configs: list[ExperimentConfig], subset: str = "docvqa", max_pages: int = 200, ) -> ComparisonReport: """ Fan out over all experiment configs and return a ranked comparison table. The dataset is loaded once and shared across all experiments. Each config runs as a concurrent Flyte task via asyncio.gather. Experiments that share a model reuse the cached index โ€” you only pay GPU time for new work. On completion, generate_report emits an interactive Chart.js HTML report visible directly in the Flyte execution detail page. Default dataset: vidore_v3_finance_en (~2 942 corpus pages, 1 854 queries) with max_pages=2 000 to exercise the GPU pipeline at scale. """ dataset = await load_vidore_pages(subset=subset, max_pages=max_pages) # All experiments launch concurrently. Shared cached outputs (same model, # same corpus) are served from cache rather than recomputed. experiment_coros = [run_experiment(config=cfg, dataset=dataset) for cfg in configs] results: list[ExperimentResult] = list(await asyncio.gather(*experiment_coros)) report = ComparisonReport(results=results) print(report.summary()) best = report.best_by("recall_at_k") print(f"\nBest by Recall@{best.metrics.k}: {best.config.name}") # Emit the interactive HTML report in the Flyte UI. await generate_report(report) return report # {{/docs-fragment compare_experiments}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Entry point # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if __name__ == "__main__": flyte.init_from_config() # Define the experiment grid. Each ExperimentConfig is one point in the # design space. Adding a new model or varying top_k is one line here โ€” # no task code changes required. # # ColPali appears twice with different top_k values. The cache ensures # index_colpali runs only once and both experiments share that result. # {{docs-fragment grid}} configs = [ ExperimentConfig(name="colpali-top5", model=RetrievalModel.COLPALI, top_k=5), ExperimentConfig(name="colpali-top10", model=RetrievalModel.COLPALI, top_k=10), ExperimentConfig(name="siglip-top5", model=RetrievalModel.SIGLIP, top_k=5), ExperimentConfig(name="ocr-bm25-top5", model=RetrievalModel.OCR_BM25, top_k=5), ] # {{/docs-fragment grid}} run = flyte.with_runcontext().run( compare_experiments, configs=configs, subset="vidore_v3_finance_en", max_pages=2000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multimodal-retrieval-evaluation/retrieval_eval.py* ## Run the evaluation This example has no secrets: datasets and model weights are pulled from public Hugging Face repositories. It does require GPUs, so run it remotely. The experiment grid is defined in the entry point; adding a model or varying `top_k` is a one-line change: ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "colpali-engine>=0.3.1", # "transformers>=4.41", # "sentencepiece>=0.2", # "torch>=2.0", # "pillow>=10", # "datasets>=2.18", # "rank-bm25>=0.2", # "numpy>=1.26", # "python-doctr[torch]>=0.8", # "pydantic>=2.0", # "flyte>=2.0.0", # ] # /// """ Multimodal Retrieval Evaluation Pipeline This tutorial is an experiment framework for benchmarking visual document retrieval approaches on the ViDoRe benchmark. Each experiment is defined by an ExperimentConfig; the pipeline fans them out as concurrent Flyte tasks and returns a ranked comparison table with an interactive HTML report. The corpus is a set of PDF page images; queries are plain-text questions. Each retrieval method must find the page that answers each question โ€” no text is provided to the model, only the raw image. ColPali-v1.2 โ€” patch-level multi-vector embeddings from a VLM (PaliGemma). No OCR. The model produces one vector per image patch (~1024 per page). MaxSim late-interaction scoring finds the best matching patch for each query token. SigLIP-SO400M โ€” single global embedding per page from Google's 2023 CLIP successor. One matrix multiply per query; fast and effective but a single vector cannot localise fine-grained regions. OCR + BM25 โ€” text-only baseline. doctr (GPU OCR) extracts text in batches, BM25 matches keywords. Strong on text-dense pages; fails on charts, tables, and figures where content is visual. """ import asyncio import enum import json import math import os import tempfile from functools import lru_cache from io import BytesIO from itertools import islice import numpy as np from PIL import Image as PILImage from pydantic import BaseModel from rank_bm25 import BM25Okapi from extras import DynamicBatcher import flyte import flyte.report from flyte.io import File # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Environments # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One Docker image for all tasks. The PEP 723 header defines Python deps. # ca-certificates is required for HTTPS calls to HuggingFace and blob stores. # {{docs-fragment image}} image = ( flyte.Image.from_uv_script(__file__, name="vidore-eval-v2") .with_apt_packages("ca-certificates", "libxcb1", "libgl1", "libglib2.0-0") # unionai-reuse installs the unionai-actor-bridge binary required by ReusePolicy. # Without it every reusable container exits with StartError (exit code 128). .with_pip_packages("unionai-reuse>=0.1.11") ) # {{/docs-fragment image}} # GPU environment for ColPali image encoding and search. # # ReusePolicy keeps up to 3 warm GPU containers alive between task calls. # Without it, every task invocation cold-starts a new container and downloads # ColPali-v1.2 (~7 GB) from scratch. With it, the container โ€” and the model # weights already loaded into VRAM โ€” is reused for the next task dispatch. # # replicas=1 single warm container โ€” all concurrent shard calls land # here so they share one DynamicBatcher process # concurrency=8 up to 8 query-shard tasks run simultaneously on the # container, all feeding the same DynamicBatcher queue # idle_ttl=120 keep alive 2 min after the last task finishes # scaledown_ttl=60 scale to zero after 1 min of complete inactivity # {{docs-fragment envs}} colpali_indexer = flyte.TaskEnvironment( name="vidore-colpali-indexer", image=image, resources=flyte.Resources(cpu=4, memory="16Gi", gpu="A10G:1"), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for SigLIP image encoding and search. # # Separate from the ColPali environment so each model's warm containers # are managed independently โ€” ColPali and SigLIP experiments can scale # without contending for the same pool of reusable containers. siglip_indexer = flyte.TaskEnvironment( name="vidore-siglip-indexer", image=image, resources=flyte.Resources(cpu=4, memory="8Gi", gpu=1), reusable=flyte.ReusePolicy( replicas=1, concurrency=8, idle_ttl=120, scaledown_ttl=60, ), ) # GPU environment for doctr OCR. doctr runs DBNet (detection) + CRNN (recognition) # in batches on GPU โ€” much faster than CPU Tesseract. # No ReusePolicy needed: the result is cached, so this task runs at most once. ocr_engine = flyte.TaskEnvironment( name="vidore-ocr-engine", image=image, resources=flyte.Resources(cpu=4, memory="20Gi", gpu=1), ) # Driver: orchestration, BM25 search, evaluation, and reporting. # depends_on ensures the shared Docker image is built before all environments # try to schedule tasks. driver = flyte.TaskEnvironment( name="vidore-driver", image=image, resources=flyte.Resources(cpu=2, memory="12Gi"), depends_on=[colpali_indexer, siglip_indexer, ocr_engine], ) # {{/docs-fragment envs}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Configuration types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment config_types}} class RetrievalModel(str, enum.Enum): """Retrieval backend to evaluate.""" COLPALI = "colpali-v1.2" # multi-vector patch embeddings, MaxSim SIGLIP = "siglip-so400m" # single-vector global embedding, cosine sim OCR_BM25 = "ocr+bm25" # text extracted by Tesseract, ranked by BM25 class ExperimentConfig(BaseModel): """ All knobs for one retrieval experiment. Passed as a typed Flyte input. Because ExperimentConfig is a Pydantic model, Flyte serialises it alongside every task output โ€” so you can always reconstruct which config produced which metric without maintaining a separate log. """ name: str # human-readable label shown in the comparison table model: RetrievalModel top_k: int = 5 # number of pages to retrieve per query # {{/docs-fragment config_types}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Data types # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment data_types}} class PageQuery(BaseModel): """One retrieval query with its ground-truth page.""" query_id: str text: str # e.g. "What was revenue growth in Q3?" relevant_page_id: str # one correct page per query class PageDataset(BaseModel): """ A corpus of document page images paired with text queries. page_ids: unique page identifiers (derived from ViDoRe image filenames). page_files: the same pages stored in Flyte's blob store as JPEG File handles. Tasks read images directly from here; no live HTTP. queries: text questions with ground-truth page IDs for evaluation. """ page_ids: list[str] page_files: list[File] queries: list[PageQuery] class Config: arbitrary_types_allowed = True class RetrievalResult(BaseModel): query_id: str ranked_page_ids: list[str] # ordered best โ†’ worst class Metrics(BaseModel): recall_at_k: float ndcg_at_k: float mrr: float k: int class ExperimentResult(BaseModel): config: ExperimentConfig metrics: Metrics # {{/docs-fragment data_types}} class ComparisonReport(BaseModel): results: list[ExperimentResult] def best_by(self, metric: str = "recall_at_k") -> ExperimentResult: return max(self.results, key=lambda r: getattr(r.metrics, metric)) def summary(self) -> str: header = f"{'Experiment':<30} {'Model':<18} {'Recall@K':>10} {'NDCG@K':>8} {'MRR':>7}" sep = "โ”€" * len(header) rows = [header, sep] for r in sorted(self.results, key=lambda x: -x.metrics.recall_at_k): rows.append( f"{r.config.name:<30} " f"{r.config.model.value:<18} " f"{r.metrics.recall_at_k:>10.3f} " f"{r.metrics.ndcg_at_k:>8.3f} " f"{r.metrics.mrr:>7.3f}" ) return "\n".join(rows) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Cached model loaders # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # These functions are at module level so they are shared across all tasks that # run on the same warm container (via ReusePolicy). lru_cache(maxsize=1) means # the model is loaded from disk/HuggingFace exactly once per container process # and kept in GPU memory for every subsequent task dispatch to that container. @lru_cache(maxsize=1) def _colpali_model(): """Load ColPali-v1.2 into GPU memory and cache the result. device_map= is the correct loading pattern for ColPali's PaliGemma backbone; it handles weight placement via accelerate. torch.compile is skipped โ€” ColPali is GPU-compute-bound and the DynamicBatcher's cross- invocation batching is the primary GPU utilisation mechanism. """ import torch from colpali_engine.models import ColPali, ColPaliProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = ColPali.from_pretrained( "vidore/colpali-v1.2", torch_dtype=torch.bfloat16, device_map=device, ) processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.2") return model, processor, device @lru_cache(maxsize=1) def _siglip_model(): """Load SigLIP SO400M into GPU memory, compile it, and cache the result. torch.compile (mode="reduce-overhead") fuses the vision and text encoder transformer layers into optimised CUDA kernels. As with ColPali, the compilation overhead is paid once per warm container lifetime. """ import torch from transformers import AutoModel, AutoProcessor device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModel.from_pretrained("google/siglip-so400m-patch14-224").to(device) if device == "cuda": model = torch.compile(model, mode="reduce-overhead") processor = AutoProcessor.from_pretrained("google/siglip-so400m-patch14-224") return model, processor, device @lru_cache(maxsize=1) def _ocr_model(): """Load the doctr OCR predictor onto GPU and cache it. doctr's ocr_predictor bundles a detection model (DBNet) and a recognition model (CRNN/SAR) into a single callable. pretrained=True downloads both model weights from doctr's model zoo on first use. """ import torch from doctr.models import ocr_predictor predictor = ocr_predictor(pretrained=True) if torch.cuda.is_available(): predictor = predictor.cuda() return predictor # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Search batcher singletons # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # One DynamicBatcher per model, shared across all concurrent search task # invocations on the same warm container (concurrency=3). Queries from every # concurrent caller are aggregated into a single GPU batch, maximizing # throughput compared to each invocation running its own forward pass. # # Initialised lazily on the first search call via double-checked locking and # lives for the container's lifetime. The process_fn runs GPU work via # asyncio.to_thread so the aggregation loop can continue collecting queries # from other callers while the GPU processes the current batch. # # File is not hashable so alru_cache cannot be used here; module-level state # with asyncio.Lock is the correct pattern. # # Assumption: index_colpali/index_siglip use cache="auto", so the same corpus # always produces the same index File across all callers on this container. If # the index file ever changed between calls, the batcher would silently continue # using the corpus embeddings loaded from the first call. _colpali_batcher: DynamicBatcher | None = None _colpali_batcher_lock = asyncio.Lock() _siglip_batcher: DynamicBatcher | None = None _siglip_batcher_lock = asyncio.Lock() async def _get_colpali_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level ColPali search batcher, creating it on first call.""" global _colpali_batcher if _colpali_batcher is not None: return _colpali_batcher async with _colpali_batcher_lock: if _colpali_batcher is not None: return _colpali_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, n_patches, dim) index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _colpali_model() corpus_emb = corpus_emb.to(device, dtype=torch.float32) async def colpali_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: query_inputs = processor.process_queries([q.text for q in batch]) query_inputs = {k: v.to(device) for k, v in query_inputs.items()} with torch.no_grad(): query_embs = model(**query_inputs).float() # (B, T, D) query_chunk = 8 n_pages = corpus_emb.shape[0] all_scores = torch.empty(len(batch), n_pages, device=device) for start in range(0, len(batch), query_chunk): chunk = query_embs[start : start + query_chunk] all_scores[start : start + query_chunk] = ( torch.einsum("ctd,pjd->ctpj", chunk, corpus_emb) .max(dim=3).values .sum(dim=1) ) sorted_indices = all_scores.argsort(dim=1, descending=True).cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] # Run GPU work in a thread so the event loop โ€” and the batcher's # aggregation loop โ€” remain unblocked while the GPU is busy. return await asyncio.to_thread(_gpu_work) batcher: DynamicBatcher[PageQuery, list[str]] = DynamicBatcher( process_fn=colpali_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _colpali_batcher = batcher return _colpali_batcher async def _get_siglip_search_batcher(index_file: File) -> DynamicBatcher: """Return the process-level SigLIP search batcher, creating it on first call.""" global _siglip_batcher if _siglip_batcher is not None: return _siglip_batcher async with _siglip_batcher_lock: if _siglip_batcher is not None: return _siglip_batcher import torch data = await _load_npz(index_file) corpus_emb = torch.from_numpy(data["embeddings"]) # (n_pages, dim), L2-normalised index_page_ids: list[str] = list(data["page_ids"]) model, processor, device = _siglip_model() corpus_emb = corpus_emb.to(device) async def siglip_process_fn(batch: list[PageQuery]) -> list[list[str]]: def _gpu_work() -> list[list[str]]: text_inputs = processor( text=[q.text for q in batch], return_tensors="pt", padding=True, truncation=True, ).to(device) with torch.no_grad(): text_out = model.text_model(**text_inputs) query_embs = text_out.pooler_output # (B, dim) query_embs = query_embs / query_embs.norm(dim=-1, keepdim=True) scores_matrix = corpus_emb @ query_embs.T # (n_pages, B) sorted_indices = scores_matrix.argsort(dim=0, descending=True).T.cpu().tolist() return [[index_page_ids[j] for j in ranked] for ranked in sorted_indices] return await asyncio.to_thread(_gpu_work) batcher = DynamicBatcher( process_fn=siglip_process_fn, target_batch_cost=128, max_batch_size=128, batch_timeout_s=0.05, default_cost=1, prefetch_batches=2, ) await batcher.start() _siglip_batcher = batcher return _siglip_batcher # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Helpers # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _batches(items: list, batch_size: int): """Yield successive fixed-size batches from a list.""" for start in range(0, len(items), batch_size): yield items[start : start + batch_size] def _load_image_sync(f: File) -> PILImage.Image: """Blocking download + decode. Intended to be called from a thread pool.""" with f.open_sync("rb") as fh: data = fh.read() return PILImage.open(BytesIO(data)).convert("RGB") async def _load_image(f: File) -> PILImage.Image: """Download and decode a page image in a thread-pool worker. asyncio.to_thread runs _load_image_sync in a real OS thread so that blocking network I/O can overlap with GPU-bound forward passes when images are pre-submitted via loop.run_in_executor before the GPU kernel. """ return await asyncio.to_thread(_load_image_sync, f) async def _load_npz(index_file: File) -> np.lib.npyio.NpzFile: """Download an index File to a local temp path and open with np.load.""" with tempfile.NamedTemporaryFile(suffix=".npz", delete=False) as tmp: async with index_file.open("rb") as fh: tmp.write(bytes(await fh.read())) return np.load(tmp.name) def _dcg(relevances: list[int]) -> float: return sum(rel / math.log2(rank + 2) for rank, rel in enumerate(relevances)) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” data loading # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(cache="auto", retries=3) async def load_vidore_pages(subset: str = "docvqa", max_pages: int = 200) -> PageDataset: """ Load a ViDoRe benchmark subset and store page images in Flyte's blob store. Supports two dataset formats: Legacy (subsampled) โ€” single 'test' split with one row per (query, page) pair; fields: image, query, image_filename. streaming=True reads only the rows requested via islice โ€” no full-shard download. Datasets: vidore/docvqa_test_subsampled, vidore/infovqa_test_subsampled V3 โ€” separate corpus / queries / qrels splits following the BEIR retrieval benchmark format. corpus contains page images; queries contains question text; qrels maps query IDs to relevant corpus page IDs (many-to-many). Datasets: vidore/vidore_v3_finance_en (~2 942 pages, 1 854 queries) The first call uploads page images to Flyte's blob store and caches the PageDataset; every subsequent call with the same arguments returns the cached result instantly. retries=3 guards against transient HuggingFace network failures. Available subsets: "docvqa", "infovqa", "vidore_v3_finance_en" """ from datasets import load_dataset subset_map = { "docvqa": "vidore/docvqa_test_subsampled", "infovqa": "vidore/infovqa_test_subsampled", "vidore_v3_finance_en": "vidore/vidore_v3_finance_en", } dataset_name = subset_map.get(subset, f"vidore/{subset}_test_subsampled") # V3 datasets ship with separate corpus / queries / qrels splits. _V3_SUBSETS = {"vidore_v3_finance_en"} if subset in _V3_SUBSETS: # โ”€โ”€ V3 format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # corpus / queries / qrels are HuggingFace configs (name=), not splits. # corpus uses streaming=True so images are decoded one at a time โ€” # loading all 2 942 rows eagerly would hold gigabytes of PIL images in # the driver's RAM simultaneously. qrels and queries are text-only and # small enough to load fully into memory. corpus_ds = load_dataset(dataset_name, name="corpus", split="test", streaming=True) qrels_ds = load_dataset(dataset_name, name="qrels", split="test") queries_ds = load_dataset(dataset_name, name="queries", split="test") # Normalise field names โ€” V3 follows BEIR convention (hyphenated ids). def _col(ds, *candidates): cols = set(ds.column_names) for c in candidates: if c in cols: return c raise KeyError(f"None of {candidates} found in columns {cols}") corpus_id_col = _col(corpus_ds, "corpus-id", "corpus_id", "id", "_id") query_id_col = _col(queries_ds, "query-id", "query_id", "id", "_id") query_text_col = _col(queries_ds, "query", "text") qrel_qid_col = _col(qrels_ds, "query-id", "query_id") qrel_cid_col = _col(qrels_ds, "corpus-id", "corpus_id") # Slice corpus to max_pages, upload each image to Flyte blob store. page_ids: list[str] = [] page_files: list[File] = [] corpus_id_to_page_id: dict[str, str] = {} for i, row in enumerate(islice(corpus_ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue cid = str(row[corpus_id_col]) page_id = f"{subset}_{i:04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) corpus_id_to_page_id[cid] = page_id page_ids.append(page_id) page_files.append(page_file) # Build query_id โ†’ relevant page_id from qrels (first match wins). # Only keep relevance judgements whose corpus page is in our slice. qrel_map: dict[str, str] = {} for row in qrels_ds: qid = str(row[qrel_qid_col]) cid = str(row[qrel_cid_col]) if cid in corpus_id_to_page_id and qid not in qrel_map: qrel_map[qid] = corpus_id_to_page_id[cid] # Collect queries that have at least one relevant page in our slice. queries: list[PageQuery] = [] for row in queries_ds: qid = str(row[query_id_col]) if qid not in qrel_map: continue queries.append( PageQuery( query_id=qid, text=str(row[query_text_col]), relevant_page_id=qrel_map[qid], ) ) else: # โ”€โ”€ Legacy format โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Single 'test' split with one row per (query, page) pair. ds = load_dataset(dataset_name, split="test", streaming=True) page_ids = [] page_files = [] queries = [] seen_pages: dict[str, str] = {} # image_filename โ†’ page_id for i, row in enumerate(islice(ds, max_pages)): img = row.get("image") if not isinstance(img, PILImage.Image): continue filename: str = row.get("image_filename") or f"page_{i}" query_text: str = row.get("query", "") if not query_text: continue # Each unique page is uploaded exactly once; multiple queries may # share the same page (same image_filename). if filename not in seen_pages: page_id = f"{subset}_{len(page_ids):04d}" with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: tmp_path = f.name img.convert("RGB").save(tmp_path, format="JPEG") del img # free PIL memory before upload page_file = await File.from_local(tmp_path) os.unlink(tmp_path) seen_pages[filename] = page_id page_ids.append(page_id) page_files.append(page_file) else: page_id = seen_pages[filename] queries.append( PageQuery( query_id=f"q{i:04d}", text=query_text, relevant_page_id=page_id, ) ) print(f"Loaded {len(page_ids)} unique pages, {len(queries)} queries", flush=True) return PageDataset(page_ids=page_ids, page_files=page_files, queries=queries) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” indexing # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @colpali_indexer.task(cache="auto", retries=2) async def index_colpali(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with ColPali-v1.2 and save the multi-vector index. ColPali skips OCR entirely. It feeds the raw page image into PaliGemma (a vision-language model) and produces one embedding vector per image patch โ€” roughly 1,024 patches per page, each of dimension 128. _colpali_model() is an lru_cache'd loader. On a cold container, it downloads and loads the model once. On a warm container (kept alive by ReusePolicy), it returns the already-loaded model instantly from cache โ€” no repeated ~7 GB download. The index is stored as a .npz file in Flyte's blob store: embeddings โ€” float32, shape (n_pages, n_patches, dim) page_ids โ€” matching page ID strings cache="auto" + retries=2: the result is stored permanently on success; transient failures (e.g. HuggingFace rate limits) are retried twice. """ import torch model, processor, device = _colpali_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 4)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor.process_images(images) inputs = {k: v.to(device) for k, v in inputs.items()} with torch.no_grad(): emb = model(**inputs) # (batch, n_patches, dim) all_embeddings.append(emb.cpu().float().numpy()) print(f"ColPali: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, n_patches, dim) out_path = os.path.join(tempfile.gettempdir(), "colpali_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @siglip_indexer.task(cache="auto", retries=2) async def index_siglip(page_ids: list[str], page_files: list[File]) -> File: """ Encode every page with SigLIP SO400M and save the single-vector index. SigLIP (2023) is Google's successor to CLIP, trained with sigmoid loss instead of softmax โ€” avoiding the normalisation bottleneck that limits CLIP's scalability. Produces one global embedding per page. _siglip_model() caches the model across warm container reuses. The index is stored as a .npz file: embeddings โ€” float32, shape (n_pages, dim), L2-normalised page_ids โ€” matching page ID strings """ import torch model, processor, device = _siglip_model() loop = asyncio.get_running_loop() batches = list(_batches(page_files, 8)) n_batches = len(batches) # Submit the first batch to the thread pool before entering the loop so # that downloads are already in flight when we first await them. prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[0]] all_embeddings: list[np.ndarray] = [] for batch_idx in range(n_batches): images = list(await asyncio.gather(*prefetch)) # Submit next batch downloads immediately โ€” OS threads run these in # parallel with the GPU forward pass below. if batch_idx + 1 < n_batches: prefetch = [loop.run_in_executor(None, _load_image_sync, f) for f in batches[batch_idx + 1]] inputs = processor(images=images, return_tensors="pt", padding=True).to(device) with torch.no_grad(): outputs = model.vision_model(**inputs) emb = outputs.pooler_output # (batch, dim) emb = emb / emb.norm(dim=-1, keepdim=True) # L2 normalise all_embeddings.append(emb.cpu().float().numpy()) print(f"SigLIP: indexed batch {batch_idx + 1}/{n_batches}", flush=True) embeddings = np.concatenate(all_embeddings, axis=0) # (n_pages, dim) out_path = os.path.join(tempfile.gettempdir(), "siglip_index.npz") np.savez(out_path, embeddings=embeddings, page_ids=np.array(page_ids)) return await File.from_local(out_path) @ocr_engine.task(cache="auto") async def extract_page_texts(page_files: list[File]) -> list[str]: """ OCR every page with doctr on GPU to produce a text-only baseline. doctr bundles DBNet (detection) + CRNN/SAR (recognition) into a single callable predictor. Pages are downloaded in parallel then fed in batches of ocr_batch_size. asyncio.to_thread keeps the event loop unblocked during GPU inference. Result structure: result.pages[i].blocks[j].lines[k].words[l].value Cached: the same corpus is OCR'd at most once across all experiments that use the OCR+BM25 backend. """ import gc predictor = _ocr_model() # Process in batches: download each batch just-in-time so only # ocr_batch_size images are in memory at once instead of all 2 000. ocr_batch_size = 8 total = len(page_files) texts: list[str] = [] for start in range(0, total, ocr_batch_size): batch_files = page_files[start : start + ocr_batch_size] batch_images = list( await asyncio.gather(*[asyncio.to_thread(_load_image_sync, f) for f in batch_files]) ) batch_np = [np.array(img) for img in batch_images] del batch_images result = await asyncio.to_thread(predictor, batch_np) del batch_np for page_output in result.pages: texts.append( "\n".join( " ".join(word.value for word in line.words) for block in page_output.blocks for line in block.lines ) ) del result gc.collect() print(f"OCR: processed {min(start + ocr_batch_size, total)}/{total} pages", flush=True) return texts # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” search # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment search_colpali}} @colpali_indexer.task async def search_colpali( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using ColPali MaxSim late interaction via DynamicBatcher. MaxSim score for page p given query q: score(q, p) = ฮฃ_{t โˆˆ query tokens} max_{j โˆˆ page patches} (q_t ยท p_j) Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_colpali invocations on the same warm container (concurrency=8) into a single GPU batch. This keeps the GPU saturated rather than running one small batch per caller. The batcher's process_fn runs GPU work in asyncio.to_thread, so the aggregation loop stays live while the GPU encodes and scores. """ batcher = await _get_colpali_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] # {{/docs-fragment search_colpali}} @siglip_indexer.task async def search_siglip( index_file: File, queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using SigLIP cosine similarity via DynamicBatcher. Each query is submitted to the process-level DynamicBatcher, which aggregates queries from all concurrent search_siglip invocations on the same warm container (concurrency=3) into a single GPU batch. SigLIP's single-vector embeddings make full vectorisation safe โ€” the scores matrix (n_pages x n_queries) is small enough to materialise in one GPU call regardless of batch size. """ batcher = await _get_siglip_search_batcher(index_file) futures = await batcher.submit_batch(queries) all_ranked: list[list[str]] = list(await asyncio.gather(*futures)) return [ RetrievalResult(query_id=q.query_id, ranked_page_ids=ranked[:top_k]) for q, ranked in zip(queries, all_ranked) ] @driver.task async def search_bm25( page_texts: list[str], page_ids: list[str], queries: list[PageQuery], top_k: int, ) -> list[RetrievalResult]: """ Retrieve pages using BM25 over OCR'd text. The standard keyword-based baseline. No GPU required; strong on text-dense pages, weak on visual content that Tesseract cannot read. """ tokenized = [text.lower().split() for text in page_texts] bm25 = BM25Okapi(tokenized) results: list[RetrievalResult] = [] for q in queries: scores = bm25.get_scores(q.text.lower().split()) ranked = sorted(range(len(page_ids)), key=lambda i: -scores[i])[:top_k] results.append( RetrievalResult( query_id=q.query_id, ranked_page_ids=[page_ids[i] for i in ranked], ) ) return results # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” evaluation # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task async def evaluate( results: list[RetrievalResult], ground_truth: list[PageQuery], k: int, ) -> Metrics: """ Compute Recall@K, NDCG@K, and MRR for a single retrieval model. Recall@K โ€” was the correct page in the top-K results? NDCG@K โ€” normalised discounted cumulative gain; rewards earlier hits. MRR โ€” mean reciprocal rank of the first correct result. All three are averaged over all queries. Higher is better. """ gt_map = {q.query_id: q.relevant_page_id for q in ground_truth} recall_vals, ndcg_vals, mrr_vals = [], [], [] for r in results: relevant = gt_map.get(r.query_id, "") top = r.ranked_page_ids[:k] recall_vals.append(1.0 if relevant in top else 0.0) rels = [1 if pid == relevant else 0 for pid in top] idcg = _dcg([1]) # ideal: correct page at rank 1 ndcg_vals.append(_dcg(rels) / idcg if idcg > 0 else 0.0) rr = 0.0 for rank, pid in enumerate(r.ranked_page_ids, start=1): if pid == relevant: rr = 1.0 / rank break mrr_vals.append(rr) return Metrics( recall_at_k=float(np.mean(recall_vals)), ndcg_at_k=float(np.mean(ndcg_vals)), mrr=float(np.mean(mrr_vals)), k=k, ) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Tasks โ€” report # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @driver.task(report=True) async def generate_report(report: ComparisonReport) -> None: """ Emit an interactive HTML report visible in the Flyte UI. report=True marks this task as a reporting task. Flyte renders the HTML returned via flyte.report.replace.aio() directly in the execution detail page โ€” no separate dashboard or export step required. The report contains: - Summary cards: experiment count, best model, best Recall@K. - Grouped bar chart: Recall@K, NDCG@K, MRR side-by-side per experiment. - Ranked results table with all three metrics. """ sorted_results = sorted(report.results, key=lambda r: -r.metrics.recall_at_k) best = sorted_results[0] labels = [r.config.name for r in sorted_results] recall_vals = [r.metrics.recall_at_k for r in sorted_results] ndcg_vals = [r.metrics.ndcg_at_k for r in sorted_results] mrr_vals = [r.metrics.mrr for r in sorted_results] table_rows = "".join( f""" {r.config.name} {r.config.model.value} {r.metrics.recall_at_k:.3f} {r.metrics.ndcg_at_k:.3f} {r.metrics.mrr:.3f} {r.metrics.k} """ for r in sorted_results ) html = f""" Visual Document Retrieval โ€” Results

Visual Document Retrieval โ€” Experiment Comparison

ViDoRe benchmark · {len(report.results)} experiment(s)

{len(report.results)}
Experiments
{best.config.name}
Best by Recall@K
{best.metrics.recall_at_k:.3f}
Best Recall@{best.metrics.k}
{best.metrics.ndcg_at_k:.3f}
Best NDCG@{best.metrics.k}
{best.metrics.mrr:.3f}
Best MRR

Metrics by Experiment

Ranked Results

{table_rows}
ExperimentModel Recall@KNDCG@KMRRK
""" await flyte.report.replace.aio(html) await flyte.report.flush.aio() # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Experiment orchestration # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # {{docs-fragment run_experiment}} @driver.task async def run_experiment(config: ExperimentConfig, dataset: PageDataset) -> ExperimentResult: """ End-to-end retrieval pipeline for a single ExperimentConfig. Flyte v2's dynamic execution means this driver task can call GPU tasks (index_colpali, search_colpali) based on the runtime value of config.model โ€” no static DAG wiring required. The if/elif is plain Python; Flyte schedules the selected sub-tasks on the appropriate environment. Caching: two experiments that share the same model and corpus (e.g. ColPali at top_k=5 and top_k=10) will hit the same cached index. GPU work is paid at most once per (model, corpus) pair across all experiments. Search queries are sharded into chunks of SEARCH_SHARD_SIZE and dispatched as concurrent task invocations. All shards land on the single warm container (replicas=1) and feed the same DynamicBatcher simultaneously, keeping the GPU saturated throughout search rather than processing one large sequential batch from a single caller. flyte.group wraps each experiment in a named span in the Flyte UI, making it easy to compare latencies and drill into individual runs. """ SEARCH_SHARD_SIZE = 256 with flyte.group(config.name): if config.model == RetrievalModel.COLPALI: index_file = await index_colpali(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_colpali(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] elif config.model == RetrievalModel.SIGLIP: index_file = await index_siglip(dataset.page_ids, dataset.page_files) shards = list(_batches(dataset.queries, SEARCH_SHARD_SIZE)) shard_results = await asyncio.gather( *[search_siglip(index_file, shard, config.top_k) for shard in shards] ) results = [r for shard in shard_results for r in shard] else: # RetrievalModel.OCR_BM25 page_texts = await extract_page_texts(dataset.page_files) results = await search_bm25(page_texts, dataset.page_ids, dataset.queries, config.top_k) metrics = await evaluate(results, dataset.queries, config.top_k) return ExperimentResult(config=config, metrics=metrics) # {{/docs-fragment run_experiment}} # {{docs-fragment compare_experiments}} @driver.task async def compare_experiments( configs: list[ExperimentConfig], subset: str = "docvqa", max_pages: int = 200, ) -> ComparisonReport: """ Fan out over all experiment configs and return a ranked comparison table. The dataset is loaded once and shared across all experiments. Each config runs as a concurrent Flyte task via asyncio.gather. Experiments that share a model reuse the cached index โ€” you only pay GPU time for new work. On completion, generate_report emits an interactive Chart.js HTML report visible directly in the Flyte execution detail page. Default dataset: vidore_v3_finance_en (~2 942 corpus pages, 1 854 queries) with max_pages=2 000 to exercise the GPU pipeline at scale. """ dataset = await load_vidore_pages(subset=subset, max_pages=max_pages) # All experiments launch concurrently. Shared cached outputs (same model, # same corpus) are served from cache rather than recomputed. experiment_coros = [run_experiment(config=cfg, dataset=dataset) for cfg in configs] results: list[ExperimentResult] = list(await asyncio.gather(*experiment_coros)) report = ComparisonReport(results=results) print(report.summary()) best = report.best_by("recall_at_k") print(f"\nBest by Recall@{best.metrics.k}: {best.config.name}") # Emit the interactive HTML report in the Flyte UI. await generate_report(report) return report # {{/docs-fragment compare_experiments}} # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Entry point # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ if __name__ == "__main__": flyte.init_from_config() # Define the experiment grid. Each ExperimentConfig is one point in the # design space. Adding a new model or varying top_k is one line here โ€” # no task code changes required. # # ColPali appears twice with different top_k values. The cache ensures # index_colpali runs only once and both experiments share that result. # {{docs-fragment grid}} configs = [ ExperimentConfig(name="colpali-top5", model=RetrievalModel.COLPALI, top_k=5), ExperimentConfig(name="colpali-top10", model=RetrievalModel.COLPALI, top_k=10), ExperimentConfig(name="siglip-top5", model=RetrievalModel.SIGLIP, top_k=5), ExperimentConfig(name="ocr-bm25-top5", model=RetrievalModel.OCR_BM25, top_k=5), ] # {{/docs-fragment grid}} run = flyte.with_runcontext().run( compare_experiments, configs=configs, subset="vidore_v3_finance_en", max_pages=2000, ) print(f"Run URL: {run.url}") ``` *Source: https://github.com/unionai/unionai-examples/blob/main/v2/tutorials/multimodal-retrieval-evaluation/retrieval_eval.py* From the [example directory](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/multimodal-retrieval-evaluation): ``` cd v2/tutorials/multimodal-retrieval-evaluation python retrieval_eval.py ``` When the run completes, open the `generate_report` task in the UI to see the summary cards, the grouped Recall@K / NDCG@K / MRR bar chart, and the ranked results table. === PAGE: https://www.union.ai/docs/v2/union/tutorials/computer-vision/detr-object-detection === Fine-tune RT-DETRv2 on a COCO dataset with live training charts, mAP evaluation, and bounding-box demos. # RT-DETR object detection > [!NOTE] > Code available [on GitHub](https://github.com/unionai/unionai-examples/tree/main/v2/tutorials/detr_object_detection). This tutorial fine-tunes [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r18vd) on a custom COCO-format dataset from HuggingFace. The pipeline downloads and splits the data, fine-tunes the detector with live training charts in Flyte reports, evaluates COCO mAP on a validation split, and renders a side-by-side inference demo with ground-truth and predicted bounding boxes. Flyte highlights: - **Cached dataset preparation** so re-runs skip the HuggingFace download. - **Live training reports** with loss curves and optional periodic mAP checkpoints. - **GPU evaluation and demo tasks** that stream annotated images into the UI. ## Define the task environments ``` # /// script # requires-python = ">=3.12" # dependencies = [ # "flyte>=2.4.0", # "torch>=2.9.0", # "torchvision>=0.24.0", # "transformers>=4.49.0", # "accelerate>=0.34.0", # "huggingface_hub>=0.24.0", # "datasets>=3.0.0", # "pillow>=10.0.0", # "albumentations>=1.4.0", # "torchmetrics>=1.4.0", # "pycocotools>=2.0.7", # "numpy", # ] # main = "pipeline" # params = "" # /// import asyncio import base64 import io import json import logging import os import random import shutil import tempfile import flyte import flyte.io import flyte.report # {{docs-fragment env}} main_img = flyte.Image.from_uv_script(__file__, name="detr-object-detection", pre=True) gpu_env = flyte.TaskEnvironment( name="detr-object-detection-gpu", image=main_img, resources=flyte.Resources(cpu=4, memory="24Gi", gpu=1), ) cpu_env = flyte.TaskEnvironment( name="detr-object-detection-cpu", image=main_img, resources=flyte.Resources(cpu=2, memory="6Gi"), depends_on=[gpu_env], ) # {{/docs-fragment env}} logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True) log = logging.getLogger(__name__) log.setLevel(logging.INFO) # ------------------------------------------------------------------ # Report styling โ€” shared CSS for all task reports # ------------------------------------------------------------------ REPORT_CSS = """ """ def _wrap_report(html: str) -> str: """Wrap HTML content with report styling.""" return f'{REPORT_CSS}
{html}
' # ------------------------------------------------------------------ # SVG chart helpers โ€” lightweight charts without matplotlib # ------------------------------------------------------------------ def _make_line_chart( data: list[dict], x_key: str, y_keys: list[str], title: str = "", x_label: str = "", y_label: str = "", colors: list[str] | None = None, width: int = 700, height: int = 300, y_max_cap: float | None = None, x_range_override: tuple[float, float] | None = None, y_display_names: dict[str, str] | None = None, ) -> str: """Generate an SVG line chart from a list of dicts. Args: data: List of dicts, each with x_key and y_keys values. x_key: Key for x-axis values. y_keys: Keys for y-axis series to plot. title: Chart title. x_label: X-axis label. y_label: Y-axis label. colors: Colors for each series (defaults to a built-in palette). width: SVG width in pixels. height: SVG height in pixels. y_max_cap: If set, cap the y-axis at this value (e.g. 1.0 for mAP). x_range_override: If set, force the x-axis to this (min, max) range. Returns: SVG string. """ default_colors = ["#5a7db5", "#0f3460", "#06d6a0", "#ffc107", "#6c757d"] colors = colors or default_colors # Chart area margins ml, mr, mt, mb = 60, 20, 40, 50 cw = width - ml - mr ch = height - mt - mb x_vals = [d[x_key] for d in data] if data else [] if x_range_override: x_min, x_max = x_range_override elif x_vals: x_min, x_max = min(x_vals), max(x_vals) else: x_min, x_max = 0, 1 x_range = x_max - x_min or 1 # Compute y range across all series all_y = [] for key in y_keys: all_y.extend(d[key] for d in data if key in d) y_min = min(all_y) if all_y else 0 y_max = max(all_y) if all_y else 1 y_pad = (y_max - y_min) * 0.1 or 0.1 y_min_plot = max(0, y_min - y_pad) y_max_plot = y_max + y_pad if y_max_cap is not None: y_max_plot = min(y_max_plot, y_max_cap) y_range = y_max_plot - y_min_plot or 1 def sx(v): return ml + (v - x_min) / x_range * cw def sy(v): return mt + ch - (v - y_min_plot) / y_range * ch # Build SVG lines = [ f'', # Background f'', ] # Grid lines (5 horizontal) for i in range(6): y_tick = y_min_plot + y_range * i / 5 py = sy(y_tick) lines.append( f'' ) lines.append( f'{y_tick:.3f}' ) # Axes lines.append( f'' ) lines.append( f'' ) # X-axis ticks if x_vals: n_x_ticks = min(len(data), 10) step = max(1, len(data) // n_x_ticks) for i in range(0, len(data), step): px = sx(x_vals[i]) lines.append( f'{x_vals[i]:.0f}' ) else: # Empty chart โ€” generate evenly spaced ticks from x range for i in range(6): x_tick = x_min + x_range * i / 5 px = sx(x_tick) lines.append( f'{x_tick:.0f}' ) # Plot each series if not data: # Empty chart placeholder lines.append( f'Waiting for data...' ) for si, key in enumerate(y_keys): color = colors[si % len(colors)] points = [(sx(d[x_key]), sy(d[key])) for d in data if key in d] if not points: continue # Draw line if we have 2+ points (dash odd series for visibility) if len(points) >= 2: path_d = f"M {points[0][0]:.1f},{points[0][1]:.1f}" for px, py in points[1:]: path_d += f" L {px:.1f},{py:.1f}" dash = ' stroke-dasharray="6,3"' if si % 2 == 1 else "" lines.append( f'' ) # Always show dots for sparse data (including single points) if len(points) <= 30: for px, py in points: lines.append( f'' ) # Title if title: lines.append( f'{title}' ) # Axis labels if x_label: lines.append( f'{x_label}' ) if y_label: lines.append( f'{y_label}' ) # Legend names = y_display_names or {} if len(y_keys) > 1: lx = ml + 10 for si, key in enumerate(y_keys): color = colors[si % len(colors)] ly = mt + 14 + si * 18 lines.append( f'' ) label = names.get(key, key) lines.append( f'{label}' ) lines.append("") return "\n".join(lines) def _make_bar_chart( labels: list[str], series: dict[str, list[float]], title: str = "", colors: list[str] | None = None, width: int = 700, height: int = 300, y_max_cap: float | None = None, ) -> str: """Generate an SVG grouped bar chart. Args: labels: Category labels for x-axis. series: Dict mapping series name to list of values (same length as labels). title: Chart title. colors: Colors for each series. width: SVG width. height: SVG height. y_max_cap: If set, cap the y-axis at this value (e.g. 1.0 for mAP). Returns: SVG string. """ if not labels: return "" default_colors = ["#adb5bd", "#0f3460", "#06d6a0", "#5a7db5"] colors = colors or default_colors ml, mr, mt, mb = 60, 20, 40, 60 cw = width - ml - mr ch = height - mt - mb all_vals = [v for vals in series.values() for v in vals] y_max = max(all_vals) if all_vals else 1 y_max_plot = y_max * 1.15 or 1 if y_max_cap is not None: y_max_plot = min(y_max_plot, y_max_cap) or y_max_cap n_groups = len(labels) n_series = len(series) group_width = cw / n_groups bar_width = group_width * 0.7 / max(n_series, 1) gap = group_width * 0.15 def sy(v): return mt + ch - (v / y_max_plot) * ch lines_svg = [ f'', f'', ] # Grid lines for i in range(6):