Skip to main content

06 - Multi-agent + LLM: hybrid systems with CrewAI/AutoGen

Modern multi-agent with LLMs replacing symbolic reasoning: CrewAI, AutoGen, LangGraph. Role-based patterns and orchestration.

What do you think about this article?

At a Glance

Modern multi-agent with LLMs replacing symbolic reasoning: CrewAI, AutoGen, LangGraph. Role-based patterns and orchestration.

This article is part of the Multi-Agent Systems series in Federico Calò's UniAppunti portfolio, reworked from university notes and personal study material. See series index.

Multi-agent + LLM hybrid systems are the dominant 2024-2026 pattern for complex tasks: CrewAI (role-based), AutoGen (Microsoft conversation-based), LangGraph (stateful workflow). We build a real multi-agent system for software engineering automation: planner + coder + reviewer + tester, each LLM-backed with specific tools. Compare with classical CNP/BDI multi-agent.

Theoretical foundations and reference papers

LLM agents reincarnate BDI: prompt history = beliefs, system prompt = desires, tool calls = intentions. Multi-agent LLM: communication via natural language, role specialisation, emergent coordination. Reference: Wu et al. AutoGen (arxiv:2308.08155), CrewAI documentation, Park et al. Generative Agents: Interactive Simulacra of Human Behavior (UIST 2023 arxiv:2304.03442).

Pattern: sequential (planner→coder→reviewer→tester), parallel (3 independent reviewers), hierarchical (manager-worker), conversational (back-and-forth refinement). Trade-off: coordination overhead vs single-agent. Cost: 4-10x LLM calls.

Outline

  1. CrewAI: role-based pattern
  2. AutoGen: conversation pattern
  3. LangGraph: stateful workflow
  4. Software engineering automation
  5. Evaluation: SWE-Bench, HumanEval+
  6. Safety, sandbox, observability

CrewAI: role-based pattern

CrewAI defines Crew of Agents, each with role + goal + backstory + tools. Tasks assigned to agents, execute sequentially or hierarchically. Inter-agent: auto delegation if allow_delegation=True. Reference: crewai.com docs.

from crewai import Agent, Task, Crew
planner = Agent(role='Planner', goal='Design solution', tools=[...])
coder = Agent(role='Coder', goal='Implement', tools=[code_tool])
tester = Agent(role='Tester', goal='Verify', tools=[run_tests])

tasks = [
    Task(description='Design X', agent=planner),
    Task(description='Code Y', agent=coder),
    Task(description='Test Z', agent=tester)]
Crew(agents=[planner, coder, tester], tasks=tasks).kickoff()

Mathematical formalisation. We define the problem as empirical risk minimisation R(θ) = (1/n) Σ L(f_θ(x_i), y_i), where L is the appropriate loss (cross-entropy for classification, MSE for regression, KL divergence for density matching). The Adam optimiser (Kingma-Ba 2014 arxiv:1412.6980) applies updates θ_t+1 = θ_t − η m̂_t / (√v̂_t + ε) with first- and second-order bias-corrected moments. AdamW (Loshchilov-Hutter 2017 arxiv:1711.05101) decouples weight decay, improving generalisation by 1-2pp on ImageNet.

Step-by-step algorithm. (1) Initialisation: He init for ReLU (He et al. 2015 arxiv:1502.01852), Xavier for tanh (Glorot-Bengio 2010). (2) Forward pass: propagate inputs through layers, caching intermediate activations for the subsequent backward. (3) Loss computation: apply softmax+CE in log-stable mode (logsumexp trick). (4) Backward: compute gradients via autograd or manual backprop; clip-norm to 1.0 for stability (Pascanu et al. 2013). (5) Optimizer step: update weights with Adam/AdamW; learning rate scheduler cosine decay (Loshchilov 2016) or linear warmup + decay (typical 1k step warmup). (6) Validation: every N steps, snapshot the best checkpoint by validation metric.

Complexity analysis and cost profile. GPU memory profile: activations dominate in training (10-20x weights), KV cache dominates inference (proportional to batch · seq_len). FlashAttention-2 (Dao 2023 arxiv:2307.08691) reduces memory from O(n^2) to O(n) via SRAM tiling. Compute cost: training a 7B model requires about 1.4e22 FLOPs (Chinchilla scaling law, Hoffmann et al. 2022 arxiv:2203.15556), i.e. ~8 weeks on 64 A100 GPUs at 312 TFLOPs. As a practical heuristic, a Bayesian hyperparameter tuning run (Optuna or Ax) typically needs 30-100 trials × 2-6 hours each, totalling 100-500 GPU-hours for a competitive model on a medium problem. Memory budget must be estimated before training: rule of thumb is GPU memory = 16 × params for fp32 Adam training, dropping to 4 × params with fp16 mixed precision + activation checkpointing (Chen et al. 2016 arxiv:1604.06174).

Known limits and ablation studies. Known limit: distribution shift between train and production; Quinonero-Candela et al. Dataset Shift in Machine Learning (MIT Press 2009) taxonomises covariate, label and concept shift. Known limit: catastrophic forgetting in sequential fine-tuning; Kirkpatrick et al. 2017 (EWC, arxiv:1612.00796) proposes Fisher regularisation to mitigate. A third limit emerges in the Recht et al. ICML 2019 benchmark (arxiv:1902.10811): SOTA CIFAR-10 models lose 5-10pp accuracy on CIFAR-10.1 (an independent replica), indicating benchmark overfitting. Mitigation: use independent test sets generated post-training, avoid tuning hyperparameters on test, apply Bonferroni correction when comparing many models.

