Framing model selection as a constrained optimization
Picking an LLM is not a beauty contest among model cards. It is a constrained optimization on three axes that you measure on the same evaluation set:
- a quality vector
- a cost vector
- a latency vector
The quality vector is a tuple of judge scores (correctness, faithfulness, relevance, plus any custom scorer the use case demands). The cost vector is input tokens times input rate plus output tokens times output rate, summed across the trace. The latency vector is P50, P95, and P99 of the end-to-end span as recorded by MLflow Tracing.
You commit to a quality floor first (for example, faithfulness greater than 0.85 on a 200-row evaluation set), then minimize cost subject to the latency budget, then break ties on operational fit (provisioned throughput available, region, governance posture).
How it works
The Mosaic AI Agent Framework reports all three vectors in one MLflow run. When you call mlflow.genai.evaluate(data=eval_set, predict_fn=agent.predict, scorers=[Correctness(), Faithfulness(), RelevanceToQuery(), my_custom_scorer]) against the same prompt, retriever, and tools but a different endpoint parameter on the underlying model serving call, MLflow logs one run per model, and the model comparison view in the MLflow UI lays the runs side by side. That side-by-side view is the artifact you treat as your decision document. A scorecard that compares a small open model, a medium open model, and a frontier proprietary model on the same evaluation set against the same chain is the deliverable, not three separate notebooks that each report one model in isolation.
Size axis: small, medium, frontier
Comparison
Small open models in the Foundation Model APIs catalog cover the 7B to 13B parameter range and are addressed by pay-per-token endpoints with low input and output rates. They land tool calls reliably on flat tool schemas, summarize short documents acceptably, and serve classification tasks well. They miss on multi-step reasoning, long context recall past roughly 32K tokens, and code synthesis above the line-completion level. Pick a small model when the quality vector tolerates a five-point drop versus the frontier and the latency floor is below 500 ms at P95.
Medium open models (Llama 3 70B, DBRX, Mixtral 8x22B) close most of the gap on summarization, classification, and standard RAG generation while remaining cheaper than frontier proprietary models. They are the default choice when faithfulness on RAG questions is the dominant judge and the application can tolerate 1 to 3 seconds of P95 latency. They are also the only practical choice when the workspace is restricted from sending traffic to external providers, because they are available through Foundation Model APIs in-region.
Frontier proprietary models (Anthropic Claude, OpenAI GPT, Google Gemini through the External Models gateway) lead on multi-step reasoning, long-context recall above 100K tokens, and tool-calling reliability on deep nested schemas. They cost an order of magnitude more per token than the small models, and their P95 latency is higher than well-tuned provisioned-throughput open models. Pick a frontier model when the agent shape requires more than three tool calls per turn and the correctness floor is above 0.92.
Architecture axis: dense, mixture of experts, encoder-decoder
Dense decoder-only architectures (Llama 3 8B/70B, GPT-4o) activate every parameter on every token and deliver predictable latency that scales linearly with output length. They are the default architectural pick for generation, chat, and tool calling.
Mixture-of-experts decoder-only architectures (Mixtral 8x7B, Mixtral 8x22B, DBRX) activate a fraction of parameters per token, so throughput per dollar is high and latency at the same active-parameter count is lower than a dense model of the same total size. They show variance in tail latency because router decisions can spike active-expert load, which is why P99 is the metric to watch when validating an MoE pick rather than P50.
Encoder-only and encoder-decoder architectures (BGE for embeddings, FLAN-T5 for sequence-to-sequence) are not the answer for chat or agents.
They are the answer for embedding generation, classification, and re-ranking.
The Mosaic AI Vector Search managed embedding endpoints (databricks-gte-large-en, databricks-bge-large-en) are encoder-only, and a cross-encoder re-ranker as introduced in Chapter 2 is a fine-tuned encoder.
Conflating the two architecture families on the model selection table is a common exam distractor.
Use Databricks custom Scorers for evaluating agents and LLMs
The built-in judges in Mosaic AI Agent Evaluation (Correctness, Faithfulness, RelevanceToQuery, ChunkRelevance, Safety, Guidelines) cover the high-frequency dimensions, but no built-in judge covers a domain-specific rule such as "the response must cite the policy number in brackets" or "the response must include a USD value formatted as $X,XXX.XX".
For these, Databricks exposes the @scorer decorator in mlflow.genai.scorers, which lets you author either a deterministic code-based scorer or a judge-prompted scorer that calls an LLM.
- A code-based custom Scorer is a Python function that accepts the trace inputs, outputs, and expectations and returns a
Feedbackobject. - Use this shape when the rule is mechanical.
- A judge-based custom Scorer wraps a prompt around an LLM call and returns a
Feedbackobject with a pass or fail value plus a rationale. - Use this shape when the rule requires linguistic judgment that a regex cannot capture.
- Both shapes plug into the same
mlflow.genai.evaluate(... scorers=[...])parameter as the built-in judges and appear as columns in the evaluation results dataset.
from mlflow.genai.scorers import scorer
from mlflow.entities import Feedback
import re
@scorer
def cites_policy_number(outputs: str) -> Feedback:
"""Pass if the model response includes a bracketed policy number like [POL-12345]."""
pattern = r"\[POL-\d{5}\]"
if re.search(pattern, outputs):
return Feedback(value="yes", rationale="Policy citation present.")
return Feedback(value="no", rationale="No bracketed policy number found.")
@scorer
def usd_amount_formatted(outputs: str) -> Feedback:
"""Pass if every dollar amount uses the $X,XXX.XX format."""
amounts = re.findall(r"\$[\d,]+(?:\.\d+)?", outputs)
bad = [a for a in amounts if not re.fullmatch(r"\$\d{1,3}(?:,\d{3})*\.\d{2}", a)]
if not amounts:
return Feedback(value="n/a", rationale="No amounts in response.")
if bad:
return Feedback(value="no", rationale=f"Malformed amounts: {bad}")
return Feedback(value="yes", rationale="All amounts correctly formatted.")
A judge-prompted Scorer follows the same decorator but calls a model. The recommended pattern is to call a small fast model for the judgment so the evaluation run does not multiply costs.
from mlflow.genai.scorers import scorer
from mlflow.entities import Feedback
from databricks.sdk import WorkspaceClient
client = WorkspaceClient().serving_endpoints
@scorer
def tone_is_professional(inputs: dict, outputs: str) -> Feedback:
prompt = (
"You are a tone reviewer. Reply with exactly 'yes' or 'no'.\n"
f"Did the assistant reply in a professional, neutral tone?\n"
f"User: {inputs.get('query', '')}\nAssistant: {outputs}"
)
resp = client.query(
name="databricks-meta-llama-3-3-70b-instruct",
messages=[{"role": "user", "content": prompt}],
max_tokens=4,
)
verdict = resp.choices[0].message.content.strip().lower()
return Feedback(
value="yes" if verdict.startswith("yes") else "no",
rationale=f"Judge said: {verdict}",
)
A worked model selection run
The standard run shape compares three candidates against the same chain. The output is a single MLflow comparison view with per-judge averages, latency percentiles, and total cost.
import mlflow
import pandas as pd
from mlflow.genai.scorers import Correctness, Faithfulness, RelevanceToQuery
eval_set = pd.read_csv("/Volumes/main/eval/genai_eval_set_v3.csv")
candidates = [
("llama-3-1-8b", "databricks-meta-llama-3-1-8b-instruct"),
("llama-3-3-70b", "databricks-meta-llama-3-3-70b-instruct"),
("claude-sonnet-4-5", "databricks-claude-sonnet-4-5"),
]
mlflow.set_experiment("/Shared/genai/model_selection")
for run_name, endpoint in candidates:
with mlflow.start_run(run_name=run_name):
mlflow.log_param("endpoint", endpoint)
agent.set_llm_endpoint(endpoint)
mlflow.genai.evaluate(
data=eval_set,
predict_fn=agent.predict,
scorers=[
Correctness(),
Faithfulness(),
RelevanceToQuery(),
cites_policy_number,
usd_amount_formatted,
tone_is_professional,
],
)
Decision Anchor: which size, which architecture
Choose a small open model (7B-13B) when the dominant task is classification, slot extraction, summarization of short documents under 4K tokens, or a single tool call per turn, and when P95 latency must stay below 500 ms.
Choose a medium open model (70B class, dense or MoE) when the dominant task is RAG generation, multi-turn chat, or two-to-three tool calls per turn, when faithfulness above 0.85 is the quality floor, and when in-workspace data residency is required.
Choose a frontier proprietary model when reasoning chains run past three tool calls, when long-context recall above 100K tokens is required, or when correctness above 0.92 is the quality floor and the cost premium is acceptable.
💡 Exam Trap: Comparing models on raw accuracy without normalizing for cost and latency is the most common scoring mistake. The selection table must show all three axes against the same evaluation set. A model that wins on correctness by two points but quadruples the cost per request is not the winner unless the quality floor explicitly required it.
💡 Exam Trap: Custom Scorers return a
Feedbackobject with avalueand arationale. Returning a bare float, a boolean, or a string from a@scorerfunction works at evaluation time but does not surface the rationale in the MLflow UI, and is wrong on the exam.
⚠️ Anti-Pattern: Picking the model first and then writing an evaluation set that the chosen model passes. Author the evaluation set against the input-output contract from Chapter 1 first, freeze it, then run all candidates against the frozen set. The evaluation set is the ground truth, not the model.
🎯 Scenario: A claims-summarization agent must produce a 200-word summary of an insurance claim that cites the policy number in brackets. The PM proposes Llama 3.1 8B because it is the cheapest. You run
mlflow.genai.evaluatewithCorrectness,Faithfulness, and the customcites_policy_numberscorer on a 150-row evaluation set against the 8B, 70B, and Claude Sonnet endpoints. The 8B reaches 0.94 on correctness and faithfulness but only 0.42 on policy citation. The 70B reaches 0.96 on quality judges and 0.91 on policy citation at four times the cost per request. You pick the 70B because the citation rule is a hard requirement of the contract, then you tune the system prompt against the 8B in parallel to see if you can lift its citation rate enough to revisit the decision.
📊 Limit: Foundation Model APIs pay-per-token endpoints have published per-workspace rate limits that vary by model class. Provisioned throughput endpoints have configurable token-per-second throughput in increments documented per model. Both numbers are listed on the Model Serving page of the workspace and on the Foundation Model APIs documentation page.
