cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Generative AI
Explore discussions on generative artificial intelligence techniques and applications within the Databricks Community. Share ideas, challenges, and breakthroughs in this cutting-edge field.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

ai-query Execution

IM_01
Valued Contributor

Hi,

I see that ai-query supports parallelization. Is it executed in parallel across each partition of the dataframe.
could any one explain how it supports optimized batch inference

5 REPLIES 5

sundar-sg
New Contributor II
Hi @IM_01,

ai_query is built for batch inference, but the docs do not say that it runs one call per DataFrame partition, and they do not describe the internal batching. They say the platform manages it. The AI Functions page says: "AI Functions automatically manage parallelization, retries, and scaling. It is advised to submit your full dataset in a single query rather than manually splitting it into small batches."

The same page says "your query runs on the compute you submit it from, such as a SQL warehouse, notebook, cluster, or pipeline", and that "the model inference may run on separate Databricks-managed infrastructure". So the docs do not link the number of partitions to the number of parallel model calls, and I would not tune partitions for this.

For optimised batch inference, the best practices on the "Use ai_query" page are:
1) Use Databricks-hosted system.ai model services, not provisioned throughput endpoints.
2) Pick a model from the batch-optimised list on that page. A non-optimised model "can result in reduced throughput and longer job completion times."
3) Submit your full dataset in a single query. "Manually splitting data into small batches can reduce throughput."
4) Set failOnError to false for large workloads, so failed rows return an error message and you keep the successful results.

[https://docs.databricks.com/aws/en/large-language-models/ai-query]
To see what happened in a run, open the query profile in the SQL editor and click AI Query. It shows the completed and failed inferences and the total time.

Yougasundar
Contributor
Hi @IM_01,

ai_query is built for batch inference, but the docs do not say that it runs one call per DataFrame partition, and they do not describe the internal batching. They say the platform manages it. The AI Functions page says: "AI Functions automatically manage parallelization, retries, and scaling. It is advised to submit your full dataset in a single query rather than manually splitting it into small batches."

The same page says "your query runs on the compute you submit it from, such as a SQL warehouse, notebook, cluster, or pipeline", and that "the model inference may run on separate Databricks-managed infrastructure". So the docs do not link the number of partitions to the number of parallel model calls, and I would not tune partitions for this.

For optimised batch inference, the best practices on the "Use ai_query" page are:
1) Use Databricks-hosted system.ai model services, not provisioned throughput endpoints.
2) Pick a model from the batch-optimised list on that page. A non-optimised model "can result in reduced throughput and longer job completion times."
3) Submit your full dataset in a single query. "Manually splitting data into small batches can reduce throughput."
4) Set failOnError to false for large workloads, so failed rows return an error message and you keep the successful results.

