报道正文
本文目录37 个章节
10 亿次分类任务
发布于 2025 年 2 月 13 日 在 GitHub 上更新 点赞 46
Derek Thomas derek-thomas 客座作者
你已经优化好了模型,流水线也运行顺畅。但随之而来的是云账单的飙升。每天处理超过 10 亿次的分类或嵌入(embedding)任务,不仅是一个技术挑战,更是一个财务挑战。如何在预算范围内实现这种规模的推理?无论是进行大规模文档分类,还是为检索增强生成(RAG)构建批量嵌入流水线,你都需要具备成本效益且高吞吐量(throughput)的推理能力,而这依赖于精心优化的配置。
这些任务通常使用 编码器模型,其规模远小于现代 LLM,但在超过 10 亿次推理请求的规模下,这仍然是一项非平凡的任务。为了直观理解,这相当于 英文维基百科 内容的 144 倍。我很少看到关于如何兼顾成本来处理此类问题的资料,因此我想解决这个问题。本博客将详细解析如何计算大规模分类和嵌入任务的成本与延迟。我们将分析不同的模型架构,基准测试不同硬件选择的成本,并为你提供一个清晰的框架来优化自己的设置。此外,如果你不想亲自经历整个流程,我们也能帮你建立一些直觉认知。
你可能有几个疑问:
- 解决 10 亿输入量任务的最经济配置是什么?(批量推理)
- 如何在考虑延迟的同时实现这一目标?(重度使用场景)
以下是实现该目标的代码:https://github.com/datavistics/encoder-analysis
tl;dr(太长不看版):我不打算复现整个过程,直接告诉你我的发现;
基于此 定价方案,我实现了以下成本:
| 使用场景 | 分类 | 嵌入 | 视觉-嵌入 |
|---|---|---|---|
| 模型 | lxyuan/distilbert-base-multilingual-cased-sentiments-student | Alibaba-NLP/gte-modernbert-base | vidore/colqwen2-v1.0-merged |
| 数据 | tyqiangz/multilingual-sentiments | sentence-transformers/trivia-qa-triplet | openbmb/RLAIF-V-Dataset |
| 硬件类型 | nvidia-L4 ($0.8/hr) | nvidia-L4 ($0.8/hr) | nvidia-L4 ($0.8/hr) |
| 10 亿次输入的成本 | $253.82 | $409.44 | $44,496.51 |
方法
为了评估成本和延迟,我们需要以下 4 个关键组件:
- 硬件选项:用于比较成本的多种硬件选择
- 部署辅助工具:一种能够按我们设定的配置部署模型的方式
- 负载测试:一种发送请求并测量性能的方式
- 推理服务器:一种在选定硬件上高效运行模型的方式
我将利用 Inference Endpoints 作为我的 硬件选项,因为它允许我从 广泛的 硬件选择中进行挑选。请注意,你可以将其替换为你首选或考虑的 GPU。对于 部署辅助工具,我将使用非常实用的 Hugging Face Hub Library,它允许我通过编程方式轻松部署模型。
对于 推理服务器,我还会使用 Infinity,这是一个用于服务基于编码器模型(以及更多其他类型!)的出色库。我之前已经写过关于 TEI 的文章,TEI 是另一个非常优秀的库。在考虑你的用例时,绝对应该将 TEI 纳入考量,不过本文主要关注方法论而非框架对比。Infinity 具有多项关键优势,例如支持多模态嵌入、适配不同硬件(AMD、Nvidia、CPU 和 Inferentia),以及运行任何包含远程代码且尚未集成到 Hugging Face Transformers 库中的新模型。对我而言,其中最重要的一点是大多数模型默认即兼容。
对于 负载测试,我将使用 Grafana 出品的 k6,这是一款用 Go 语言编写、提供 JavaScript 接口的开源负载测试工具。它易于配置、性能高且开销低。它内置了许多非常实用的执行器。此外,它还预分配虚拟用户(VUs),这比自行搭建测试环境要真实得多。
我将介绍 3 个用例,它们涵盖了各种有趣的要点:
| 用例 | 模型 | 基础架构 | 参数量 | 关注点 |
|---|---|---|---|---|
| 分类(文本) | lxyuan/distilbert-base-multilingual-cased-sentiments-student | DistilBertForSequenceClassification | 1.35 亿 | 蒸馏后的架构小巧快速,非常适合某些场景。 |
| 嵌入 | Alibaba-NLP/gte-modernbert-base | ModernBertModel | 1.49 亿 | 采用 ModernBERT,速度极快。也支持扩展以处理长上下文。 |
| 视觉-嵌入 | vidore/colqwen2-v1.0-merged | ColQwen2 | 22.1 亿 | ColQwen2 能在视觉语言模型(VLMs)的 ColBERT 风格检索中提供独特见解。 |
优化
优化是一个棘手的问题,因为需要考虑的因素很多。从宏观层面来看,我希望遍历重要的负载测试参数,找出在单 GPU 上表现最佳的配置,因为大多数编码器模型都可以适配到单个 GPU 中。一旦我们确定了单 GPU 的成本基准,就可以通过增加 副本 GPU 的数量来横向扩展 GPU 数量和吞吐量。
设置
既然你拥有 代码,请随意根据你的需求调整其中的任何部分:
- GPU
- 部署流程
- 实验框架
- 等等
我不会介意这些修改的。
负载测试参数
虚拟用户数(VUs)和批次大小(Batch Size)非常重要,因为它们影响我们利用 GPU 所有计算资源的能力。足够大的批次大小确保我们充分利用流式多处理器(Streaming Multiprocessors)和显存(VRAM)。在某些场景下,即使还有剩余的显存,带宽成本也会阻碍吞吐量的进一步提升。因此,实验有助于我们发现最佳配置。VUs 允许我们确保充分利用可用的批次大小。
以下是我将主要测试的参数:
-
INFINITY_BATCH_SIZE -
这决定了在一次前向传播中,批次内包含多少文档
-
如果太小,我们将无法充分利用 GPU
-
如果太大,GPU 可能无法处理如此大的输入
-
VUs
[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]
-
This is the number of Virtual Users simulating parallel client requests that is sent to K6
-
It can be hard to simulate a large number of users, and each machine will vary.
-
GPUs
-
I prioritized those with the best performance/cost ratio
-
CPUs
-
I omitted these since Nvidia-T4s are so cheap that CPUs didn’t seem appealing upon light testing. I left some code to test this if a user is interested though!
Depending on your model you might want to consider:
-
Which Docker image you are using. [
'michaelf34/infinity:0.0.75-trt-onnx','michaelf34/infinity:0.0.75'] -
There are a number of Infinity Images that can support different backends. You should consider which ones are most applicable to your hardware/model/configuration.
-
INFINITY_COMPILEwhether or not you want to usetorch.compile()docs -
INFINITY_BETTERTRANSFORMERwhether or not you want torch to use Better Transformer
K6
K6 is great because it allows you to pre-allocate VUs and prevent some insidious bugs. It's quite flexible in how you are sending requests. I decided to use it in a specific way.
When I'm calling a k6 experiment, I mainly want to know what the throughput and average latency is for the requests, and have a few sanity checks for the load testing parameters I have chosen. I also want to do a sweep which means many experiments.
I use the shared-iterations executor (docs) which means K6 shares iterations between the number of VUs. The test ends once k6 executes all iterations. This allows me to have a reasonable time-out, but also put through enough requests to have a decent confidence that I can discriminate between load testing parameters choices in my sweep. In contrast to other executors, this allows me to be confident that I'm simulating the client working as hard as possible per VU which should show me what the cheapest option is.
I use 10_000 requests† and have a max experiment time of 1 min. So if 10_000 requests aren’t finished by 1 minute, then that experiment is over.
export const options = {
scenarios: {
shared_load_test: {
executor: 'shared-iterations',
vus: {{ pre_allocated_vus }},
iterations: 10000,
maxDuration: '1m',
},
},
};Stats
- P95†† and Average Latency
- Throughput
Sanity Checks
- Accuracy (Classification only)
- Test Duration
- Successful Requests
- Format validation
† I use less max requests for the Vision Embeddings given that the throughput is much lower and images are heavy. †† P95 means that 95% of requests complete within this time. It represents the worst-case latency for most users.
Orchestration
You can find the 3 notebooks that put the optimization workflow together here:
The main purpose was to get my experiments defined, launch the correct Inference Endpoint with the right parameters, and launch k6 with the right parameters to test the endpoint.
I made a couple design choices which you may want to think through to see if they work for you:
-
I do an exponential increase of VUs then a binary search to find the best value
-
I don’t treat the results as exactly repeatable
-
If you run the same test multiple times you will get slightly different results
-
I used an improvement threshold of 2% to decide if I should keep searching
Classification
Introduction
Text Classification can have a variety of use-cases at scale, like Email Filtering, Toxicity Detection in pre-training datasets, etc. The OG classic architecture was BERT, and quickly many other architectures came about. Do note that in contrast to popular decoder models, these need to be fine-tuned on your task before using them. Today I think the following architectures† are the most notable:
-
Good task performance, Great Engineering performance
-
It made some architectural changes from OG Bert and is not compatible for classification with TEI
-
Great task performance
-
Very slow engineering performance†† as its unique attention mechanism is hard to optimize
-
Uses Sequence Packing and Flash-Attention-2
-
Great task performance and great engineering performance††
† Do note that for these models, you typically need to fine-tune this on your data to perform well †† I'm using “Engineering performance” to denote anticipated latency/throughput
Experiment
| Category | Values |
|---|---|
| Model | lxyuan/distilbert-base-multilingual-cased-sentiments-student |
| Model Architecture | DistilBERT |
| Data | tyqiangz/multilingual-sentiments (text col) Avg of 100 token (min of 50), multiple languages |
| Hardware | nvidia-L4 ($0.8/hr) nvidia-t4 ($0.5/hr) |
| Infinity Image | trt-onnx vs default |
batch_size | [16, 32, 64, 128, 256, 512, 1024] |
vus | 32+ |
I chose DistilBERT to focus on as it’s a great lightweight choice for many applications. I compared 2 GPUs, nvidia-t4 and nvidia-l4 as well as 2 Infinity Docker Images.
Results
You can see the results in an interactive format here or in the space embedded below in the Analysis section. This is the cheapest configuration across the experiments I ran:
| Category | Best Value |
|---|---|
| Cost of 1B Inputs | $253.82 |
| Hardware Type | nvidia-L4 ($0.8/hr) |
| Infinity Image | default |
batch_size | 64 |
vus | 448 |
Embedding
Introduction
Text Embeddings are a loose way of describing the task of taking a text input and projecting it into a semantic space where close points are similar in meaning and distant ones are dissimilar (example below). This is used heavily in RAG and is an important part of AI search (which some are fans of).