Recent SOTA-pushing paper. Vaswani et al. 2017 Attention Is All You Need (arxiv:1706.03762), Jiang et al. 2024 Mixtral 8x7B (arxiv:2401.04088), Brown et al. 2020 GPT-3 (arxiv:2005.14165). In particular, 2024-2025 works moved the frontier: Mixtral 8x22B (Jiang et al. 2024) beats GPT-3.5-turbo on MMLU (77.8 vs 70.0) using 39B active params over 141B total (Mixture of Experts top-2 routing). DeepSeek-V3 (DeepSeek-AI Dec 2024 arxiv:2412.19437) reaches 88.5 MMLU with MLA attention and Multi-Token Prediction loss, training cost USD 5.5M (10x cheaper than GPT-4). Claude 3.5 Sonnet (Anthropic Jun 2024) beats GPT-4o on HumanEval (92.0 vs 90.2) and becomes the reference model for agentic coding. Llama 3.3 70B (Meta Dec 2024) matches 405B using half the parameters thanks to iterative Knowledge Distillation.

Industry impact. Fortune 500 companies spend on average USD 4.2M/year on LLM APIs (Stanford HAI State of AI Report 2025); 38% are migrating to self-hosted open-weights models by 2026. For a principal-level portfolio engineer: tracking cost per 1k inferences, sustainable throughput and p99 SLO is mandatory. Standard tooling: Prometheus + Grafana for infra metrics, Langfuse or Helicone for LLM-specific observability, OpenTelemetry for distributed tracing. Typical cost optimisation: semantic cache (gptcache, Redis with embedding similarity) cuts 30-40% of calls; speculative decoding (Leviathan 2023 arxiv:2211.17192) doubles throughput at the same quality.

AutoGen: conversation pattern

AutoGen (Microsoft Research 2024 arxiv:2308.08155): GroupChat of multiple agents, manager selects next speaker. Pattern: UserProxyAgent (human-in-loop) + AssistantAgent (LLM) + Code Executor. Code execution sandboxed in Docker.

from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager
planner = AssistantAgent('Planner', llm_config={'model':'gpt-4o'})
coder = AssistantAgent('Coder', llm_config={'model':'gpt-4o'})
user = UserProxyAgent('User', code_execution_config={'use_docker':True})
gc = GroupChat([planner, coder, user], messages=[], max_round=20)
mgr = GroupChatManager(gc, llm_config={'model':'gpt-4o'})
user.initiate_chat(mgr, message='Build a flask app')

Mathematical formalisation. We define the problem as empirical risk minimisation R(θ) = (1/n) Σ L(f_θ(x_i), y_i), where L is the appropriate loss (cross-entropy for classification, MSE for regression, KL divergence for density matching). The Adam optimiser (Kingma-Ba 2014 arxiv:1412.6980) applies updates θ_t+1 = θ_t − η m̂_t / (√v̂_t + ε) with first- and second-order bias-corrected moments. AdamW (Loshchilov-Hutter 2017 arxiv:1711.05101) decouples weight decay, improving generalisation by 1-2pp on ImageNet.

Step-by-step algorithm. (1) Initialisation: He init for ReLU (He et al. 2015 arxiv:1502.01852), Xavier for tanh (Glorot-Bengio 2010). (2) Forward pass: propagate inputs through layers, caching intermediate activations for the subsequent backward. (3) Loss computation: apply softmax+CE in log-stable mode (logsumexp trick). (4) Backward: compute gradients via autograd or manual backprop; clip-norm to 1.0 for stability (Pascanu et al. 2013). (5) Optimizer step: update weights with Adam/AdamW; learning rate scheduler cosine decay (Loshchilov 2016) or linear warmup + decay (typical 1k step warmup). (6) Validation: every N steps, snapshot the best checkpoint by validation metric.

Complexity analysis and cost profile. Asymptotic complexity: forward pass O(n · d^2) per dense layer, O(n^2 · d) for quadratic attention; typical memory O(n · d) with activation checkpointing. GPU memory profile: activations dominate in training (10-20x weights), KV cache dominates inference (proportional to batch · seq_len). FlashAttention-2 (Dao 2023 arxiv:2307.08691) reduces memory from O(n^2) to O(n) via SRAM tiling. As a practical heuristic, a Bayesian hyperparameter tuning run (Optuna or Ax) typically needs 30-100 trials × 2-6 hours each, totalling 100-500 GPU-hours for a competitive model on a medium problem. Memory budget must be estimated before training: rule of thumb is GPU memory = 16 × params for fp32 Adam training, dropping to 4 × params with fp16 mixed precision + activation checkpointing (Chen et al. 2016 arxiv:1604.06174).

Known limits and ablation studies. Known limit: mode collapse when loss converges to non-expressive local minima; Goodfellow et al. 2014 ablation shows Inception Score dropping from 8.1 to 3.2 when feature matching is disabled. Known limit: overconfidence in deep nets; Guo et al. ICML 2017 arxiv:1706.04599 reports ECE > 0.10 without temperature scaling. A third limit emerges in the Recht et al. ICML 2019 benchmark (arxiv:1902.10811): SOTA CIFAR-10 models lose 5-10pp accuracy on CIFAR-10.1 (an independent replica), indicating benchmark overfitting. Mitigation: use independent test sets generated post-training, avoid tuning hyperparameters on test, apply Bonferroni correction when comparing many models.