[https://docs.databricks.com/aws/en/large-language-models/ai-query]
To see what happened in a run, open the query profile in the SQL editor and click AI Query. It shows the completed and failed inferences and the total time.

Valeria_Koz_DBX
Databricks Employee
Databricks Employee

Hi @IM_01 ,

Short answer: yes, ai_query works in parallel, but partitions aren't really the lever. Parallelism happens at two levels, and Databricks manages the important one for you.

1. Spark side (your DataFrame)
ai_query is evaluated like any other Spark SQL expression, so rows are processed by Spark tasks, and partitions are processed in parallel across the cluster's cores. In most cases Spark sizes the partitions adaptively, so you don't need to tune anything.

2. Model-serving side (where the optimised batch inference happens)
This is usually the real bottleneck, and AI Functions "automatically handle paralleliation, retries, and scaling" for it. With a batch-optimised Databricks-hosted model, the batch backend scales capacity up for your query automatically. You don't provision or configure endpoint compute.

Should I repartition?
Usually no. The docs advise submitting your full dataset in a single query and warn that "manually splitting data into small batches can reduce throughput." The exception is input that is clearly under-partitioned, such as a small CSV read into one or two partitions on classic compute with idle cores. There, a modest repartition(n) with n roughly equal to the available cores can help. Benchmark it: too many partitions gives diminishing returns, and repartitioning doesn't change cost.

How to get the optimised batch path:First, make sure:

  • Run on DBR 15.4 LTS+ (18.2+ recommended, and note the announced move to 17.3 LTS as the minimum). Not available on Classic SQL warehouses.

Then follow the steps that were mentioned in the previous comments:

  1. Use a system.ai (Databricks-hosted) model from the batch-optimised list, not a provisioned-throughput or custom endpoint.
  2.  Send the whole dataset in one query
    CREATE OR REPLACE TABLE results AS
    SELECT id, ai_query('databricks-โ€ฆ', prompt, failOnError => false) AS ai
    FROM source;โ€‹
    Use one ai_query session per model rather than several running side by side. Persist the results to a table instead of re-running inference in later queries.
  3. Set failOnError => false for large workloads. You get a STRUCT with response and errorMessage, so failed rows don't fail the job.
  4. Monitor progress in the query profile.

Docs: 

Good luck

IM_01
Valued Contributor

Hi @Valeria_Koz_DBX 

could u please elaborate on second level i.e; model serving side

Valeria_Koz_DBX
Databricks Employee
Databricks Employee

Sure, happy to. I hope this gives a bit more details and makes it a bit clearer 

The second level is about where the model inference itself runs, separately from the Spark compute that runs your query.

  1. Two layers, billed separately

Your cluster, serverless compute or Pro/Serverless SQL warehouse runs the query (AI Functions aren't available on Classic SQL warehouses). It reads the rows, builds the prompts and writes the results. Each ai_query call goes to Model Serving, which runs the LLM inference. For Databricks-hosted models you don't create or size an endpoint. The docs describe them as "provisionless endpoints [that] are fully managed and work best for batch processing."

So you see cost in two places: the compute running the query, and the inference. Per the AI Functions docs, batch inference is recorded in system.billing.usage as MODEL_SERVING with offering type BATCH_INFERENCE:

SELECT usage_date, sku_name, SUM(usage_quantity) AS dbus

FROM system.billing.usage

WHERE billing_origin_product = 'MODEL_SERVING'

  AND product_features.model_serving.offering_type = 'BATCH_INFERENCE'

GROUP BY ALL

ORDER BY usage_date DESC;
  1. What "managed scaling" means for you

According the documentation "AI Functions automatically handle parallelisation, retries, and scaling."
In practice: 

  • It sends the full dataset in one query. Manually splitting it into small batches can reduce throughput.
  • Retries are handled for you. With failOnError => false, each row returns a struct with response and errorMessage. Rows that fail on a model endpoint error get a null response plus the error, instead of failing the whole job, so you can re-run just those rows later. Other kinds of errors still fail the query.
  • The docs describe no tuning settings (concurrency, replicas and so on) for this path. They also note that "performance may not scale linearly from very small workloads to large-scale workloads", so benchmark on a realistic sample, not a few rows.
  1. Which endpoint you call matters
  • Databricks-hosted models optimized for batch: recommended. "Databricks optimizes specific models for high-throughput batch workloads." The list is on the ai_query page (for example system.ai.gpt-5-2, system.ai.gemini-3-1-pro). Other hosted models work but may give lower throughput and longer runs.
  • Provisioned throughput endpoints: ai_query can call them, but "AI Functions does not use the compute provisioned to the endpoint" and "fully manages the scaling used for batch inference". So sizing up a provisioned endpoint won't speed up batch ai_query, and the docs recommend Databricks-hosted models instead.
  • Rate limits: the published pay-per-token limits (input/output tokens per minute, requests per hour) apply to pay-per-token endpoints. The docs don't say how they apply to batch AI Functions, so don't size a batch job from those numbers.
  • Custom model endpoints: ai_query supports them, and they're billed as their own serving endpoint.

Back to the practical steps 

  1. Practical checklist
  • Pick a model from the batch-optimized list.
  • Save the results once with CREATE OR REPLACE TABLE ... AS SELECT ai_query(...), then query that table.
  • Set failOnError => false.
  • Watch progress in the query profile, and cost in system.billing.usage.

Docs: AI Functions ยท ai_query ยท ai_query function reference ยท Foundation Model API limits