There are a large number of architectures which are compatible, and you can see the most performant ones in the MTEB Leaderboard.
Experiment
ModernBERT is the most exciting encoder release since DeBERTa back in 2020. It has all the ahem modern tricks built into an old and familiar architecture. It makes for an attractive model to experiment with as it's much less explored than other architectures and has a lot more potential. There are a number of improvements in speed and performance, but the most notable for a user is likely the 8k context window. Do check out this blog for a more thorough understanding.
It's important to note that Flash Attention 2 will only work with more modern GPUs due to the compute capability requirement, so I opted to skip the T4 in favor of the L4. An H100 would also work really well here for the heavy hitters category.
| Category | Values |
|---|---|
| Model | Alibaba-NLP/gte-modernbert-base |
| Model Architecture | ModernBERT |
| Data | sentence-transformers/trivia-qa-triplet (positive col) Avg of 144 tokens std dev of 14. |
| Hardware | nvidia-L4 ($0.8/hr) |
| Infinity Image | default |
batch_size | [16, 32, 64, 128, 256, 512, 1024] |
vus | 32+ |
Results
You can see the results in an interactive format here. This is the cheapest configuration across the experiments I ran:
| Category | Best Value |
|---|---|
| Cost of 1B Inputs | $409.44 |
| Hardware Type | nvidia-L4 ($0.8/hr) |
| Infinity Image | default |
batch_size | 32 |
vus | 256 |
Vision Embedding
Introduction
ColQwen2 is a Visual Retriever which is based on the Qwen2-VL-2B-Instruct and uses ColBERT style multi-vector representations of both text and images. We can see that it has a complex architecture compared to the encoders we explored above.
There are a number of use-cases which might benefit from this at large scale like, e-commerce search, multi-modal recommendations, enterprise multi-modal RAG, etc
ColBERT style is different than our previous embedding use-case since it breaks the input into multiple tokens and returns a vector for each instead of 1 vector for the input. You can find an excellent tutorial from Jina AI here.This can lead to superior semantic encoding and better retrieval, but is also slower, and more expensive.
I'm excited for this experiment as it explores 2 lesser known concepts, vision embeddings and ColBERT style embeddings†. There are a few things to note about ColQwen2/VLMs:
-
2B is ~15x bigger than the other models we looked at in this blog
-
ColQwen2 has a complex architecture with multiple models including a decoder which is slower than an encoder
-
Images can easily consume a lot of tokens
-
API Costs:
-
Sending images over an API is slower than sending text.
-
You will further encounter larger egress costs if you are on a cloud
†Do check out this more detailed blog if this is new and interesting to you.
Experiment
I wanted to try a small and modern GPU like the nvidia-l4 since it should be able to fit the 2B param model but also scale well since it's cheap. Like the other embedding model, I'm varying batch_size and vus.
| Category | Values |
|---|---|
| Model | vidore/colqwen2-v1.0-merged |
| Model Architecture | ColQwen2 |
| Data | openbmb/RLAIF-V-Dataset (image col) Most images are ~600x400 at 4MB |
| Hardware | nvidia-L4 ($0.8/hr) |
| Infinity Image | default |
batch_size | [1, 2, 4, 8, 16] |
vus | 1+ |
Results
You can see the results in an interactive format here. This is the cheapest configuration across the experiments I ran:
| Category | Best Value |
|---|---|
| Cost of 1B Inputs | $44,496.51 |
| Hardware Type | nvidia-l4 |
| Infinity Image | default |
batch_size | 4 |
vus | 4 |
Analysis
Do check out the detailed analysis in this space (derek-thomas/classification-analysis) for the classification use-case (hide side-bar and scroll down for the charts):
Conclusion
Scaling to 1B+ classifications or embeddings per day is a non-trivial challenge, but with the right optimizations, it can be made cost-effective. From my experiments, a few key patterns emerged:
- Hardware Matters – NVIDIA L4 ($0.80/hr) consistently provided the best balance of performance and cost, making it the preferred choice over T4 for modern workloads. CPUs were not competitive at scale.
- Batch Size is Critical – The sweet spot for batch size varies by task, but in general, maximizing batch size without hitting GPU memory and bandwidth limits is the key to efficiency. For classification, batch size 64 was optimal; for embeddings, it was 32.
- Parallelism is Key – Finding the right number of Virtual Users (VUs) ensures GPUs are fully utilized. An exponential increase + binary search approach helped converge on the best VU settings efficiently.
- ColBERT style Vision Embeddings are Expensive – At over $44,000 per 1B embeddings, image-based retrieval is 2 orders of magnitude costlier than text-based tasks.
Your data, hardware, models, etc might differ, but I hope you find some use in the approach and code provided. The best way to get an estimate is to run this on your own task with your own configurations. Let's get exploring!
Special thanks to andrewrreed/auto-bench for some inspiration, Michael Feil for creating Infinity. Also thanks to Pedro Cuenca, Erik Kaunismaki, and Tom Aarsen for helping me review.
References
- https://towardsdatascience.com/exploring-the-power-of-embeddings-in-machine-learning-18a601238d6b
- https://yellow-apartment-148.notion.site/AI-Search-The-Bitter-er-Lesson-44c11acd27294f4495c3de778cd09c8d
- https://jina.ai/news/what-is-colbert-and-late-interaction-and-why-they-matter-in-search/
Appendix
Sanity Checks
It's important to scale sanity checks as your complexity scales. Since we are using subprocess and jinja to then call k6 I felt far from the actual testing so I put a few checks in place.
Task Performance
The goal of task performance is that for a specific configuration we are performing similarly to what we expect. Task Performance will have different meanings across tasks. For classification I chose accuracy, and for embeddings I skipped it. We could look at average similarity and other similar metrics. It gets a bit more complex with ColBERT style since we are getting many vectors per request.
Even though 58% isn't bad for some 3 class classification tasks, it's irrelevant. The goal is to make sure that we are getting the expected task performance. If we see a significant change (increase or decrease) we should be suspicious and try to understand why.
Below is a great example from the classification use-case since we can see an extremely tight distribution and one outlier. Upon further investigation the outlier is due to a low amount of requests sent. 
You can see the interactive results visualized by nbviewer here:
Failed Requests Check
We should expect to see no failed requests as Inference Endpoints has a queue to handle extra requests. This is relevant for all 3 use-cases: Classification, Embedding, and Vision Embedding.
sum(df.total_requests - df.successful_requests) allows us to see if we had any failed requests.
Monotonic Series - Did we try enough VUs?
As described above we are using a nice strategy of using exponential increases and then a binary search to find the best number of VUs. But how do we know that we tried enough VUs? What if we tried a higher amount of VUs and throughput kept increasing? If that's the case then we would see a monotonically increasing relationship between VUs and Throughput and we would need to run more tests.
You can see the interactive results visualized by nbviewer here:
Embedding Size Check
When we request an embedding it makes sense that we would always get back an embedding of the same size as specified by the model type. You can see the checks here:
- Embedding
- Vision Embedding (inner embedding)
ColBERT Embedding Count
We are using a ColBERT style model for Vision Embedding which means we should be getting multiple vectors per image. It's interesting to see the distribution of these as it allows us to check for anything unexpected and to get to know our data. To do so I stored the min_num_vectors, avg_num_vectors, max_num_vectors, in the experiments.
We should expect to see some variance in all 3, but it’s ok that min_num_vectors and max_num_vectors have the same value across experiments.
You can see the check here:
Cost Analysis
Here is a short description, but you can get a more detailed interactive experience in the space: derek-thomas/classification-analysis
Best Image by Cost Savings
For the classification use-case we looked at 2 different Infinity Images, default and trt-onnx. Which one was better? It's best if we can compare these across the same settings (GPU, batch_size, VUs). We can simply group our results by those settings and then see which one was cheaper.
Cost vs Latency
This is a key chart as for many use-cases there is a maximum latency that a user can experience. Usually if we allow the latency to increase we can increase throughput creating a trade-off scenario. That's true in all the use-cases I've looked at here. Having a pareto curve is great to help visualize where that tradeoff is.

