This chapter consolidates key equations, architecture specifications, API references, and failure mode diagnostics for rapid lookup during development and debugging.
Core RL & Alignment Equations
Transformer & Architecture Formulas
Decoding Methods
MethodFormula / RuleKey ParamGreedy—Beam searchKeep top- partial sequences by joint probability–TemperatureTop-Zero out all but top- logits, renormalize–Top- (nucleus)Keep smallest set s.t. –Min-Keep tokens with –Repetition penalty if appeared before–
Systems & Parallelism
FormulaValue (70B, BF16)DescriptionModel memory bytes GB (weights only)Adam optimizer bytes (m + v) GBFull training footprint bytes GB (weights + opt + grad)FSDP memory/GPU GB with 8 GPUsGen arithmetic intensity FLOP/byteHeavily memory-boundToken rate (gen)HBM_BW 14 tok/s (A100, batch=1)TP AllReduce / layer bytes188 MB (70B, TP=8)PP bubble fraction=stages, =micro-batchesMFUobserved_toks 6 / peak_FLOPSTarget:
GPU Hardware Specs
GPUMemoryBW (HBM)BF16 TFLOPSNVLinkNotesA100-80GB80 GB HBM2e2.0 TB/s312600 GB/sWorkhorse, widely availableH100-80GB80 GB HBM33.35 TB/s989900 GB/sCurrent gen, FP8 supportH200-141GB141 GB HBM3e4.8 TB/s989900 GB/sLarge context / fewer GPUsB200192 GB HBM3e8.0 TB/s22501800 GB/sNext gen (2025)
Hyperparameter Ranges
ParameterTypical RangeDefaultNotes (DPO/KTO)0.05–0.50.1Higher = more conservative (PPO clip)0.1–0.30.2Higher = more aggressive updates (GAE discount)0.99–1.01.0Use 1.0 for episodic tasks (GAE)0.9–0.990.95Lower = more biased, less varianceKL coeff ()0.01–0.20.05Auto-adapt to target KL 5–8LR (RLHF)1e-7 – 5e-65e-7Much lower than pre-trainingLR (SFT)1e-5 – 5e-52e-5Standard fine-tuning rangeLoRA rank 8–12816–64Higher = more capacity, more memoryLoRA alpha – Scaling factor; is the effective scaleTemperature (gen)0.6–1.00.7Lower = less diverse candidatesNum generations 4–644–16For GRPO/Online DPO/Best-of-NGrad clip norm0.5–2.01.0Prevents gradient explosion
TRL API Quick Reference
TrainerMethodKey ConfigData FormatSFTTrainerSupervised FTpacking, max_seq_lengthprompt + completionRewardTrainerReward modelcenter_rewards_coefficientprompt + chosen + rejectedPPOTrainerPPOinit_kl_coef, target_kl, cliprangeprompts (online gen)DPOTrainerDPO/IPObeta, loss_type="sigmoid"/"ipo"prompt + chosen + rejectedGRPOTrainerGRPOnum_generations, beta, use_vllmprompts + reward_fnOnlineDPOTrainerOnline DPOnum_generations, reward_model_pathprompts (online gen)KTOTrainerKTOdesirable_weight, undesirable_weightprompt + completion + labelORPOTrainerORPObetaprompt + chosen + rejectedBest-of-N (manual)Best-of-Nn_samplesprompts (inference)
RAG Pipeline Formulas
Agentic Design Patterns
PatternStructureBest ForReActThink Act Observe loopGeneral tool-use agentsPlan-and-ExecutePlan Execute steps ReviseLong-horizon, structured tasksSupervisorRouter specialist agentsMulti-domain, clear subtask boundariesSwarm (handoffs)Agent transfers control + contextCustomer service, escalation flowsHierarchicalTree of delegating agentsComplex decompositionHuman-in-the-loopAgent Approval gate ContinueHigh-stakes, irreversible actions
Agent Communication Protocols
ProtocolScopeTransportKey ConceptMCPTool integrationstdio / HTTP+SSEServer exposes tools; client discovers & callsA2AAgent-to-agentHTTP + JSON-RPCTasks with lifecycle (submittedworkingdone)OpenAI Function CallingTool useAPI payloadJSON schema in tools[] array
Context Window Budget
Rule of thumb for 128K context:
- System prompt: 1–4K tokens (fixed)
- Tool definitions: 2–8K (scales with # tools)
- RAG context: 4–16K (top- chunks)
- History: grows unbounded summarize/truncate
- Reserved output: 2–8K
Common Failure Modes & Fixes
SymptomLikely CauseFixReward up, quality downReward hackingRM ensemble, length penalty, increase KL exploding (15)LR too high or mode collapseReduce LR, checkpoint rollbackEntropy collapsePremature convergenceIncrease entropy coeff, raise temperatureTraining loss NaNGradient explosionReduce LR, increase grad clip, check dataNo improvement after 5K stepsBad prompt distributionGoldilocks filter (20–80% pass rate)Benchmark regressionAlignment taxReduce RL budget, use LoRA, mix SFT dataLength increasing monotonicallyLength exploit in RMLength penalty, retrain RM with length controlOOM during generationKV cache overflowReduce batch, increase TP, PagedAttentionAgent loops foreverNo max-iteration guardSet max_iterations, add loop detectionTool call parse failuresInconsistent output formatFew-shot examples, constrained decodingRAG returns irrelevant docsPoor embedding / chunkingReranker, hybrid search, smaller chunksMulti-agent deadlockCircular dependenciesDAG enforcement, timeout per agent
Method Selection Decision Tree
- Have paired preferences (chosen + rejected)?•Noisy labels IPO•Memory-constrained, no SFT done yet ORPO•Clean data, limited compute DPO•DPO plateaus, want exploration Online DPO
- Have only binary feedback (thumbs up/down)?KTO
- Have verifiable rewards (math/code)?GRPO
- Need maximum quality, any cost?PPO
- Want training-free improvement?Best-of-N
Evaluation Metrics
MetricRangeWhat It MeasuresPerplexityModel’s surprise; lower = better language modelingWin Rate (vs. baseline)Fraction of outputs preferred by judge/humanBLEU-gram overlap with reference (precision-focused)ROUGE-LLongest common subsequence with referencePass@Probability 1 of code samples passes testsMMLU / GPQAMulti-choice accuracy on knowledge/reasoning benchmarksHumanEvalFunctional correctness of generated codeFaithfulness (RAG)Fraction of claims supported by retrieved contextContext RelevancyFraction of retrieved content relevant to queryAnswer RelevancyDegree to which answer addresses the question
Reasoning & Test-Time Scaling
MethodCompute CostMechanismChain-of-Thought (CoT)1.5–3 tokens“Think step by step” in promptSelf-Consistency generationSample CoT paths, majority vote on final answerTree-of-Thought (ToT) generationBFS/DFS over reasoning tree; evaluate branchesBest-of- generationSample , score with RM, pick highestBeam search (on reasoning) generationMaintain top- partial reasoning chainsBudget forcingVariableAllocate more tokens to harder problems dynamicallyVerification (ORM/PRM) gen + scoringGenerate solutions, rank by outcome/process RM
Memory System Types
TypeStorageUse CaseWorking memoryContext windowCurrent conversation, immediate tool resultsEpisodic memoryVector storePast interactions, user preferences, session historySemantic memoryKnowledge graph / embeddingsFacts, concepts, domain knowledgeProcedural memorySkill library / codeHow-to procedures, learned workflows
MCP Quick Reference
PrimitiveDirectionSide Effects?PurposeToolsClient ServerYesExecute actions (create, modify, delete)ResourcesClient ServerNo (read-only)Read data (files, DB records, configs)PromptsClient ServerNoReusable templates for common tasksSamplingServer ClientNoServer requests LLM generation from client
Transport: stdio (local subprocess) or HTTP+SSE (remote, streamable).
Discovery: Client calls tools/list, resources/list, prompts/list at connection init.
Tool annotations: readOnlyHint, destructiveHint, idempotentHint, openWorldHint.
A2A Protocol Quick Reference
ConceptDescriptionAgent CardJSON at /.well-known/agent.json — name, skills, supported content typesTaskUnit of work: id, status, artifacts. Lifecycle: submitted working completed/failedMessageCommunication unit within a task (role: user/agent, parts: text/file/data)ArtifactOutput produced by the agent (structured data, files, generated content)Push NotificationsWebhook-based updates for long-running tasks (via tasks/pushNotification/set)
Key endpoints: tasks/send (create/update), tasks/get (poll status), tasks/sendSubscribe (SSE stream).
Agent Framework Comparison
FrameworkOrchestrationMulti-AgentBest ForLangGraphExplicit state graphConditional routingProduction: persistence, HITL, fine controlOpenAI Agents SDKDeclarative handoffsHandoff-basedSimplicity: guardrails, tracing, fast startAutoGen (AG2)Conversation-drivenGroupChatPrototyping: code execution, researchCrewAIRole-based teamsSequential/parallelLow-code: quick demos, simple pipelinesGoogle ADKSession + eventsA2A nativeEnterprise: artifact mgmt, multi-modal
Agentic RL Formulas
Agent Security Checklist
ThreatLayerMitigationPrompt injection (direct)InputInput validation, instruction hierarchy, delimitersPrompt injection (indirect)Tool outputTreat tool output as untrusted; don’t follow instructions in retrieved docsTool misuseExecutionLeast-privilege permissions; destructiveHint gates; sandboxingData exfiltrationOutputOutput filtering; restrict tool access to allowed domainsExcessive autonomyArchitectureMax iterations; cost budgets; human approval gatesConfused deputyMulti-agentVerify task origin; capability-based access control
Agent Evaluation Metrics
MetricFormula / DefinitionTargetTask Success Rate (TSR)Correct completions / total tasks (production)Steps to completionAvg agent actions per successful taskLower = more efficientCost per taskTotal tokens price/tokenBudget-dependentLatency (TTFC)Time from request to first useful outputs for interactiveTool call accuracyCorrect tool selections / total callsRecovery rateSuccessful retries / initial failuresHuman escalation rateTasks requiring human / total tasks
Key Agentic Benchmarks
BenchmarkDomainMetricSOTA (2025)SWE-bench VerifiedSoftware engineering% resolved issues70%WebArenaWeb browsingTask success rate40%OSWorldDesktop computer useTask success rate25%GAIAGeneral AI assistantExact match accuracy75% (L1)Tau-benchTool-use reliabilityPass rate (5 trials)65%HumanEval / MBPPCode generationPass@1