Recent SOTA-pushing paper. Devlin et al. 2018 BERT (arxiv:1810.04805), Yao et al. 2022 ReAct (arxiv:2210.03629), Dao et al. 2022 FlashAttention (arxiv:2205.14135). In particular, 2024-2025 works moved the frontier: Mixtral 8x22B (Jiang et al. 2024) beats GPT-3.5-turbo on MMLU (77.8 vs 70.0) using 39B active params over 141B total (Mixture of Experts top-2 routing). DeepSeek-V3 (DeepSeek-AI Dec 2024 arxiv:2412.19437) reaches 88.5 MMLU with MLA attention and Multi-Token Prediction loss, training cost USD 5.5M (10x cheaper than GPT-4). Claude 3.5 Sonnet (Anthropic Jun 2024) beats GPT-4o on HumanEval (92.0 vs 90.2) and becomes the reference model for agentic coding. Llama 3.3 70B (Meta Dec 2024) matches 405B using half the parameters thanks to iterative Knowledge Distillation.

Industry impact. MLPerf Inference Benchmark (Reddi et al. 2020 arxiv:1911.02549) is the de facto vendor-hardware standard: NVIDIA H100, AMD MI300X, Google TPU v5e, Intel Gaudi 3. For a principal-level portfolio engineer: tracking cost per 1k inferences, sustainable throughput and p99 SLO is mandatory. Standard tooling: Prometheus + Grafana for infra metrics, Langfuse or Helicone for LLM-specific observability, OpenTelemetry for distributed tracing. Typical cost optimisation: semantic cache (gptcache, Redis with embedding similarity) cuts 30-40% of calls; speculative decoding (Leviathan 2023 arxiv:2211.17192) doubles throughput at the same quality.

LangGraph: stateful workflow

LangGraph (LangChain 2024): directed graph of nodes (LLM/tool), conditional edges. Persistent state cross-node. Enables bounded loops, retry, parallel branches. 2026 standard for production agents.

from langgraph.graph import StateGraph, END
from typing import TypedDict
class State(TypedDict):
    plan: str
    code: str
    review: str
g = StateGraph(State)
g.add_node('plan', planner_fn)
g.add_node('code', coder_fn)
g.add_node('review', reviewer_fn)
g.add_edge('plan', 'code')
g.add_edge('code', 'review')
g.add_conditional_edges('review', lambda s: 'code' if 'fix' in s['review'] else END)
g.set_entry_point('plan')
app = g.compile()

Mathematical formalisation. We define the problem as empirical risk minimisation R(θ) = (1/n) Σ L(f_θ(x_i), y_i), where L is the appropriate loss (cross-entropy for classification, MSE for regression, KL divergence for density matching). The Adam optimiser (Kingma-Ba 2014 arxiv:1412.6980) applies updates θ_t+1 = θ_t − η m̂_t / (√v̂_t + ε) with first- and second-order bias-corrected moments. AdamW (Loshchilov-Hutter 2017 arxiv:1711.05101) decouples weight decay, improving generalisation by 1-2pp on ImageNet.

Step-by-step algorithm. (1) Initialisation: He init for ReLU (He et al. 2015 arxiv:1502.01852), Xavier for tanh (Glorot-Bengio 2010). (2) Forward pass: propagate inputs through layers, caching intermediate activations for the subsequent backward. (3) Loss computation: apply softmax+CE in log-stable mode (logsumexp trick). (4) Backward: compute gradients via autograd or manual backprop; clip-norm to 1.0 for stability (Pascanu et al. 2013). (5) Optimizer step: update weights with Adam/AdamW; learning rate scheduler cosine decay (Loshchilov 2016) or linear warmup + decay (typical 1k step warmup). (6) Validation: every N steps, snapshot the best checkpoint by validation metric.

Complexity analysis and cost profile. GPU memory profile: activations dominate in training (10-20x weights), KV cache dominates inference (proportional to batch · seq_len). FlashAttention-2 (Dao 2023 arxiv:2307.08691) reduces memory from O(n^2) to O(n) via SRAM tiling. Production throughput target: 1k req/s per node with vLLM PagedAttention (Kwon et al. SOSP 2023 arxiv:2309.06180), continuous batching and KV cache sharing across requests. As a practical heuristic, a Bayesian hyperparameter tuning run (Optuna or Ax) typically needs 30-100 trials × 2-6 hours each, totalling 100-500 GPU-hours for a competitive model on a medium problem. Memory budget must be estimated before training: rule of thumb is GPU memory = 16 × params for fp32 Adam training, dropping to 4 × params with fp16 mixed precision + activation checkpointing (Chen et al. 2016 arxiv:1604.06174).

Known limits and ablation studies. Known limit: catastrophic forgetting in sequential fine-tuning; Kirkpatrick et al. 2017 (EWC, arxiv:1612.00796) proposes Fisher regularisation to mitigate. Known limit: mode collapse when loss converges to non-expressive local minima; Goodfellow et al. 2014 ablation shows Inception Score dropping from 8.1 to 3.2 when feature matching is disabled. A third limit emerges in the Recht et al. ICML 2019 benchmark (arxiv:1902.10811): SOTA CIFAR-10 models lose 5-10pp accuracy on CIFAR-10.1 (an independent replica), indicating benchmark overfitting. Mitigation: use independent test sets generated post-training, avoid tuning hyperparameters on test, apply Bonferroni correction when comparing many models.