Cost vs VUs and Batch Size Contour Plots
Lastly it's important to build intuition on what is happening when we try these different settings. Do we get beautiful idealized charts? Do we see unexpected gradients? Do we need more exploration in a region? Could we have issues in our setup like not having an isolated environment? All of these are good questions and some can be tricky to answer.
The contour plot is built by interpolating intermediate points in a space defined by the 3 dimensions. There are a couple phenomena that are worth understanding:
- Color Gradient: Shows the cost levels, with darker colors representing higher costs and lighter colors representing lower costs.
- Contour Lines: Represent cost levels, helping identify cost-effective regions.
- Tight clusters: (of contour lines) indicate costs changing rapidly with small adjustments to batch size or VUs.
We can see a complex contour chart with some interesting results from the classification use-case:
But here is a much cleaner one from the vision-embedding task:
Infinity Client
For actual usage, do consider using the infinity client. When we are benchmarking it's good practice to use k6 to know what’s possible. For actual usage, use the official lib, or something close for a few benefits:
- Base64 means smaller payloads (faster and cheaper)
- The maintained library should make development cleaner and easier
- You have inherent compatibility which will make development faster
You also have OpenAI lib compatibility with the Infinity backend as another option.
As an example vision-embeddings can be accessed like this:
pip install infinity_client && python -c "from infinity_client.vision_client import InfinityVisionAPI" Other Lessons Learned
- I tried deploying multiple models on the same GPU but didn’t see major improvements despite having leftover VRAM and GPU processing power left, this is likely due to the bandwidth cost of processing a large batch
- Getting K6 to work with images was a headache until I learned about SharedArrays
- Image Data can be super cumbersome to work with
- The key to debugging K6 when you are generating scripts is to manually run K6 and look at the output.
Future Improvements
- Have the tests run in parallel while managing a global max of
VUswould save a lot of time - Look at more diverse datasets and see how that impacts the numbers