Recent SOTA-pushing paper. Hu et al. 2021 LoRA (arxiv:2106.09685), Brown et al. 2020 GPT-3 (arxiv:2005.14165), Vaswani et al. 2017 Attention Is All You Need (arxiv:1706.03762). In particular, 2024-2025 works moved the frontier: Mixtral 8x22B (Jiang et al. 2024) beats GPT-3.5-turbo on MMLU (77.8 vs 70.0) using 39B active params over 141B total (Mixture of Experts top-2 routing). DeepSeek-V3 (DeepSeek-AI Dec 2024 arxiv:2412.19437) reaches 88.5 MMLU with MLA attention and Multi-Token Prediction loss, training cost USD 5.5M (10x cheaper than GPT-4). Claude 3.5 Sonnet (Anthropic Jun 2024) beats GPT-4o on HumanEval (92.0 vs 90.2) and becomes the reference model for agentic coding. Llama 3.3 70B (Meta Dec 2024) matches 405B using half the parameters thanks to iterative Knowledge Distillation.

Industry impact. In production, OpenAI reports inference cost of USD 0.50 per million tokens on GPT-4o-mini (Q1 2025), while on-prem vLLM on LLaMA-3.1-8B reaches USD 0.05-equivalent per million tokens on a single A10 GPU. For a principal-level portfolio engineer: tracking cost per 1k inferences, sustainable throughput and p99 SLO is mandatory. Standard tooling: Prometheus + Grafana for infra metrics, Langfuse or Helicone for LLM-specific observability, OpenTelemetry for distributed tracing. Typical cost optimisation: semantic cache (gptcache, Redis with embedding similarity) cuts 30-40% of calls; speculative decoding (Leviathan 2023 arxiv:2211.17192) doubles throughput at the same quality.

Software engineering automation

Devin (Cognition 2024), Claude 3.5 Sonnet Computer Use, SWE-Bench leaderboard. Pattern: read repo → understand task → write code → run tests → fix iteratively. Devin claimed 14% SWE-Bench, Cognition 49% with Claude 3.5. Real-world: pattern used in Sweep, Aider, Cursor Composer.

# Aider-like pseudo-code
repo = clone_repo()
task = 'Fix bug in auth.py'
relevant_files = embed_search(task, repo)
diff = llm.generate_diff(task, relevant_files)
apply_diff(diff)
result = run_tests()
if result.failed: refine_with(llm, result)

Mathematical formalisation. We define the problem as empirical risk minimisation R(θ) = (1/n) Σ L(f_θ(x_i), y_i), where L is the appropriate loss (cross-entropy for classification, MSE for regression, KL divergence for density matching). The Adam optimiser (Kingma-Ba 2014 arxiv:1412.6980) applies updates θ_t+1 = θ_t − η m̂_t / (√v̂_t + ε) with first- and second-order bias-corrected moments. AdamW (Loshchilov-Hutter 2017 arxiv:1711.05101) decouples weight decay, improving generalisation by 1-2pp on ImageNet.

Step-by-step algorithm. (1) Initialisation: He init for ReLU (He et al. 2015 arxiv:1502.01852), Xavier for tanh (Glorot-Bengio 2010). (2) Forward pass: propagate inputs through layers, caching intermediate activations for the subsequent backward. (3) Loss computation: apply softmax+CE in log-stable mode (logsumexp trick). (4) Backward: compute gradients via autograd or manual backprop; clip-norm to 1.0 for stability (Pascanu et al. 2013). (5) Optimizer step: update weights with Adam/AdamW; learning rate scheduler cosine decay (Loshchilov 2016) or linear warmup + decay (typical 1k step warmup). (6) Validation: every N steps, snapshot the best checkpoint by validation metric.

Complexity analysis and cost profile. Compute cost: training a 7B model requires about 1.4e22 FLOPs (Chinchilla scaling law, Hoffmann et al. 2022 arxiv:2203.15556), i.e. ~8 weeks on 64 A100 GPUs at 312 TFLOPs. GPU memory profile: activations dominate in training (10-20x weights), KV cache dominates inference (proportional to batch · seq_len). FlashAttention-2 (Dao 2023 arxiv:2307.08691) reduces memory from O(n^2) to O(n) via SRAM tiling. As a practical heuristic, a Bayesian hyperparameter tuning run (Optuna or Ax) typically needs 30-100 trials × 2-6 hours each, totalling 100-500 GPU-hours for a competitive model on a medium problem. Memory budget must be estimated before training: rule of thumb is GPU memory = 16 × params for fp32 Adam training, dropping to 4 × params with fp16 mixed precision + activation checkpointing (Chen et al. 2016 arxiv:1604.06174).

Known limits and ablation studies. Known limit: distribution shift between train and production; Quinonero-Candela et al. Dataset Shift in Machine Learning (MIT Press 2009) taxonomises covariate, label and concept shift. Known limit: mode collapse when loss converges to non-expressive local minima; Goodfellow et al. 2014 ablation shows Inception Score dropping from 8.1 to 3.2 when feature matching is disabled. A third limit emerges in the Recht et al. ICML 2019 benchmark (arxiv:1902.10811): SOTA CIFAR-10 models lose 5-10pp accuracy on CIFAR-10.1 (an independent replica), indicating benchmark overfitting. Mitigation: use independent test sets generated post-training, avoid tuning hyperparameters on test, apply Bonferroni correction when comparing many models.

Recent SOTA-pushing paper. Vaswani et al. 2017 Attention Is All You Need (arxiv:1706.03762), Touvron et al. 2023 LLaMA (arxiv:2302.13971), Hu et al. 2021 LoRA (arxiv:2106.09685). In particular, 2024-2025 works moved the frontier: Mixtral 8x22B (Jiang et al. 2024) beats GPT-3.5-turbo on MMLU (77.8 vs 70.0) using 39B active params over 141B total (Mixture of Experts top-2 routing). DeepSeek-V3 (DeepSeek-AI Dec 2024 arxiv:2412.19437) reaches 88.5 MMLU with MLA attention and Multi-Token Prediction loss, training cost USD 5.5M (10x cheaper than GPT-4). Claude 3.5 Sonnet (Anthropic Jun 2024) beats GPT-4o on HumanEval (92.0 vs 90.2) and becomes the reference model for agentic coding. Llama 3.3 70B (Meta Dec 2024) matches 405B using half the parameters thanks to iterative Knowledge Distillation.

Industry impact. MLPerf Inference Benchmark (Reddi et al. 2020 arxiv:1911.02549) is the de facto vendor-hardware standard: NVIDIA H100, AMD MI300X, Google TPU v5e, Intel Gaudi 3. For a principal-level portfolio engineer: tracking cost per 1k inferences, sustainable throughput and p99 SLO is mandatory. Standard tooling: Prometheus + Grafana for infra metrics, Langfuse or Helicone for LLM-specific observability, OpenTelemetry for distributed tracing. Typical cost optimisation: semantic cache (gptcache, Redis with embedding similarity) cuts 30-40% of calls; speculative decoding (Leviathan 2023 arxiv:2211.17192) doubles throughput at the same quality.

Evaluation: SWE-Bench, HumanEval+

SWE-Bench (Princeton 2023 arxiv:2310.06770): 2294 real GitHub issues + tests. 2026 frontier: Claude 3.5 Sonnet 49% resolved, GPT-4o 33%, open-source LLaMA-70B 14%. HumanEval+ (Liu 2023): function-level coding, pass@1 96.3% Claude 3.5 Sonnet.

# SWE-Bench eval
# Each instance: repo SHA + test before fix + golden patch
# Agent must produce patch that passes test post-fix
# Metric: resolved % = test passes
# Lite split: 300 easier instances

Mathematical formalisation. We define the problem as empirical risk minimisation R(θ) = (1/n) Σ L(f_θ(x_i), y_i), where L is the appropriate loss (cross-entropy for classification, MSE for regression, KL divergence for density matching). The Adam optimiser (Kingma-Ba 2014 arxiv:1412.6980) applies updates θ_t+1 = θ_t − η m̂_t / (√v̂_t + ε) with first- and second-order bias-corrected moments. AdamW (Loshchilov-Hutter 2017 arxiv:1711.05101) decouples weight decay, improving generalisation by 1-2pp on ImageNet.

Step-by-step algorithm. (1) Initialisation: He init for ReLU (He et al. 2015 arxiv:1502.01852), Xavier for tanh (Glorot-Bengio 2010). (2) Forward pass: propagate inputs through layers, caching intermediate activations for the subsequent backward. (3) Loss computation: apply softmax+CE in log-stable mode (logsumexp trick). (4) Backward: compute gradients via autograd or manual backprop; clip-norm to 1.0 for stability (Pascanu et al. 2013). (5) Optimizer step: update weights with Adam/AdamW; learning rate scheduler cosine decay (Loshchilov 2016) or linear warmup + decay (typical 1k step warmup). (6) Validation: every N steps, snapshot the best checkpoint by validation metric.

Complexity analysis and cost profile. Compute cost: training a 7B model requires about 1.4e22 FLOPs (Chinchilla scaling law, Hoffmann et al. 2022 arxiv:2203.15556), i.e. ~8 weeks on 64 A100 GPUs at 312 TFLOPs. GPU memory profile: activations dominate in training (10-20x weights), KV cache dominates inference (proportional to batch · seq_len). FlashAttention-2 (Dao 2023 arxiv:2307.08691) reduces memory from O(n^2) to O(n) via SRAM tiling. As a practical heuristic, a Bayesian hyperparameter tuning run (Optuna or Ax) typically needs 30-100 trials × 2-6 hours each, totalling 100-500 GPU-hours for a competitive model on a medium problem. Memory budget must be estimated before training: rule of thumb is GPU memory = 16 × params for fp32 Adam training, dropping to 4 × params with fp16 mixed precision + activation checkpointing (Chen et al. 2016 arxiv:1604.06174).

Known limits and ablation studies. Known limit: mode collapse when loss converges to non-expressive local minima; Goodfellow et al. 2014 ablation shows Inception Score dropping from 8.1 to 3.2 when feature matching is disabled. Known limit: catastrophic forgetting in sequential fine-tuning; Kirkpatrick et al. 2017 (EWC, arxiv:1612.00796) proposes Fisher regularisation to mitigate. A third limit emerges in the Recht et al. ICML 2019 benchmark (arxiv:1902.10811): SOTA CIFAR-10 models lose 5-10pp accuracy on CIFAR-10.1 (an independent replica), indicating benchmark overfitting. Mitigation: use independent test sets generated post-training, avoid tuning hyperparameters on test, apply Bonferroni correction when comparing many models.

Recent SOTA-pushing paper. Devlin et al. 2018 BERT (arxiv:1810.04805), Jiang et al. 2024 Mixtral 8x7B (arxiv:2401.04088), Vaswani et al. 2017 Attention Is All You Need (arxiv:1706.03762). In particular, 2024-2025 works moved the frontier: Mixtral 8x22B (Jiang et al. 2024) beats GPT-3.5-turbo on MMLU (77.8 vs 70.0) using 39B active params over 141B total (Mixture of Experts top-2 routing). DeepSeek-V3 (DeepSeek-AI Dec 2024 arxiv:2412.19437) reaches 88.5 MMLU with MLA attention and Multi-Token Prediction loss, training cost USD 5.5M (10x cheaper than GPT-4). Claude 3.5 Sonnet (Anthropic Jun 2024) beats GPT-4o on HumanEval (92.0 vs 90.2) and becomes the reference model for agentic coding. Llama 3.3 70B (Meta Dec 2024) matches 405B using half the parameters thanks to iterative Knowledge Distillation.

Industry impact. MLPerf Inference Benchmark (Reddi et al. 2020 arxiv:1911.02549) is the de facto vendor-hardware standard: NVIDIA H100, AMD MI300X, Google TPU v5e, Intel Gaudi 3. For a principal-level portfolio engineer: tracking cost per 1k inferences, sustainable throughput and p99 SLO is mandatory. Standard tooling: Prometheus + Grafana for infra metrics, Langfuse or Helicone for LLM-specific observability, OpenTelemetry for distributed tracing. Typical cost optimisation: semantic cache (gptcache, Redis with embedding similarity) cuts 30-40% of calls; speculative decoding (Leviathan 2023 arxiv:2211.17192) doubles throughput at the same quality.

Safety, sandbox, observability

Sandbox tool execution: Docker, Firecracker, gVisor. Permission per tool (read-only vs write). Confirm step for destructive (DB write, send email, file delete). Immutable logging: Langfuse, LangSmith, custom OpenTelemetry. Cost budget per agent run.

# Cost budget enforcement
MAX_COST_USD = 5.0
total_cost = 0.0
while not done:
    cost = llm_call_estimate(prompt)
    total_cost += cost
    if total_cost > MAX_COST_USD:
        raise BudgetExceeded()
    response = llm.generate(prompt)

Mathematical formalisation. We define the problem as empirical risk minimisation R(θ) = (1/n) Σ L(f_θ(x_i), y_i), where L is the appropriate loss (cross-entropy for classification, MSE for regression, KL divergence for density matching). The Adam optimiser (Kingma-Ba 2014 arxiv:1412.6980) applies updates θ_t+1 = θ_t − η m̂_t / (√v̂_t + ε) with first- and second-order bias-corrected moments. AdamW (Loshchilov-Hutter 2017 arxiv:1711.05101) decouples weight decay, improving generalisation by 1-2pp on ImageNet.

Step-by-step algorithm. (1) Initialisation: He init for ReLU (He et al. 2015 arxiv:1502.01852), Xavier for tanh (Glorot-Bengio 2010). (2) Forward pass: propagate inputs through layers, caching intermediate activations for the subsequent backward. (3) Loss computation: apply softmax+CE in log-stable mode (logsumexp trick). (4) Backward: compute gradients via autograd or manual backprop; clip-norm to 1.0 for stability (Pascanu et al. 2013). (5) Optimizer step: update weights with Adam/AdamW; learning rate scheduler cosine decay (Loshchilov 2016) or linear warmup + decay (typical 1k step warmup). (6) Validation: every N steps, snapshot the best checkpoint by validation metric.

Complexity analysis and cost profile. Compute cost: training a 7B model requires about 1.4e22 FLOPs (Chinchilla scaling law, Hoffmann et al. 2022 arxiv:2203.15556), i.e. ~8 weeks on 64 A100 GPUs at 312 TFLOPs. Latency p50 ~50ms / p99 ~250ms on a single T4 instance with batch 16 and an INT8-quantised 100M-parameter model. As a practical heuristic, a Bayesian hyperparameter tuning run (Optuna or Ax) typically needs 30-100 trials × 2-6 hours each, totalling 100-500 GPU-hours for a competitive model on a medium problem. Memory budget must be estimated before training: rule of thumb is GPU memory = 16 × params for fp32 Adam training, dropping to 4 × params with fp16 mixed precision + activation checkpointing (Chen et al. 2016 arxiv:1604.06174).

Known limits and ablation studies. Known limit: learning rate sensitivity; Smith 2017 ablation (arxiv:1708.07120) shows 1cycle policy cuts convergence time by 3-5x compared to fixed LR. Known limit: overconfidence in deep nets; Guo et al. ICML 2017 arxiv:1706.04599 reports ECE > 0.10 without temperature scaling. A third limit emerges in the Recht et al. ICML 2019 benchmark (arxiv:1902.10811): SOTA CIFAR-10 models lose 5-10pp accuracy on CIFAR-10.1 (an independent replica), indicating benchmark overfitting. Mitigation: use independent test sets generated post-training, avoid tuning hyperparameters on test, apply Bonferroni correction when comparing many models.

Recent SOTA-pushing paper. Devlin et al. 2018 BERT (arxiv:1810.04805), Brown et al. 2020 GPT-3 (arxiv:2005.14165), Hu et al. 2021 LoRA (arxiv:2106.09685). In particular, 2024-2025 works moved the frontier: Mixtral 8x22B (Jiang et al. 2024) beats GPT-3.5-turbo on MMLU (77.8 vs 70.0) using 39B active params over 141B total (Mixture of Experts top-2 routing). DeepSeek-V3 (DeepSeek-AI Dec 2024 arxiv:2412.19437) reaches 88.5 MMLU with MLA attention and Multi-Token Prediction loss, training cost USD 5.5M (10x cheaper than GPT-4). Claude 3.5 Sonnet (Anthropic Jun 2024) beats GPT-4o on HumanEval (92.0 vs 90.2) and becomes the reference model for agentic coding. Llama 3.3 70B (Meta Dec 2024) matches 405B using half the parameters thanks to iterative Knowledge Distillation.

Industry impact. Hugging Face Hub hosts 1.2M+ models as of 2025; monthly new-model rate tripled between 2023 and 2024 (HF Trends Report). For a principal-level portfolio engineer: tracking cost per 1k inferences, sustainable throughput and p99 SLO is mandatory. Standard tooling: Prometheus + Grafana for infra metrics, Langfuse or Helicone for LLM-specific observability, OpenTelemetry for distributed tracing. Typical cost optimisation: semantic cache (gptcache, Redis with embedding similarity) cuts 30-40% of calls; speculative decoding (Leviathan 2023 arxiv:2211.17192) doubles throughput at the same quality.

Benchmark and current SOTA

Reference benchmarks and SOTA for this topic:

CrewAI GitHub stars
Q1 2026 ~20k stars
AutoGen Microsoft adoption
Used in Azure AI Studio
LangGraph
Production standard 2026
SWE-Bench Verified
Claude 3.5 Sonnet 49%, frontier 2026
Devin Cognition
1.6x slower vs single Claude but more autonomous
Cost per SWE-Bench run
$1-10 typical agent run

Production deployment

2026 production stack: LangGraph (stateful), Claude 3.5 Sonnet / GPT-4o (frontier), Pydantic schema validation, Firecracker sandbox, Redis state persistence, Langfuse observability, PagerDuty alerts. Cost budget: $0.05-0.50 per simple task, $5-50 per SWE-Bench-class. Safety: human confirm on destructive, immutable audit log.

Production case studies

Three real-world case studies illustrate applying the techniques above to industrial problems with latency, cost and compliance constraints.

Case study 1 - Anthropic Claude on AWS Trainium

Anthropic announced (Sep 2024 blog) porting Claude 3 to AWS Trainium2: 50% higher training throughput vs H100 at the same cost, thanks to Neuron SDK compiler optimised for attention patterns and BF16 mixed precision. Trade-off: less mature software ecosystem, porting PyTorch libraries takes 2-4 weeks of engineering. Operational lesson: GPU is not the only option; TPU v5 and Trainium2 are competitive for specific workloads if the team has the skills.

Case study 2 - Spotify retrieval with Annoy + ScaNN

Spotify published (KDD 2024) the retrieval pipeline for 100M+ tracks: 128-dim embeddings, Annoy index (Bernhardsson) for billion-scale, search with ScaNN (Guo et al. 2020 arxiv:1908.10396) for low latency. Throughput 50k QPS per node, p99 latency 8ms. Embeddings obtained via two-tower co-training on 30M interactions/hour. Embedding re-train every 24h; A/B test shows +12% NDCG@10 vs collaborative-filtering baseline.

Case study 3 - Stripe fraud detection with XGBoost + drift

Stripe (StripeCon 2024) runs an XGBoost + DeepFM ensemble for real-time fraud scoring. 500+ engineered features (velocity, network features, geo). Target latency p99 50ms. Drift detection with Evidently AI: alert if PSI > 0.2 on top-20 features; weekly shadow auto-retraining + manual approval before promotion. USD 200M+ annual fraud-loss savings.

Advanced patterns and optimisation

To go beyond the baseline you need non-standard patterns. We list eight production-grade patterns used by Anthropic, OpenAI, Google DeepMind and Meta AI.

Continuous batching (vLLM, Orca)
Schedules completed and new requests at the token level, not the request level. +5-10x throughput vs naive batching (Yu et al. OSDI 2022).
Speculative decoding
A small draft model proposes n tokens, the target model accepts/rejects; 2-3x throughput (Leviathan ICML 2023 arxiv:2211.17192).
int4 / GPTQ / AWQ quantisation
4-bit compression with <1pp accuracy loss; 4x less memory (Frantar et al. ICLR 2023 arxiv:2210.17323).
FlashAttention-2
O(n) memory instead of O(n^2); 2-4x forward+backward speedup (Dao 2023 arxiv:2307.08691).
Tensor + Pipeline parallelism
Megatron-LM (Shoeybi et al. 2019); shard weights and activations across 8-128 GPUs.
Top-2 routing Mixture of Experts
Switch Transformer (Fedus 2021); activate 2/E experts per token, +10x params at constant cost.
LoRA / QLoRA adapters
Fine-tune 0.1% of params; QLoRA (Dettmers NeurIPS 2023 arxiv:2305.14314) uses a 4-bit base.
KV cache compression (H2O, Scissorhands)
Heavy-hitter oracle shrinks the cache 80% with no quality loss (Zhang NeurIPS 2023).

End-to-end MLOps operations

A production-grade pipeline has seven stages: ingestion, validation, training, evaluation, registry, serving, monitoring. Each stage has automatic quality gating.

1. Ingestion. Kafka or Pub/Sub for stream; Airflow or Dagster for batch. Schema validated with GE or Pandera. Lineage tracked with OpenLineage. Typical volume: 10-100 GB/day for a mid-size model, 10+ TB/day for foundation training.

2. Validation. Schema check, distribution drift (KS test, PSI), business rules (no NaN on critical features, values in plausible range). Block ingestion if violations > threshold.

3. Training. PyTorch Lightning + Hydra config; MLflow / W&B tracking. Reproducible experiment: seed + version pinning + Docker image. Cost guardrail: max GPU-hour per run, alert if > 80% budget.

4. Evaluation. Fixed test set + rolling canary set; primary metric (e.g. ROC-AUC) + secondary (fairness, calibration, robustness). Champion-challenger: a new model must beat the champion by 1-2% statistically.

5. Registry. MLflow Model Registry or BentoML; semantic versioning, lineage data → code → model, approval workflow (4-eyes for high-risk models).

6. Serving. FastAPI / TorchServe / Triton / vLLM / SageMaker. Latency target: p50 < 50ms, p99 < 200ms. KEDA auto-scaling on queue length or latency. Blue-green or canary deploy 1% → 10% → 50% → 100%.

7. Monitoring. Prometheus + Grafana + Loki. Data drift (Evidently AI), prediction drift, performance drift (labels arrive with delay). PagerDuty alert on SLO violation.

Known pitfalls and ablation studies

  • Infinite looping: cap max iterations.
  • Unchecked cost: budget per run.
  • Hallucinated tool: schema validation.
  • Multi-agent prompt injection: trust boundaries.
  • State race condition: lock or serialise.
  • Unpredictable emergent behaviour: extensive eval.
  • Cumulative latency: 10x single agent.
  • Hard debug: log every step.

Advanced exercises

  1. CrewAI 3-agent research/write/review on topic; faithfulness.
  2. AutoGen UserProxy + Assistant + CodeExecutor: build flask app.
  3. LangGraph stateful workflow: planner-coder-tester with retry.
  4. SWE-Bench Lite eval with Claude 3.5 Sonnet; resolve %.
  5. Cost optimisation: model routing easy → mini, hard → frontier.
  6. Multi-agent debate (Du 2023): N-agent reasoning consensus.

Frequently asked questions

How much does training a competitive model cost in 2026?
For a 7B model competitive on MMLU > 65, a realistic budget is USD 80-150k on 8-16 H100 for 14-21 days, excluding data curation. Most of the cost is data engineering (~60%), not compute.
Which consumer GPU makes sense today?
RTX 4090 (24GB) for 7B QLoRA fine-tuning; RTX 6000 Ada (48GB) for int4 70B inference. For serious training, A100 80GB remains the workhorse.
How to estimate tokens in a dataset?
Rule of thumb: 1 token ≈ 4 chars EN or 3 chars IT. Use tiktoken with the target model's tokenizer. Hugging Face datasets exposes num_tokens() natively.
RAG or fine-tuning?
RAG when knowledge changes (news, updated docs) or is private; fine-tune for style adaptation, custom function calling, latency reduction. Often combined.
When does ColBERT beat BGE?
Domains with narrow vocabulary and long queries (legal, medical); late interaction recovers rarely co-occurring concepts. BGE-M3 with multi-vector is competitive at 10x less storage.
How to handle dataset bias?
Fairlearn, AIF360 for metrics (equal opportunity, demographic parity); resampling, reweighting, adversarial debiasing for mitigation; documentation via DataCard (Pushkarna et al. 2022).

Extended technical glossary

SGD
Stochastic Gradient Descent: base optimiser with momentum, Polyak (1964) and Nesterov (1983) variants.
Adam
Adaptive Moment Estimation (Kingma-Ba 2014 arxiv:1412.6980); default for most deep learning tasks.
KL
Kullback-Leibler divergence: asymmetric distance measure between probability distributions, basis of ELBO and VAE.
VAE
Variational Autoencoder (Kingma-Welling 2013 arxiv:1312.6114); encoder produces μ, σ; reparametrisation trick z = μ + σε.
GAN
Generative Adversarial Network (Goodfellow 2014); generator + discriminator min-max.
RLHF
(Christiano 2017, Ouyang InstructGPT 2022 arxiv:2203.02155); reward model + PPO.
DPO
Direct Preference Optimization (Rafailov 2023 arxiv:2305.18290); RLHF alternative without explicit reward model.
MCMC
Markov Chain Monte Carlo; HMC (Neal 2011), NUTS (Hoffman-Gelman 2014) for complex posteriors.
VI
Approximates posterior with variational family q(z); optimises ELBO.
MoE
Mixture of Experts (Shazeer 2017); top-k router activates a subset of experts per token.

Essential bibliography

  • Wu et al. - AutoGen (arxiv:2308.08155)
  • CrewAI documentation
  • LangGraph documentation (LangChain 2024)
  • Park et al. - Generative Agents (UIST 2023, arxiv:2304.03442)
  • Jimenez et al. - SWE-Bench (arxiv:2310.06770)
  • Du et al. - Improving Factuality and Reasoning via Multi-Agent Debate (arxiv:2305.14325)
  • Yao et al. - ReAct (ICLR 2023)
  • Anthropic Claude 3.5 Sonnet Computer Use docs

Technical prerequisites

  • LLM API basics
  • LangChain / CrewAI / AutoGen
  • Docker sandboxing
  • Observability: Langfuse, LangSmith

Related resources

Article updated 2026-05-16, research engineer level.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects