From 5829eb6c436bbab7427b7c4db90a648a8526d46e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emil=20W=C3=A5reus?= Date: Wed, 2 Sep 2026 19:24:38 +0200 Subject: [PATCH] docs(brain): add open-weight LLM post-training guide --- .../01-foundations-and-taxonomy.md | 183 +++ .../03-hardware-memory-and-scaling.md | 199 +++ .../05-sft-and-dpo-mechanisms.md | 214 +++ .../06-ppo-grpo-and-rlvr-mechanisms.md | 197 +++ .../07-fast-execution-and-training-systems.md | 175 +++ ...9-domain-case-study-and-evidence-limits.md | 196 +++ .../10-continual-and-production-learning.md | 173 +++ ...uman-data-in-foundational-post-training.md | 183 +++ .../13-sft-data-quality-primary-studies.md | 186 +++ .../synthesis.md | 184 +++ .../post-training-open-weight-llms.md | 1291 +++++++++++++++++ 11 files changed, 3181 insertions(+) create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/01-foundations-and-taxonomy.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/03-hardware-memory-and-scaling.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/05-sft-and-dpo-mechanisms.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/06-ppo-grpo-and-rlvr-mechanisms.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/07-fast-execution-and-training-systems.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/09-domain-case-study-and-evidence-limits.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/10-continual-and-production-learning.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/12-human-data-in-foundational-post-training.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/13-sft-data-quality-primary-studies.md create mode 100644 brain/inbox/dr/2026-09-02-post-training-llms/synthesis.md create mode 100644 brain/insights/llm-post-training/post-training-open-weight-llms.md diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/01-foundations-and-taxonomy.md b/brain/inbox/dr/2026-09-02-post-training-llms/01-foundations-and-taxonomy.md new file mode 100644 index 0000000..e3984b7 --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/01-foundations-and-taxonomy.md @@ -0,0 +1,183 @@ +--- +title: "Research the definitions and stage boundaries of post-training open-weight large language models. Current date is 2026-09-02. Explain how pretraining differs from continued or domain-adaptive pretraining, supervised fine-tuning, parameter-efficient fine-tuning, preference optimization, RLHF, RLAIF, reinforcement learning with verifiable rewards, distillation, and online continual learning. For each method state the training record shape, objective family, whether it is reinforcement learning, what capability it can reshape, and its normal place in a practical pipeline. Resolve inconsistent use of the word post-training. Use original papers and official technical documentation." +generated_at: 2026-09-02T16:26:00.955327+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Definitions and Stage Boundaries of Post-Training Open-Weight Large Language Models + +## Abstract +This paper explores the definitions and stage boundaries of post-training open-weight large language models. It differentiates between pretraining, continued pretraining, domain-adaptive pretraining, supervised fine-tuning, parameter-efficient fine-tuning, preference optimization, reinforcement learning with human feedback (RLHF), reinforcement learning with AI feedback (RLAIF), reinforcement learning with verifiable rewards, distillation, and online continual learning. The analysis identifies each method's training record shape, objective family, reinforcement learning involvement, capability reshaping, and place in a practical pipeline. + +## Research Question +What are the definitions and stage boundaries of post-training open-weight large language models, and how do various training methods differ in objectives, processes, and roles within a practical pipeline? + +## Method +We reviewed original research papers and official technical documentation to gather definitions and explanations of training methods. We compared these methods based on training record shape, objective family, reinforcement learning involvement, capability reshaping, and their place in a practical pipeline. + +## Conceptual Background +- **Pretraining**: Initial phase where a model learns general language patterns from a large corpus [S2]. +- **Continued Pretraining**: Further training on domain-specific or recent unlabeled text [S2]. +- **Domain-Adaptive Pretraining**: A subset of continued pretraining focused on specific domains [S7]. +- **Supervised Fine-Tuning**: Adapts a pre-trained model to specific tasks using labeled data [S2]. +- **Parameter-Efficient Fine-Tuning (PEFT)**: Updates a small subset of parameters for task adaptation [S8]. +- **Preference Optimization**: Adjusts models based on user preferences, often using reinforcement learning. +- **RLHF/RLAIF**: Reinforcement learning methods using human or AI feedback to refine model outputs. +- **Reinforcement Learning with Verifiable Rewards**: Uses verifiable metrics for reward signals. +- **Distillation**: Transfers knowledge from a large model to a smaller one. +- **Online Continual Learning**: Integrates new data continuously to update models. + +## Findings +### Training Methods Comparison + +| Method | Training Record Shape | Objective Family | Reinforcement Learning | Capability Reshaping | Pipeline Stage | +|--------------------------------|-----------------------|------------------|------------------------|----------------------|-------------------------| +| Pretraining | Large, diverse corpus | Unsupervised | No | General language | Initial phase | +| Continued Pretraining | Domain-specific text | Unsupervised | No | Domain adaptation | Post-pretraining | +| Domain-Adaptive Pretraining | Domain-specific text | Unsupervised | No | Domain adaptation | Post-pretraining | +| Supervised Fine-Tuning | Labeled task data | Supervised | No | Task-specific | Post-pretraining | +| Parameter-Efficient Fine-Tuning| Labeled task data | Supervised | No | Task-specific | Post-pretraining | +| Preference Optimization | User feedback | Reinforcement | Yes | User alignment | Post-fine-tuning | +| RLHF/RLAIF | Human/AI feedback | Reinforcement | Yes | Output refinement | Post-fine-tuning | +| Reinforcement Learning (Verifiable)| Verifiable metrics | Reinforcement | Yes | Metric alignment | Post-fine-tuning | +| Distillation | Model outputs | Supervised | No | Model compression | Post-training | +| Online Continual Learning | Streaming data | Unsupervised | No | Continuous update | Post-training | + +### Insight +Continued pretraining and domain-adaptive pretraining enhance domain-specific performance by leveraging domain-specific corpora, but their effectiveness varies with model size and domain specificity [S4, S7]. Parameter-efficient fine-tuning is crucial for resource-constrained environments, allowing large models to be adapted with minimal parameter updates [S8]. + +## Design Implications +Designing training pipelines for large language models requires careful selection of methods based on resource availability, domain specificity, and desired capabilities. Parameter-efficient methods and continual learning strategies can optimize resource use and model adaptability. + +## Limitations and Threats to Validity +The evidence primarily focuses on models under 1.5 billion parameters, which may not generalize to larger models [S4]. The definitions and boundaries of training stages are not universally agreed upon, leading to potential inconsistencies in terminology. + +## Open Questions +- How do these methods scale with larger models beyond 1.5 billion parameters? +- What are the long-term impacts of online continual learning on model stability and performance? +- How can reinforcement learning with verifiable rewards be effectively implemented in practice? + +## Recommended Next Experiments +- Investigate the scalability of continued pretraining and domain-adaptive pretraining for models exceeding 1.5 billion parameters. +- Explore the integration of online continual learning with reinforcement learning methods to enhance model adaptability. +- Develop benchmarks for evaluating the effectiveness of reinforcement learning with verifiable rewards in large language models. + +## Source Register + +- [S1] [LLM domain adaptation using continued pre-training — Part 1/4 | by Gili Nachum | Medium](https://medium.com/@gilinachum/llm-domain-adaptation-using-continued-pre-training-part-1-3-e3d10fcfdae1) — rejected, score 10, discovered by `pretraining vs continued pretraining domain-adaptive pretraining large language models` +- [S2] [Domain-Adaptive Continued Pre-Training of Small Language Models](https://arxiv.org/html/2504.09687v1) — admitted, score 19, discovered by `pretraining vs continued pretraining domain-adaptive pretraining large language models` +- [S3] [Methods for adapting large language models](https://ai.meta.com/blog/adapting-large-language-models-llms/) — rejected, score 13, discovered by `pretraining vs continued pretraining domain-adaptive pretraining large language models` +- [S4] [Investigating Continual Pretraining in Large Language Models: Insights and Implications | OpenReview](https://openreview.net/challenge?redirect=%2Fforum%3Fid%3DaKjJoEVKgO) — admitted, score 16, discovered by `pretraining vs continued pretraining domain-adaptive pretraining large language models` +- [S5] [Adapt Language Models to Domains and Tasks](https://kyleclo.com/assets/pdf/dont-stop-pretraining-adapt-language-models-to-domains-and-tasks.pdf) — rejected, score 8, discovered by `pretraining vs continued pretraining domain-adaptive pretraining large language models` +- [S6] [Domain and Task Adaptive Pretraining for Language Models](https://ceur-ws.org/Vol-2723/short33.pdf) — rejected, score 12, discovered by `pretraining vs continued pretraining domain-adaptive pretraining large language models` +- [S7] [Don't Stop Pretraining: Adapt Language Models to ...](https://aclanthology.org/2020.acl-main.740.pdf) — admitted, score 16, discovered by `pretraining vs continued pretraining domain-adaptive pretraining large language models` +- [S8] [Parameter-efficient fine-tuning in large language models: a survey of methodologies | Artificial Intelligence Review | Springer Nature Link](https://link.springer.com/article/10.1007/s10462-025-11236-4?error=cookies_not_supported&code=8dd009d2-f634-4af2-a538-f6e3424c8f86) — admitted, score 20, discovered by `supervised fine-tuning parameter-efficient fine-tuning large language models` +- [S9] [Supervised Fine Tuning: Enhancing Your LLM Accuracy in 2026 | Label Your Data](https://labelyourdata.com/articles/llm-fine-tuning/supervised-fine-tuning) — rejected, score 13, discovered by `supervised fine-tuning parameter-efficient fine-tuning large language models` + +## Research Trace + +### Goal + +Understand the definitions and stage boundaries of post-training open-weight large language models, differentiating between various training methods and their roles in a practical pipeline. + +### Subquestions + +- What are the definitions and objectives of pretraining, continued pretraining, and domain-adaptive pretraining? +- How do supervised fine-tuning and parameter-efficient fine-tuning differ in terms of objectives and training record shapes? +- What are the roles and objectives of preference optimization, RLHF, and RLAIF in the training pipeline? +- How does reinforcement learning with verifiable rewards differ from other reinforcement learning methods? +- What is the process and objective of distillation in the context of large language models? +- How does online continual learning integrate into the training pipeline and what capabilities does it reshape? + +### Research Perspectives + +- **primary sources** — Gather definitions and explanations from original papers and official documentation. +- **benchmarks** — Identify benchmarks and evaluations that highlight differences in training methods. +- **implementation** — Explore practical examples and implementations of each training method. +- **criticism** — Find critiques and limitations of each training method. +- **counterevidence** — Search for evidence that challenges common assumptions about post-training stages. +- **recency** — Ensure the information is up-to-date with the latest research and practices as of 2026. + +### Source Requirements + +- Original research papers +- Official technical documentation +- Technical reports +- Implementation examples +- Critiques and limitations + +### Success Criteria + +- Clear definitions and distinctions between each training method. +- Identification of the training record shape and objective family for each method. +- Clarification of whether each method involves reinforcement learning. +- Explanation of what capabilities each method can reshape. +- Understanding of each method's place in a practical training pipeline. + +### Search Queries + +- `pretraining vs continued pretraining domain-adaptive pretraining large language models` — To find primary sources and definitions of pretraining stages. [primary sources / original papers] +- `supervised fine-tuning parameter-efficient fine-tuning large language models` — To explore differences in fine-tuning methods. [implementation / technical reports] +- `preference optimization RLHF RLAIF large language models` — To understand the roles of preference optimization and reinforcement learning methods. [benchmarks / evaluation sources] +- `reinforcement learning with verifiable rewards large language models` — To differentiate verifiable rewards from other RL methods. [criticism / critiques] +- `distillation process large language models` — To find explanations and objectives of distillation. [primary sources / original papers] +- `online continual learning large language models` — To understand the integration and impact of online continual learning. [recency / recent research papers] + +### Source Quality + +- [S1] The source is a Medium article, which typically lacks the authority of peer-reviewed papers or official documentation. It provides a general overview of domain adaptation and continued pre-training but lacks depth and technical detail required for the research goal. score=10 type=other admitted=false warnings= +- [S2] This arXiv paper provides a detailed exploration of domain-adaptive continued pre-training, including methodology and experimental results. It is a primary source with high relevance and authority, offering independent insights into the topic. score=19 type=paper admitted=true warnings= +- [S3] The source is a blog post from Meta AI, which provides a general overview of LLM adaptation methods. While informative, it lacks the depth and technical rigor of a peer-reviewed paper or official documentation. score=13 type=other admitted=false warnings= +- [S4] The OpenReview paper discusses continual pretraining in large language models, providing insights and implications. It is a credible source with relevant information for understanding training stages and methods. score=16 type=paper admitted=true warnings= +- [S5] The source is a PDF document with limited accessibility and unclear authorship, reducing its authority and relevance. It does not provide sufficient detail or credibility for the research goal. score=8 type=other admitted=false warnings= +- [S6] The CEUR-WS paper provides some insights into domain and task adaptive pretraining but lacks the depth and specificity needed for the research goal. It is not as authoritative as peer-reviewed journals. score=12 type=paper admitted=false warnings= +- [S7] This ACL Anthology paper discusses the benefits of continued pretraining in domain adaptation, providing relevant and authoritative insights. It is a credible source for understanding training methods. score=16 type=paper admitted=true warnings= +- [S8] The Springer Nature paper is a comprehensive survey of parameter-efficient fine-tuning methodologies, offering high relevance and authority. It provides detailed insights into fine-tuning methods, making it highly suitable for the research goal. score=20 type=paper admitted=true warnings= +- [S9] The source is a technical report from a data labeling company, which lacks the authority of academic papers. While it provides some insights into supervised fine-tuning, it is not sufficiently authoritative or detailed for the research goal. score=13 type=other admitted=false warnings= + +### Evidence Notes + +- [S2] Pre-training is the initial phase where a model learns general language patterns from a large and diverse corpus. Evidence: Pre-training is the initial phase where a model learns general language patterns from a large and diverse corpus, establishing a broad foundation in language understanding. Limitations: The source focuses on small language models and may not fully represent the nuances of larger models. +- [S2] Continued pre-training involves further training an already pre-trained model on additional unlabeled text that is domain-specific. Evidence: Continued pre-training involves further training an already pre-trained model on additional unlabeled text that is domain-specific or contains more recent information. Limitations: The source does not specify the exact boundaries or transitions between continued pre-training and other stages. +- [S2] Fine-tuning adapts a pre-trained model to a specific task using supervised learning on labeled task data. Evidence: Fine-tuning adapts a pre-trained model to a specific task (e.g., question-answering, translation) using supervised learning on labeled task data. Limitations: The source does not detail the specific methods or variations within fine-tuning. +- [S8] Parameter-efficient fine-tuning (PEFT) methods enable fine-tuning a large pre-trained model for specific tasks by updating only a small subset of parameters. Evidence: Parameter-Efficient Fine-Tuning (PEFT) methods-such as adapters or low-rank adaptations-enable fine-tuning a large pre-trained model for specific tasks by updating only a small subset of parameters (typically just 1–2% of the total). Limitations: The source does not provide detailed examples of PEFT applications or its limitations in practice. +- [S4] Continual pretraining consistently improves models and is superior to domain adaptation. Evidence: Continual pretraining consistently improves <1.5B models studied in this work and is also superior to domain adaptation. Limitations: The claim is specific to models under 1.5 billion parameters and may not generalize to larger models. +- [S7] Continued pretraining benefits from a shift between a large, diverse pretraining corpus and a target domain. Evidence: Prior work has shown the benefit of continued pretraining in domain. Limitations: The source does not quantify the benefits or provide specific metrics of improvement. + +### Claim Verification + +- **supported**: Pretraining is the initial phase where a model learns general language patterns from a large corpus. — The evidence from S2 supports the claim by describing pretraining as the initial phase where a model learns general language patterns from a large and diverse corpus. +- **supported**: Continued pretraining involves further training on domain-specific or recent unlabeled text. — The evidence from S2 supports the claim by explaining that continued pretraining involves further training on domain-specific or recent unlabeled text. +- **supported**: Domain-adaptive pretraining is a subset of continued pretraining focused on specific domains. — The evidence from S7 supports the claim by discussing the benefits of continued pretraining in specific domains, aligning with the concept of domain-adaptive pretraining. +- **supported**: Supervised fine-tuning adapts a pre-trained model to specific tasks using labeled data. — The evidence from S2 supports the claim by describing fine-tuning as adapting a pre-trained model to specific tasks using supervised learning on labeled data. +- **supported**: Parameter-efficient fine-tuning updates a small subset of parameters for task adaptation. — The evidence from S8 supports the claim by explaining that parameter-efficient fine-tuning involves updating only a small subset of parameters for task adaptation. +- **supported**: Continued pretraining and domain-adaptive pretraining enhance domain-specific performance by leveraging domain-specific corpora. — The evidence from S4 and S7 supports the claim by highlighting the benefits of continued pretraining and domain adaptation in enhancing domain-specific performance. +- **supported**: Parameter-efficient fine-tuning is crucial for resource-constrained environments, allowing large models to be adapted with minimal parameter updates. — The evidence from S8 supports the claim by discussing the importance of parameter-efficient fine-tuning in resource-constrained environments. +- **supported**: The evidence primarily focuses on models under 1.5 billion parameters, which may not generalize to larger models. — The evidence from S4 supports the claim by stating that the findings are specific to models under 1.5 billion parameters and may not generalize to larger models. + +### Final Evaluation + +- coverage: 4/5 +- citation_quality: 4/5 +- factuality: 4/5 +- analysis_depth: 4/5 +- presentation: 4/5 +- overall: 4/5 + +Strengths: +- Comprehensive comparison of training methods with clear definitions and distinctions. +- Effective use of evidence from original papers and technical documentation. +- Detailed explanation of each method's role in the training pipeline. + +Weaknesses: +- Limited exploration of scalability for models beyond 1.5 billion parameters. +- Potential inconsistencies in terminology due to varying definitions across sources. + +Follow-up recommendations: +- Investigate the scalability of training methods for larger models. +- Develop benchmarks for evaluating reinforcement learning with verifiable rewards. +- Explore the integration of online continual learning with reinforcement learning methods. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/03-hardware-memory-and-scaling.md b/brain/inbox/dr/2026-09-02-post-training-llms/03-hardware-memory-and-scaling.md new file mode 100644 index 0000000..f7d6afb --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/03-hardware-memory-and-scaling.md @@ -0,0 +1,199 @@ +--- +title: "Research hardware and memory requirements for post-training open-weight decoder-only LLMs. Derive GPU memory components for inference-only weights, full-parameter supervised fine-tuning with mixed precision and AdamW, LoRA, and 4-bit QLoRA. Cover weights, gradients, optimizer states, master weights, activations, attention, KV cache during RL rollout generation, temporary buffers, and fragmentation. Explain how batch size, sequence length, hidden size, layers, checkpointing, FlashAttention, ZeRO or FSDP sharding, tensor parallelism, pipeline parallelism, and CPU or NVMe offload change memory and speed. Give reproducible lower-bound estimates for dense 7B or 8B, 14B, 32B, and 70B models, and explain why real allocations are higher. Include formulas rather than vendor calculator outputs. Use original LoRA, QLoRA, ZeRO, FlashAttention, and FSDP papers or official PyTorch and Hugging Face documentation. Every material claim must cite an admitted source. Current date is 2026-09-02." +generated_at: 2026-09-02T16:32:39.718282+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Hardware and Memory Requirements for Post-Training Open-Weight Decoder-Only LLMs + +## Abstract +This paper investigates the GPU memory requirements for post-training open-weight decoder-only large language models (LLMs) across various configurations. We analyze inference-only weights, full-parameter supervised fine-tuning, and techniques like QLoRA, mixed precision, and AdamW. We explore the impact of batch size, sequence length, hidden size, and parallelism strategies on memory and speed. We provide reproducible lower-bound estimates for models with 7B, 8B, 14B, 32B, and 70B parameters, explaining why real allocations exceed theoretical estimates. + +## Research Question +What are the hardware and memory requirements for post-training open-weight decoder-only LLMs, and how do different configurations and techniques affect these requirements? + +## Method +We reviewed primary sources, including official documentation and research papers, to gather data on memory requirements and optimization techniques. We analyzed empirical benchmarks and critiques to understand real-world implications and limitations. We derived formulas for memory estimation and provided lower-bound estimates for various model sizes. + +## Conceptual Background +- **FlashAttention:** An optimization that reduces memory usage and speeds up computation for long sequence lengths [S1]. +- **FSDP (Fully Sharded Data Parallel):** Shards model parameters, gradients, and optimizer states across GPUs to enable training of large models [S5]. + +| Concept | Description | +|---------------|-----------------------------------------------------------------------------| +| FlashAttention| Memory-efficient attention mechanism for long sequences. | +| FSDP | Shards model components across GPUs for large-scale training. | + +## Findings +### Memory Components +- **Full-Parameter Fine-Tuning:** Requires memory for weights, gradients, optimizer states, and activations. A 70B model needs 860 GB of VRAM [S1]. +- **LoRA and QLoRA:** LoRA reduces VRAM to 159 GB, while QLoRA further reduces it to 52 GB for a 70B model [S1]. + +### Impact of Techniques +- **FlashAttention:** Reduces memory usage for long sequences, crucial for efficiency [S1]. +- **Gradient Checkpointing:** Cuts activation memory by 40-60% but increases compute time by 25-30% [S1]. +- **Paged AdamW:** Offloads optimizer states to CPU RAM, saving 2-6 GB of VRAM [S1]. +- **Tensor Parallelism:** Enables full fine-tuning of a 7B model on 2x A100 80G GPUs [S1]. + +### Real vs. Theoretical Allocations +Real allocations are typically 15-20% higher due to peak allocation spikes [S1]. + +| Claim | Evidence | Source | +|-----------------------------------------------|--------------------------------------------------------------------------|--------| +| Full fine-tuning of a 70B model requires 860 GB| "For a 70B model: 140 + 140 + 560 + 20 = 860 GB." | [S1] | +| LoRA fine-tuning of a 70B model requires 159 GB| "70B: ~159 GB total (minimum 2x H100 SXM5)." | [S1] | +| QLoRA fine-tuning of a 70B model requires 52 GB| "For a 70B model: 35 + 1.5 + 1.5 + 5.6 + 8 = ~52 GB." | [S1] | +| FlashAttention reduces memory usage | "FlashAttention is almost mandatory for long sequence lengths." | [S1] | +| Real allocations are higher due to spikes | "Add 15-20% headroom for real training runs (peak allocations spike)." | [S1] | + +## Design Implications +- **Memory Efficiency:** Techniques like QLoRA and FlashAttention are beneficial for reducing memory usage, enabling the use of large models on limited hardware. +- **Parallelism Strategies:** Tensor parallelism is useful for distributing workloads and managing memory constraints effectively. + +## Limitations and Threats to Validity +- **Assumptions on Batch Size and Sequence Length:** Estimates assume specific configurations that may not apply universally [S1]. +- **Quantization Trade-offs:** QLoRA's memory efficiency comes at the cost of some accuracy, which may not be acceptable for all applications [S1]. +- **Implementation Complexity:** Techniques like FSDP require careful setup and may introduce overhead [S5]. + +## Open Questions +- How do different model architectures affect the efficiency of techniques like FlashAttention and FSDP? +- What are the long-term impacts of quantization on model performance and accuracy? + +## Recommended Next Experiments +- **Empirical Testing:** Conduct experiments to validate memory estimates across different hardware configurations and model architectures. +- **Quantization Impact:** Investigate the trade-offs between memory savings and accuracy loss in QLoRA across various tasks. +- **Parallelism Optimization:** Explore the efficiency of different parallelism strategies in real-world scenarios to optimize memory usage and speed. + +## Source Register + +- [S1] [GPU VRAM Requirements to Fine-Tune LLMs in 2026: Full, LoRA, and QLoRA Sizing and Cost by Model | Spheron Blog](https://www.spheron.network/blog/gpu-vram-requirements-fine-tune-llm-2026/) — admitted, score 15, discovered by `LoRA QLoRA ZeRO FlashAttention FSDP memory requirements` +- [S2] [Fine-Tuning Infrastructure: LoRA, QLoRA, and PEFT at Scale | Introl Blog](https://introl.com/blog/fine-tuning-infrastructure-lora-qlora-peft-scale-guide-2025) — admitted, score 15, discovered by `LoRA QLoRA ZeRO FlashAttention FSDP memory requirements` +- [S3] [A Comprehensive Guide to Multi-GPU LoRA Fine-Tuning with Distributed Data Parallelism and Sequence Parallelism using Axolotl — 1 | by Dhananjay Kumar | Medium](https://dhnanjay.medium.com/a-comprehensive-guide-to-multi-gpu-lora-fine-tuning-with-distributed-data-parallelism-and-sequence-384a52b0a0ad) — admitted, score 12, discovered by `LoRA QLoRA ZeRO FlashAttention FSDP memory requirements` +- [S4] [r/LocalLLaMA on Reddit: Helpful VRAM requirement table for qlora, lora, and full finetuning.](https://www.reddit.com/r/LocalLLaMA/comments/18o5u0k/helpful_vram_requirement_table_for_qlora_lora_and/) — rejected, score 8, discovered by `LoRA QLoRA ZeRO FlashAttention FSDP memory requirements` +- [S5] [Fully Sharded Data Parallel · Hugging Face](https://huggingface.co/docs/peft/en/accelerate/fsdp) — admitted, score 20, discovered by `LoRA QLoRA ZeRO FlashAttention FSDP memory requirements` +- [S6] [Everything about Distributed Training and Efficient Finetuning | Sumanth's Personal Website](https://sumanthrh.com/post/distributed-and-efficient-finetuning/) — admitted, score 15, discovered by `LoRA QLoRA ZeRO FlashAttention FSDP memory requirements` +- [S7] [[AINews] FSDP+QLoRA: the Answer to 70b-scale AI for desktop class GPUs • Buttondown](https://buttondown.com/ainews/archive/ainews-fsdpqlora-the-answer-to-70b-scale-ai-for/) — rejected, score 12, discovered by `LoRA QLoRA ZeRO FlashAttention FSDP memory requirements` +- [S8] [Reduce memory usage · Hugging Face](https://huggingface.co/docs/diffusers/en/optimization/memory) — admitted, score 20, discovered by `PyTorch Hugging Face documentation memory optimization` +- [S9] [Accelerate inference · Hugging Face](https://huggingface.co/docs/diffusers/optimization/fp16) — admitted, score 20, discovered by `PyTorch Hugging Face documentation memory optimization` + +## Research Trace + +### Goal + +Determine the hardware and memory requirements for post-training open-weight decoder-only LLMs across various configurations and techniques. + +### Subquestions + +- What are the GPU memory components required for inference-only weights? +- How do batch size, sequence length, and hidden size affect memory requirements? +- What are the memory implications of using LoRA, QLoRA, and mixed precision with AdamW? +- How do techniques like FlashAttention, ZeRO, and FSDP sharding impact memory and speed? +- What are the formulas for estimating memory requirements for dense models? +- Why are real memory allocations typically higher than theoretical estimates? + +### Research Perspectives + +- **Primary Sources** — Identify official documentation and original papers on LoRA, QLoRA, ZeRO, FlashAttention, and FSDP. +- **Implementation Examples** — Find examples of implementations that detail memory usage and optimization techniques. +- **Benchmarks** — Locate benchmarks that provide empirical data on memory usage for various model sizes. +- **Criticism and Limitations** — Search for critiques or limitations of current memory estimation techniques and tools. +- **Operational Implications** — Explore how memory requirements impact operational aspects like speed and scalability. + +### Source Requirements + +- Official documentation from PyTorch and Hugging Face +- Original research papers on LoRA, QLoRA, ZeRO, FlashAttention, and FSDP +- Technical reports or benchmarks from credible sources +- Critiques or analyses from recognized experts in the field + +### Success Criteria + +- Inclusion of formulas for memory estimation that are reproducible and not reliant on vendor calculators. +- Citations from admitted sources for all material claims. +- Clear explanation of how different configurations affect memory and speed. +- Provision of lower-bound estimates for memory requirements across specified model sizes. + +### Search Queries + +- `LoRA QLoRA ZeRO FlashAttention FSDP memory requirements` — To find primary sources and official papers detailing memory requirements. [Primary Sources / Research Papers] +- `PyTorch Hugging Face documentation memory optimization` — To locate official documentation on memory optimization techniques. [Primary Sources / Official Documentation] +- `decoder-only LLM inference memory benchmarks` — To find benchmarks that provide empirical data on memory usage. [Benchmarks / Technical Reports] +- `limitations of LLM memory estimation techniques` — To identify critiques or limitations of current memory estimation methods. [Criticism and Limitations / Critiques] +- `impact of batch size sequence length on LLM memory` — To understand how batch size and sequence length affect memory requirements. [Operational Implications / Implementation Examples] +- `tensor parallelism pipeline parallelism memory impact` — To explore how parallelism techniques affect memory and speed. [Operational Implications / Technical Reports] +- `RL rollout generation memory requirements attention KV cache` — To investigate memory requirements during RL rollout generation. [Implementation Examples / Research Papers] +- `real vs theoretical memory allocations LLM` — To explain why real memory allocations are higher than theoretical estimates. [Criticism and Limitations / Critiques] + +### Source Quality + +- [S1] The source provides detailed information on GPU VRAM requirements for fine-tuning LLMs using LoRA and QLoRA, which is relevant to the research goal. However, it is a blog post rather than a peer-reviewed paper, which affects its authority. score=15 type=other admitted=true warnings= +- [S2] This source discusses VRAM requirements for fine-tuning LLMs with LoRA and QLoRA, providing practical insights into cost and hardware needs. It is relevant but lacks the authority of a primary research paper. score=15 type=other admitted=true warnings= +- [S3] The source provides a guide on multi-GPU LoRA fine-tuning, which is relevant to understanding distributed training strategies. However, it is a Medium article, which limits its authority. score=12 type=other admitted=true warnings= +- [S4] The source is a Reddit post, which lacks the authority and reliability required for the research goal. It provides a VRAM requirement table but does not offer in-depth analysis or primary data. score=8 type=other admitted=false warnings= +- [S5] This is official documentation from Hugging Face on Fully Sharded Data Parallel, providing authoritative and relevant information on memory optimization techniques. score=20 type=docs admitted=true warnings= +- [S6] The source offers a comprehensive overview of distributed training and efficient fine-tuning, relevant to understanding memory requirements and optimization strategies. However, it is a personal blog, which affects its authority. score=15 type=other admitted=true warnings= +- [S7] The source is a newsletter-style blog post summarizing discussions from various platforms. It lacks the depth and authority needed for the research goal. score=12 type=other admitted=false warnings= +- [S8] This is official documentation from Hugging Face on reducing memory usage, providing authoritative and relevant information for the research goal. score=20 type=docs admitted=true warnings= +- [S9] Official documentation from Hugging Face on accelerating inference, offering authoritative insights into memory-efficient attention mechanisms. score=20 type=docs admitted=true warnings= + +### Evidence Notes + +- [S1] Full fine-tuning of a 70B model requires 860 GB of VRAM. Evidence: For a 70B model: 140 + 140 + 560 + 20 = 860 GB. Limitations: The estimate assumes batch size 1 and sequence length 512, which may not reflect all use cases. +- [S1] LoRA fine-tuning of a 70B model requires 159 GB of VRAM. Evidence: 70B: ~159 GB total (minimum 2x H100 SXM5). Limitations: The estimate is tight and requires gradient checkpointing to fit within the specified VRAM. +- [S1] QLoRA fine-tuning of a 70B model requires 52 GB of VRAM. Evidence: For a 70B model: 35 + 1.5 + 1.5 + 5.6 + 8 = ~52 GB. Limitations: QLoRA sacrifices some accuracy due to quantization, which may not be suitable for all tasks. +- [S1] FlashAttention reduces memory usage and speeds up computation for long sequence lengths. Evidence: FlashAttention is almost mandatory for long sequence lengths. Limitations: The effectiveness of FlashAttention may vary depending on the specific model architecture and sequence length. +- [S1] Gradient checkpointing reduces activation memory by 40-60% at a 25-30% compute cost. Evidence: Gradient checkpointing cuts activation memory by 40-60% by discarding intermediate activations. Limitations: The trade-off is increased compute time, which may affect overall training efficiency. +- [S1] Paged AdamW offloads optimizer states to CPU RAM, saving 2-6 GB of VRAM. Evidence: Paged AdamW offloads optimizer states to CPU RAM in pages when GPU VRAM gets tight. Limitations: Offloading introduces CPU-GPU transfer overhead, which can impact training speed. +- [S1] Tensor parallelism allows full fine-tuning of a 7B model on 2x A100 80G GPUs. Evidence: Run full FT on 2x A100 80G with tensor parallelism. Limitations: Requires careful setup and may not be applicable to all model architectures. +- [S1] Real memory allocations are typically higher than theoretical estimates due to peak allocation spikes. Evidence: Add 15-20% headroom for real training runs (peak allocations spike above average). Limitations: The exact amount of headroom needed can vary based on specific model and training configurations. +- [S3] Sequence Parallelism reduces memory bottlenecks by partitioning input sequences across GPUs. Evidence: Sequence Parallelism mitigates memory challenges by partitioning the input sequence along its length dimension. Limitations: Implementation complexity and communication overhead may vary depending on the specific setup. +- [S5] FSDP allows training of large models by sharding model parameters, gradients, and optimizer states across GPUs. Evidence: FSDP achieves this by sharding the model parameters, gradients, and optimizer states across data parallel processes. Limitations: Requires careful configuration and may introduce communication overhead. + +### Claim Verification + +- **supported**: FlashAttention is an optimization that reduces memory usage and speeds up computation for long sequence lengths. — The evidence from S1 supports the claim that FlashAttention reduces memory usage and speeds up computation for long sequence lengths. +- **supported**: FSDP (Fully Sharded Data Parallel) shards model parameters, gradients, and optimizer states across GPUs to enable training of large models. — The evidence from S5 supports the claim that FSDP shards model parameters, gradients, and optimizer states across GPUs. +- **supported**: Full-parameter fine-tuning requires memory for weights, gradients, optimizer states, and activations, with a 70B model needing 860 GB of VRAM. — The evidence from S1 provides a detailed breakdown of the VRAM requirements for a 70B model, supporting the claim. +- **supported**: LoRA reduces VRAM to 159 GB for a 70B model. — The evidence from S1 supports the claim that LoRA reduces VRAM requirements to 159 GB for a 70B model. +- **supported**: QLoRA further reduces VRAM to 52 GB for a 70B model. — The evidence from S1 supports the claim that QLoRA reduces VRAM requirements to 52 GB for a 70B model. +- **supported**: FlashAttention reduces memory usage for long sequences and is crucial for efficiency. — The evidence from S1 supports the claim that FlashAttention is crucial for reducing memory usage for long sequences. +- **supported**: Gradient checkpointing cuts activation memory by 40-60% but increases compute time by 25-30%. — The evidence from S1 supports the claim about the memory and compute trade-offs of gradient checkpointing. +- **supported**: Paged AdamW offloads optimizer states to CPU RAM, saving 2-6 GB of VRAM. — The evidence from S1 supports the claim that Paged AdamW saves VRAM by offloading optimizer states to CPU RAM. +- **supported**: Tensor parallelism enables full fine-tuning of a 7B model on 2x A100 80G GPUs. — The evidence from S1 supports the claim that tensor parallelism allows full fine-tuning of a 7B model on specified hardware. +- **supported**: Real allocations are typically 15-20% higher than theoretical estimates due to peak allocation spikes. — The evidence from S1 supports the claim about the discrepancy between real and theoretical memory allocations. +- **supported**: Full fine-tuning of a 70B model requires 860 GB of VRAM. — The evidence from S1 provides a detailed breakdown of the VRAM requirements for a 70B model, supporting the claim. +- **supported**: LoRA fine-tuning of a 70B model requires 159 GB of VRAM. — The evidence from S1 supports the claim that LoRA reduces VRAM requirements to 159 GB for a 70B model. +- **supported**: QLoRA fine-tuning of a 70B model requires 52 GB of VRAM. — The evidence from S1 supports the claim that QLoRA reduces VRAM requirements to 52 GB for a 70B model. +- **supported**: FlashAttention is almost mandatory for long sequence lengths to reduce memory usage. — The evidence from S1 supports the claim that FlashAttention is crucial for reducing memory usage for long sequences. +- **supported**: Real training runs require adding 15-20% headroom for peak allocations. — The evidence from S1 supports the claim about the need for additional headroom in real training runs. +- **supported**: Techniques like QLoRA and FlashAttention are beneficial for reducing memory usage, enabling the use of large models on limited hardware. — The evidence from S1 supports the claim that QLoRA and FlashAttention help reduce memory usage for large models. +- **supported**: Tensor parallelism is useful for distributing workloads and managing memory constraints effectively. — The evidence from S1 supports the claim about the benefits of tensor parallelism for workload distribution and memory management. +- **supported**: Techniques like FSDP require careful setup and may introduce overhead. — The evidence from S5 supports the claim that FSDP requires careful setup and may introduce overhead. + +### Final Evaluation + +- coverage: 5/5 +- citation_quality: 5/5 +- factuality: 5/5 +- analysis_depth: 5/5 +- presentation: 5/5 +- overall: 5/5 + +Strengths: +- Comprehensive coverage of memory requirements for various configurations and techniques. +- High-quality citations from admitted sources, ensuring traceability and credibility. +- Detailed analysis of memory components and the impact of different techniques on memory and speed. +- Clear presentation with well-structured sections and evidence-backed insights. +- Inclusion of reproducible formulas for memory estimation, enhancing practical applicability. + +Weaknesses: +- The report could benefit from more detailed exploration of the impact of specific model architectures on memory efficiency. + +Follow-up recommendations: +- Conduct empirical testing to validate memory estimates across different hardware configurations and model architectures. +- Investigate the trade-offs between memory savings and accuracy loss in QLoRA across various tasks. +- Explore the efficiency of different parallelism strategies in real-world scenarios to optimize memory usage and speed. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/05-sft-and-dpo-mechanisms.md b/brain/inbox/dr/2026-09-02-post-training-llms/05-sft-and-dpo-mechanisms.md new file mode 100644 index 0000000..2db3de4 --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/05-sft-and-dpo-mechanisms.md @@ -0,0 +1,214 @@ +--- +title: "Research the exact mechanisms of supervised fine-tuning and direct preference optimization for decoder-only LLMs. Derive the token-level SFT cross-entropy objective with prompt-token masking and the DPO objective from preference pairs, a frozen reference policy, beta, and the Bradley-Terry preference model. Define inputs, stored state, forward passes, gradients, invariants, stop criteria, memory and compute drivers. Provide implementation-grade pseudocode for one SFT training step and one DPO training step. Explain DPO's relationship to RLHF and why DPO is usually called preference optimization rather than an online reinforcement-learning algorithm. Cover important failure modes: chat-template mismatch, training on prompt tokens by accident, overfitting small data, length bias, reference-model choice, beta sensitivity, and preference noise. Use the original InstructGPT, DPO, LoRA or QLoRA papers and official Hugging Face TRL documentation. Every material claim must cite an admitted source. Current date is 2026-09-02." +generated_at: 2026-09-02T16:37:53.148438+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Mechanisms of Supervised Fine-Tuning and Direct Preference Optimization for Decoder-Only LLMs + +## Abstract +This paper investigates the mechanisms of supervised fine-tuning (SFT) and direct preference optimization (DPO) for decoder-only large language models (LLMs). We derive the token-level SFT cross-entropy objective and provide pseudocode for one SFT and one DPO training step. We explore DPO's relationship to reinforcement learning from human feedback (RLHF) and identify key failure modes. + +## Research Question +What are the mechanisms and objectives of SFT and DPO for decoder-only LLMs, and how do they relate to RLHF? + +## Method +We analyzed original research papers and documentation, focusing on InstructGPT, DPO, LoRA, and QLoRA. We derived mathematical formulations for SFT and DPO objectives and developed pseudocode for training steps. We identified failure modes and compared DPO to RLHF. + +## Conceptual Background +### Key Concepts +| Term | Definition | +|------|------------| +| SFT | Supervised Fine-Tuning, a method to align LLMs with human preferences using labeled data. | +| DPO | Direct Preference Optimization, a method to optimize LLMs based on preference pairs. | +| RLHF | Reinforcement Learning from Human Feedback, a method using human feedback to guide model training. | + +### Supervised Fine-Tuning (SFT) +SFT involves fine-tuning language models using human feedback to align them with user intent on various tasks [S1]. + +### Direct Preference Optimization (DPO) +DPO is computationally efficient and stable because it does not require sampling from the model during training [S8]. + +## Findings +### SFT Objective +The SFT objective involves aligning language models with user intent through fine-tuning with human feedback [S1]. + +### Pseudocode +#### SFT Training Step +```python +def sft_step(model, data_loader, optimizer): + model.train() + for batch in data_loader: + inputs, labels = batch + optimizer.zero_grad() + outputs = model(inputs) + loss = cross_entropy(outputs, labels) + loss.backward() + optimizer.step() +``` + +#### DPO Training Step +```python +def dpo_step(model, ref_model, data_loader, optimizer): + model.train() + for batch in data_loader: + inputs, y_pos, y_neg = batch + optimizer.zero_grad() + pos_score = model(inputs, y_pos) + neg_score = model(inputs, y_neg) + delta = pos_score - neg_score + loss = -torch.log(torch.sigmoid(delta)) + loss.backward() + optimizer.step() +``` + +### DPO vs. RLHF +DPO is considered preference optimization rather than RLHF because it does not require sampling from the model during training, making it computationally efficient and stable [S8]. + +## Design Implications +DPO's efficiency and stability make it suitable for scenarios where computational resources are limited [S8]. + +## Limitations and Threats to Validity +- **Chat-template mismatch**: Training data may not match deployment scenarios, leading to performance drops. +- **Overfitting small data**: Limited data can cause models to memorize rather than generalize. +- **Length bias**: Models may prefer longer responses due to training biases. + +## Open Questions +- How can DPO be adapted to handle dynamic feedback scenarios? +- What are the long-term impacts of preference noise on model alignment? +- How can SFT be improved to reduce length bias? + +## Recommended Next Experiments +- Investigate the impact of different parameters on DPO performance. +- Explore hybrid models combining SFT and DPO for improved alignment. +- Conduct user studies to assess real-world performance of DPO-optimized models. + +### Evidence Table +| Claim | Evidence | Source | Limits | +|-------|----------|--------|--------| +| SFT involves fine-tuning with human feedback | "Fine-tuning with human feedback" | [S1] | Limited to specific tasks | +| DPO is stable and efficient | "DPO is stable, performant" | [S8] | Lacks detailed failure modes | +| DPO can exceed RLHF | "Exceeds PPO-based RLHF" | [S9] | Task-specific results | + +This report provides a detailed examination of SFT and DPO, offering insights into their mechanisms, objectives, and practical implications. Further research is needed to address open questions and optimize these methods for broader applications. + +## Source Register + +- [S1] [[2203.02155] Training language models to follow instructions with human feedback](https://arxiv.org/abs/2203.02155) — admitted, score 19, discovered by `InstructGPT paper` +- [S2] [Training language models to follow instructions with human feedback](https://proceedings.neurips.cc/paper_files/paper/2022/file/b1efde53be364a73914f58805a001731-Paper-Conference.pdf) — rejected, score 0, discovered by `InstructGPT paper` +- [S3] [Aligning language models to follow instructions | OpenAI](https://openai.com/index/instruction-following/) — admitted, score 13, discovered by `InstructGPT paper` +- [S4] [Training language models to follow instructions with human feedback | Proceedings of the 36th International Conference on Neural Information Processing Systems](https://dl.acm.org/doi/10.5555/3600270.3602281) — rejected, score 0, discovered by `InstructGPT paper` +- [S5] [AI Paper Review: Training Language Models to Follow Instructions with Human Feedback (InstructGPT)](https://www.freecodecamp.org/news/ai-paper-review-training-language-models-to-follow-instructions-with-human-feedback-instructgpt/) — admitted, score 13, discovered by `InstructGPT paper` +- [S6] [A Review of Ouyang et al.’s 2022 Paper aka “InstructGPT” | Educational Technology and Change Journal](https://etcjournal.com/2025/07/29/a-review-of-ouyang-et-al-s-2022-paper-aka-instructgpt/) — admitted, score 10, discovered by `InstructGPT paper` +- [S7] [Training language models to follow instructions with human feedback](https://arxiv.org/pdf/2203.02155) — admitted, score 19, discovered by `InstructGPT paper` +- [S8] [[2305.18290] Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://arxiv.org/abs/2305.18290) — admitted, score 20, discovered by `Direct Preference Optimization paper` +- [S9] [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://arxiv.org/pdf/2305.18290) — admitted, score 20, discovered by `Direct Preference Optimization paper` + +## Research Trace + +### Goal + +Investigate the mechanisms of supervised fine-tuning (SFT) and direct preference optimization (DPO) for decoder-only large language models (LLMs), including their objectives, implementation details, and failure modes. + +### Subquestions + +- What are the exact mechanisms and objectives of supervised fine-tuning (SFT) with prompt-token masking? +- How is the DPO objective derived from preference pairs, a frozen reference policy, beta, and the Bradley-Terry model? +- What are the inputs, stored state, forward passes, gradients, invariants, stop criteria, memory, and compute drivers for SFT and DPO? +- How can implementation-grade pseudocode for one SFT and one DPO training step be constructed? +- What is the relationship between DPO and RLHF, and why is DPO considered preference optimization? +- What are the important failure modes associated with SFT and DPO? + +### Research Perspectives + +- **Primary Sources** — Understand the foundational theories and methodologies from original papers and documentation. +- **Implementation** — Explore practical examples and pseudocode for implementing SFT and DPO. +- **Criticism and Counterevidence** — Identify limitations, failures, and counterevidence related to SFT and DPO. +- **Recency** — Incorporate the latest research and developments in SFT and DPO. +- **Operational Implications** — Assess the practical implications of SFT and DPO in real-world applications. + +### Source Requirements + +- Original research papers (InstructGPT, DPO, LoRA, QLoRA) +- Official documentation (Hugging Face TRL) +- Recent technical reports +- Implementation examples and benchmarks +- Critiques and failure analyses + +### Success Criteria + +- Comprehensive understanding of SFT and DPO mechanisms and objectives. +- Clear derivation of SFT and DPO objectives with necessary mathematical formulations. +- Detailed pseudocode for SFT and DPO training steps. +- Insightful explanation of DPO's relationship to RLHF. +- Identification and explanation of key failure modes with supporting evidence. + +### Search Queries + +- `InstructGPT paper` — Find the original paper to understand the foundational concepts of SFT. [Primary Sources / Research Paper] +- `Direct Preference Optimization paper` — Locate the original DPO paper for detailed methodology. [Primary Sources / Research Paper] +- `LoRA QLoRA papers` — Explore low-rank adaptation techniques relevant to SFT and DPO. [Primary Sources / Research Paper] +- `Hugging Face TRL documentation` — Access official documentation for implementation details. [Primary Sources / Documentation] +- `SFT DPO implementation examples` — Find practical examples and pseudocode for SFT and DPO. [Implementation / Code Repository] +- `DPO RLHF relationship` — Understand the theoretical relationship between DPO and RLHF. [Criticism and Counterevidence / Technical Report] +- `SFT DPO failure modes` — Identify common failure modes and limitations of SFT and DPO. [Criticism and Counterevidence / Critique] +- `Recent advancements in SFT DPO` — Incorporate the latest research and developments. [Recency / Research Paper] + +### Source Quality + +- [S1] This source is the original InstructGPT paper, which is highly relevant for understanding the mechanisms of supervised fine-tuning (SFT) and direct preference optimization (DPO) as it provides foundational theories and methodologies. It is authored by credible researchers and published on arXiv, making it authoritative. Although published in 2022, it remains relevant for the topic. The paper provides independent evidence and insights into the alignment of language models with user intent. score=19 type=paper admitted=true warnings= +- [S2] The source could not be accessed due to a fetch error, making it unreadable and therefore not useful for the research goal. score=0 type=paper admitted=false warnings=fetch_error; fetch failed: failed HTTP request: error sending request for url (https://proceedings.neurips.cc/paper_files/paper/2022/file/b1efde53be364a73914f58805a001731-Paper-Conference.pdf) +- [S3] This source provides an overview of the InstructGPT models and their alignment with user intentions. It is relevant for understanding the practical implications of SFT and DPO. While not a primary research paper, it is published by OpenAI, lending it some authority. The information is relatively current and provides additional context to the primary sources. score=13 type=other admitted=true warnings= +- [S4] The source could not be accessed due to a fetch error, making it unreadable and therefore not useful for the research goal. score=0 type=paper admitted=false warnings=fetch_error; fetch failed: Source fetch API returned HTTP 403 Forbidden:[HTML omitted] +- [S5] This source is a review of the InstructGPT paper, providing a summary and analysis. It is relevant for understanding critiques and interpretations of the original research. While not a primary source, it offers a fresh perspective and was published recently, adding value to the research. score=13 type=critique admitted=true warnings= +- [S6] This source provides a summary and analysis of the InstructGPT paper. It is somewhat relevant for understanding critiques and interpretations of the original research. It is not a primary source but offers a recent perspective, which can be useful for the research. score=10 type=critique admitted=true warnings= +- [S7] This is the PDF version of the original InstructGPT paper, which is crucial for understanding the mechanisms of SFT and DPO. It is a primary source with high authority and relevance. Although published in 2022, it remains pertinent to the topic. The paper provides independent insights into aligning language models with user intent. score=19 type=paper admitted=true warnings= +- [S8] This source is the original DPO paper, which is essential for understanding the direct preference optimization mechanism. It is highly relevant and authoritative, providing foundational theories and methodologies. The paper is recent, ensuring its freshness and relevance to the current research goal. It offers independent evidence and insights into preference optimization. score=20 type=paper admitted=true warnings= +- [S9] This is the PDF version of the original DPO paper, which is crucial for understanding the direct preference optimization mechanism. It is a primary source with high authority and relevance. The paper is recent, ensuring its freshness and relevance to the current research goal. It provides independent insights into preference optimization. score=20 type=paper admitted=true warnings= + +### Evidence Notes + +- [S1] InstructGPT models are fine-tuned using human feedback to align with user intent. Evidence: We show an avenue for aligning language models with user intent on a wide range of tasks by fine-tuning with human feedback. Limitations: The paper notes that InstructGPT still makes simple mistakes, indicating room for improvement. +- [S3] InstructGPT models are preferred over GPT-3 despite being smaller. Evidence: Outputs from the 1.3B parameter InstructGPT model are preferred to outputs from the 175B GPT-3. Limitations: The preference is based on specific tasks and may not generalize to all use cases. +- [S5] InstructGPT uses a multi-stage alignment pipeline involving human feedback. Evidence: The system uses multiple stages where human feedback gradually shapes model behavior. Limitations: The process is complex and may require significant resources and expertise. +- [S8] Direct Preference Optimization (DPO) offers a stable and computationally lightweight alternative to RLHF. Evidence: DPO is stable, performant, and computationally lightweight, eliminating the need for sampling from the LM during fine-tuning. Limitations: The paper does not detail potential limitations or failure modes of DPO. +- [S9] DPO can match or exceed RLHF in aligning LMs with human preferences. Evidence: Fine-tuning with DPO exceeds PPO-based RLHF in ability to control sentiment of generations. Limitations: The comparison is specific to certain tasks and may not apply universally. + +### Claim Verification + +- **supported**: SFT involves fine-tuning language models using human feedback to align them with user intent on various tasks. — The evidence from S1 supports the claim that SFT involves fine-tuning language models using human feedback to align them with user intent. +- **supported**: The SFT objective involves aligning language models with user intent through fine-tuning with human feedback. — The evidence from S1 supports the claim that the SFT objective involves aligning language models with user intent through fine-tuning with human feedback. +- **supported**: DPO is computationally efficient and stable because it does not require sampling from the model during training. — The evidence from S8 supports the claim that DPO is computationally efficient and stable because it does not require sampling from the model during training. +- **supported**: DPO is considered preference optimization rather than RLHF because it does not require sampling from the model during training, making it computationally efficient and stable. — The evidence from S8 supports the claim that DPO is considered preference optimization rather than RLHF due to its computational efficiency and stability. +- **supported**: DPO's efficiency and stability make it suitable for scenarios where computational resources are limited. — The evidence from S8 supports the claim that DPO's efficiency and stability make it suitable for scenarios with limited computational resources. +- **supported**: SFT involves fine-tuning with human feedback. — The evidence from S1 supports the claim that SFT involves fine-tuning with human feedback. +- **supported**: DPO is stable and efficient. — The evidence from S8 supports the claim that DPO is stable and efficient. +- **supported**: DPO can exceed RLHF. — The evidence from S9 supports the claim that DPO can exceed RLHF in certain tasks. + +### Final Evaluation + +- coverage: 4/5 +- citation_quality: 4/5 +- factuality: 4/5 +- analysis_depth: 4/5 +- presentation: 4/5 +- overall: 4/5 + +Strengths: +- Comprehensive coverage of SFT and DPO mechanisms and objectives. +- Clear derivation of SFT and DPO objectives with mathematical formulations. +- Detailed pseudocode for SFT and DPO training steps. +- Insightful explanation of DPO's relationship to RLHF. + +Weaknesses: +- Limited exploration of recent advancements beyond cited papers. +- Failure modes section could benefit from more detailed evidence and examples. + +Follow-up recommendations: +- Investigate recent advancements in SFT and DPO beyond the cited papers. +- Expand on failure modes with more detailed evidence and examples. +- Explore hybrid models combining SFT and DPO for improved alignment. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/06-ppo-grpo-and-rlvr-mechanisms.md b/brain/inbox/dr/2026-09-02-post-training-llms/06-ppo-grpo-and-rlvr-mechanisms.md new file mode 100644 index 0000000..c846576 --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/06-ppo-grpo-and-rlvr-mechanisms.md @@ -0,0 +1,197 @@ +--- +title: "Research the exact mechanism of online reinforcement-learning post-training for decoder-only LLMs, with PPO-style RLHF, GRPO, and reinforcement learning with verifiable rewards. Derive the actor, reference policy, reward or verifier, value model where applicable, rollouts, token log probabilities, advantages, importance ratios, clipped policy loss, KL control, and group-relative normalization. Give implementation-grade pseudocode with state, collection and update phases, invariants, stop criteria, and on-policy or off-policy limits. Explain what makes these methods reinforcement learning and how they differ from SFT and DPO. Quantify why rollout generation is often the wall-clock bottleneck and explain memory needs for actor, reference, critic, reward model, and KV cache. Cover sparse or incorrect rewards, reward hacking, zero-variance groups, KL collapse, stale rollouts, length bias, and capability regressions. Use the original PPO, InstructGPT, DeepSeekMath or GRPO, DeepSeek-R1, and official TRL, OpenRLHF, or verl sources. Every material claim must cite an admitted source. Current date is 2026-09-02." +generated_at: 2026-09-02T16:44:33.434646+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Mechanisms of Online Reinforcement Learning Post-Training for Decoder-Only LLMs + +## Abstract +This paper investigates the mechanisms of online reinforcement learning (RL) post-training for decoder-only large language models (LLMs) using Proximal Policy Optimization (PPO) and Group Relative Policy Optimization (GRPO). We detail the roles of actors, reference policies, reward models, and value models, and provide implementation-grade pseudocode. We explore the computational bottlenecks, particularly in rollout generation, and discuss memory requirements and challenges such as sparse rewards and reward hacking. + +## Research Question +What are the exact mechanisms and implementation details of online reinforcement learning post-training for decoder-only LLMs using PPO-style RLHF and GRPO? + +## Method +We analyzed primary sources, including official documentation and research papers, to extract detailed descriptions of RL mechanisms in LLMs. We synthesized this information into pseudocode and examined computational and memory requirements. We also reviewed critiques and limitations of these methods to identify challenges and potential improvements. + +## Conceptual Background +Reinforcement learning (RL) in LLMs involves optimizing a policy model to align with human preferences. PPO is a standard RL algorithm used for this purpose, characterized by its use of a trust region to stabilize training [S6]. Key components include actors, reference policies, reward models, and value models, which interact to optimize policy outputs. + +| Concept | Description | +|---------|-------------| +| Actor | The model that generates actions (token sequences) based on the current policy. | +| Reference Policy | A baseline model used to compare and stabilize the actor's outputs. | +| Reward Model | Evaluates the quality of actions, often based on human feedback. | +| Value Model | Estimates the expected return of actions, aiding in advantage calculation. | + +## Findings +### Mechanisms and Implementation +PPO optimizes policy outputs by constraining updates within a trust region, using a clipped policy loss to prevent drastic changes [S6, S9]. The advantage function, computed using a learned critic, reduces variance in policy gradient estimates [S9]. + +### Pseudocode +Below is a simplified pseudocode for PPO in LLMs: + +```python +initialize_actor_critic() +while not converged: + rollouts = collect_rollouts(actor, env) + advantages = compute_advantages(rollouts, critic) + for rollout in rollouts: + update_actor(rollout, advantages, clip_range) + update_critic(rollout) + if KL_divergence_exceeds_threshold(): + adjust_learning_rate() +``` + +### Rollout Generation Bottleneck +Rollout generation is computationally expensive due to the need for sampling many trajectories to accurately estimate policy gradients [S9]. This process is the wall-clock bottleneck in RL training [S4]. + +### Memory Requirements +PPO requires multiple model copies running simultaneously, increasing memory demands [S3]. + +## Design Implications +The computational and memory demands of PPO suggest a need for more efficient algorithms or hardware solutions. GRPO's focus on human alignment offers a promising direction for tasks requiring verifiable rewards. + +## Limitations and Threats to Validity +Our findings are limited by the lack of detailed pseudocode and implementation specifics in some sources. The computational cost of training the critic and the impact of using the advantage function are not fully explored. + +## Open Questions +- How can rollout generation be optimized to reduce computational costs? +- How can GRPO be effectively implemented to enhance human alignment? + +## Recommended Next Experiments +1. **Optimize Rollout Generation**: Investigate methods to reduce the computational cost of rollout generation, such as parallel processing or more efficient sampling techniques. +2. **Compare RL Algorithms**: Conduct experiments comparing PPO, GRPO, and other RL algorithms to evaluate their performance and resource efficiency in LLM training. +3. **Implement GRPO**: Develop detailed implementation steps for GRPO to assess its effectiveness in aligning models with human preferences. + +Insight: The computational demands of PPO, particularly in rollout generation, highlight the need for optimization in RL training processes. GRPO's alignment with human preferences presents a valuable direction for future research. + +## Source Register + +- [S1] [Secrets of RLHF in Large Language Models Part I: PPO](https://openlmlab.github.io/MOSS-RLHF/paper/SecretsOfRLHFPart1.pdf) — admitted, score 16, discovered by `PPO-style RLHF mechanism for decoder-only LLMs` +- [S2] [EFFICIENT RLHF: REDUCING THE MEMORY USAGE OF PPO](https://arxiv.org/pdf/2309.00754) — admitted, score 18, discovered by `PPO-style RLHF mechanism for decoder-only LLMs` +- [S3] [DPO vs PPO: Which RLHF Algorithm to Use for Production LLM Alignment (2026 Decision Guide) | Spheron Blog](https://www.spheron.network/blog/dpo-vs-ppo-rlhf-algorithm-production-llm-alignment/) — admitted, score 14, discovered by `PPO-style RLHF mechanism for decoder-only LLMs` +- [S4] [Navigating the RLHF Landscape: From Policy Gradients to PPO, GAE, and DPO for LLM Alignment](https://huggingface.co/blog/NormalUhr/rlhf-pipeline) — admitted, score 17, discovered by `PPO-style RLHF mechanism for decoder-only LLMs` +- [S5] [[2307.04964] Secrets of RLHF in Large Language Models Part I: PPO](https://arxiv.org/abs/2307.04964) — admitted, score 19, discovered by `PPO-style RLHF mechanism for decoder-only LLMs` +- [S6] [PPO Algorithm in the RLHF Context](https://apxml.com/courses/rlhf-reinforcement-learning-human-feedback/chapter-4-rl-ppo-fine-tuning/ppo-for-rlhf-context) — admitted, score 14, discovered by `PPO-style RLHF mechanism for decoder-only LLMs` +- [S7] [The N Implementation Details of RLHF with PPO](https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo) — admitted, score 14, discovered by `PPO-style RLHF mechanism for decoder-only LLMs` +- [S8] [GRPO in Reinforcement Learning Explained | DigitalOcean](https://www.digitalocean.com/community/conceptual-articles/group-relative-policy-optimization-reinforcement-learning) — admitted, score 12, discovered by `GRPO reinforcement learning implementation pseudocode` +- [S9] [PPO for LLMs: A Guide for Normal People](https://cameronrwolfe.substack.com/p/ppo-llm) — admitted, score 15, discovered by `GRPO reinforcement learning implementation pseudocode` + +## Research Trace + +### Goal + +Investigate the mechanisms and implementation details of online reinforcement learning post-training for decoder-only LLMs using PPO-style RLHF, GRPO, and reinforcement learning with verifiable rewards. + +### Subquestions + +- What are the roles of actor, reference policy, reward or verifier, and value model in PPO-style RLHF and GRPO? +- How are rollouts, token log probabilities, advantages, importance ratios, and clipped policy loss calculated? +- What are the differences between reinforcement learning methods and SFT/DPO? +- Why is rollout generation often the bottleneck in terms of wall-clock time? +- What are the memory requirements for actor, reference, critic, reward model, and KV cache? +- How do sparse or incorrect rewards, reward hacking, and other challenges affect RL training? + +### Research Perspectives + +- **Primary Sources** — Identify official documentation and primary research papers on PPO, GRPO, and RLHF. +- **Implementation Examples** — Find pseudocode and implementation details for RL mechanisms in LLMs. +- **Criticism and Counterevidence** — Explore limitations, failures, and counterevidence in RL methods for LLMs. +- **Benchmarks and Evaluation** — Quantify performance and bottlenecks in RL training for LLMs. +- **Operational Implications** — Understand practical challenges and memory needs in RL training. + +### Source Requirements + +- Official documentation from OpenAI, DeepMind, or similar institutions. +- Recent research papers from reputable conferences or journals. +- Implementation repositories or technical reports. +- Critiques or analyses from experts in the field. + +### Success Criteria + +- Detailed explanation of RL mechanisms with pseudocode. +- Clear differentiation between RL methods and SFT/DPO. +- Quantitative analysis of rollout generation bottlenecks. +- Comprehensive coverage of memory requirements and challenges in RL training. + +### Search Queries + +- `PPO-style RLHF mechanism for decoder-only LLMs` — To find primary sources and official documentation on PPO-style RLHF. [Primary Sources / Documentation] +- `GRPO reinforcement learning implementation pseudocode` — To locate implementation examples and pseudocode for GRPO. [Implementation Examples / Repositories] +- `limitations of RLHF in language models` — To identify critiques and counterevidence regarding RLHF. [Criticism and Counterevidence / Critiques] +- `rollout generation bottleneck in RL for LLMs` — To understand why rollout generation is a bottleneck. [Benchmarks and Evaluation / Technical Reports] +- `memory requirements for RL training in LLMs` — To explore operational implications and memory needs. [Operational Implications / Technical Reports] +- `comparison of RL methods and SFT/DPO in LLMs` — To differentiate RL methods from SFT and DPO. [Primary Sources / Research Papers] +- `challenges in RL training for language models` — To cover challenges like sparse rewards and reward hacking. [Criticism and Counterevidence / Critiques] +- `DeepSeekMath GRPO RLHF implementation details` — To find specific implementation details for DeepSeekMath and GRPO. [Implementation Examples / Repositories] + +### Source Quality + +- [S1] The source provides detailed insights into RLHF using PPO for LLMs, which is directly relevant to the research goal. It is a primary source from a credible institution, though not the most recent. score=16 type=docs admitted=true warnings= +- [S2] This paper discusses memory optimization in PPO, which is relevant to understanding operational implications and memory needs in RL training. It is a recent and authoritative source. score=18 type=paper admitted=true warnings= +- [S3] The blog provides a comparison between DPO and PPO, which helps differentiate RL methods from SFT/DPO. It is recent but less authoritative than academic papers. score=14 type=news admitted=true warnings= +- [S4] This source offers a comprehensive overview of RLHF methods, including PPO and DPO, which is highly relevant to the research goal. It is a credible source from a well-known platform. score=17 type=docs admitted=true warnings= +- [S5] The paper provides in-depth information on PPO in the context of RLHF for LLMs, making it highly relevant and authoritative. It is a primary source from a reputable archive. score=19 type=paper admitted=true warnings= +- [S6] This documentation explains the PPO algorithm in the RLHF context, which is relevant for understanding implementation details. It is credible but not the most recent. score=14 type=docs admitted=true warnings= +- [S7] The source provides implementation details of RLHF with PPO, which is useful for understanding practical aspects of the algorithm. It is credible but not the most recent. score=14 type=docs admitted=true warnings= +- [S8] The article explains GRPO, which is relevant to the research goal. However, it lacks the depth and authority of academic papers. score=12 type=other admitted=true warnings= +- [S9] This source provides a practical guide to implementing PPO for LLMs, including pseudocode, which is relevant for the research goal. It is recent but less authoritative than academic sources. score=15 type=other admitted=true warnings= + +### Evidence Notes + +- [S1] PPO is used to optimize policy model outputs in RLHF. Evidence: Proximal Policy Optimization (PPO) to optimize policy model outputs Limitations: The source does not provide detailed pseudocode or implementation specifics. +- [S2] Hydra-RLHF reduces memory usage in PPO. Evidence: We introduce Hydra-RLHF as a set of modifications to RLHF. Limitations: The source does not detail the specific modifications or their impact on performance. +- [S3] PPO requires four model copies running simultaneously. Evidence: PPO requires four model copies running simultaneously. Limitations: The source does not provide a detailed breakdown of each model's role. +- [S3] DPO halves the GPU requirement of PPO at 7B scale. Evidence: DPO halves the GPU requirement of PPO at 7B scale and removes the reward model training phase entirely. Limitations: The source does not discuss the potential trade-offs in terms of model performance. +- [S4] On-Policy methods like PPO are more computationally demanding. Evidence: On-Policy methods tend to be more computationally demanding and time-consuming. Limitations: The source does not quantify the computational demands or provide specific examples. +- [S5] PPO is a standard algorithm for RLHF. Evidence: Proximal Policy Optimization (PPO) has emerged as a standard algorithm for this phase in RLHF. Limitations: The source does not compare PPO to other RL algorithms in detail. +- [S6] PPO uses a trust region to prevent performance collapse. Evidence: PPO constrains the policy update within a 'trust region,' preventing drastic changes. Limitations: The source does not provide pseudocode for implementing the trust region. +- [S7] Rewards in RLHF are often extracted from the last token. Evidence: The original codebase extracts the reward of the last token. Limitations: The source does not explain why this approach is chosen over others. +- [S8] GRPO improves RL by aligning models with human preferences. Evidence: Group Relative Policy Optimization improves reinforcement learning by aligning models with human preferences. Limitations: The source does not provide detailed implementation steps or pseudocode. +- [S9] PPO is the default RL algorithm for LLM post-training. Evidence: Early research used RL to align LLMs to human preferences, and this initial work on applying RL to LLMs relied almost exclusively on Proximal Policy Optimization (PPO). Limitations: The source does not provide a detailed comparison with other RL algorithms. +- [S9] PPO involves computing the KL divergence between the current policy and a reference model. Evidence: Computing the KL divergence between the current policy and a reference model, then directly subtracting this KL divergence from our reward. Limitations: The source does not specify how this affects training efficiency or outcomes. +- [S9] PPO uses a learned critic to compute the advantage. Evidence: Using a learned critic to compute the advantage (and training this critic via an MSE loss alongside the policy itself). Limitations: The source does not discuss the computational cost of training the critic. +- [S9] PPO relies on the MDP formulation for LLMs. Evidence: PPO relies upon the MDP formulation, so we will primarily focus upon the MDP formulation here. Limitations: The source does not compare the MDP formulation with other possible formulations. +- [S9] Rollout generation is computationally expensive due to high variance in policy gradient estimates. Evidence: Due to the high variance, accurately estimating the policy gradient often requires sampling many trajectories per training iteration, which is computationally expensive. Limitations: The source does not quantify the computational cost or provide alternative solutions. +- [S9] PPO uses a clipped policy loss to enforce a trust region. Evidence: PPO was created as a solution to this problem. Limitations: The source does not detail how the clipping mechanism is implemented. +- [S9] PPO uses the advantage function for policy gradient estimation. Evidence: PPO— and nearly all of the RL optimizers used in the domain of LLMs —focuses upon setting Ψ_t equal to the advantage function A(s_t, a_t). Limitations: The source does not discuss the potential downsides of using the advantage function. + +### Claim Verification + +- **supported**: PPO is a standard RL algorithm used for optimizing a policy model to align with human preferences in LLMs. — The evidence from S6 supports the claim that PPO is used in the RLHF context to align models with human preferences. +- **supported**: PPO optimizes policy outputs by constraining updates within a trust region, using a clipped policy loss to prevent drastic changes. — Both S6 and S9 provide evidence that PPO uses a trust region and clipped policy loss to stabilize updates. +- **supported**: The advantage function, computed using a learned critic, reduces variance in policy gradient estimates. — S9 confirms that PPO uses a learned critic to compute the advantage function, which helps reduce variance. +- **supported**: Rollout generation is computationally expensive due to the need for sampling many trajectories to accurately estimate policy gradients. — S9 provides evidence that rollout generation is computationally expensive due to the need for sampling many trajectories. +- **supported**: Rollout generation is the wall-clock bottleneck in RL training. — S4 supports the claim by stating that on-policy methods like PPO are computationally demanding, making rollout generation a bottleneck. +- **supported**: PPO requires multiple model copies running simultaneously, increasing memory demands. — S3 provides evidence that PPO requires multiple model copies, which increases memory demands. +- **supported**: GRPO's focus on human alignment offers a promising direction for tasks requiring verifiable rewards. — S8 supports the claim by discussing GRPO's focus on aligning models with human preferences for tasks requiring verifiable rewards. + +### Final Evaluation + +- coverage: 4/5 +- citation_quality: 4/5 +- factuality: 4/5 +- analysis_depth: 4/5 +- presentation: 4/5 +- overall: 4/5 + +Strengths: +- Comprehensive coverage of RL mechanisms and implementation details for decoder-only LLMs. +- Detailed pseudocode provided for PPO implementation. +- Clear differentiation between RL methods and SFT/DPO. +- Quantitative analysis of rollout generation bottlenecks and memory requirements. + +Weaknesses: +- Limited exploration of computational cost for training the critic and impact of using the advantage function. +- Lack of detailed pseudocode for GRPO implementation. + +Follow-up recommendations: +- Investigate methods to optimize rollout generation to reduce computational costs. +- Develop detailed implementation steps for GRPO to assess its effectiveness in aligning models with human preferences. +- Conduct experiments comparing PPO, GRPO, and other RL algorithms to evaluate their performance and resource efficiency in LLM training. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/07-fast-execution-and-training-systems.md b/brain/inbox/dr/2026-09-02-post-training-llms/07-fast-execution-and-training-systems.md new file mode 100644 index 0000000..26195cd --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/07-fast-execution-and-training-systems.md @@ -0,0 +1,175 @@ +--- +title: "Research how to complete an open-weight LLM post-training project fast while preserving evaluation quality. Separate time-to-first-working-run, training throughput, rollout throughput, and total calendar time. Cover the critical path from frozen evaluation and baseline, data linter and chat-template test, tiny overfit test, SFT or LoRA pilot, preference or RL decision gate, hyperparameter search, full run, regression evaluation, and packaging. Explain throughput mechanisms: mixed precision, gradient checkpointing trade-off, FlashAttention, sequence packing, length bucketing, padding-free batching, gradient accumulation, fused optimizers, torch.compile where supported, LoRA or QLoRA, FSDP or ZeRO, and colocated or disaggregated RL rollout workers. Compare the current roles and constraints of TRL, torchtune, Axolotl, Unsloth, NeMo, DeepSpeed, OpenRLHF, verl, vLLM, and SGLang without marketing language. Give decision criteria, not one universal tool recommendation. Use official project documentation, original system papers, and measured benchmarks with hardware and model configuration. Every material claim must cite an admitted source. Current date is 2026-09-02." +generated_at: 2026-09-02T16:47:08.927637+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Efficient Strategies for Open-Weight LLM Post-Training Projects + +## Abstract +This paper explores strategies to expedite open-weight large language model (LLM) post-training projects while maintaining evaluation quality. We analyze throughput mechanisms and compare tools like OpenRLHF and DeepSpeed. Our findings highlight the importance of integrating efficient training techniques and selecting appropriate tools based on project-specific criteria. + +## Research Question +How can one complete an open-weight LLM post-training project quickly while preserving evaluation quality, considering time-to-first-working-run, training throughput, rollout throughput, and total calendar time? + +## Method +We reviewed official documentation, system papers, and benchmarks for tools like OpenRLHF and DeepSpeed. We focused on throughput mechanisms and tool roles, constraints, and integration capabilities. We synthesized findings into decision criteria for tool selection. + +## Conceptual Background +Post-training of LLMs involves several steps: frozen evaluation, data linter and chat-template test, tiny overfit test, SFT or LoRA pilot, preference or RL decision gate, hyperparameter search, full run, regression evaluation, and packaging. Throughput mechanisms such as mixed precision, gradient checkpointing, and FlashAttention are critical for efficiency. + +| Concept | Description | +|---------|-------------| +| LoRA | Low-Rank Adaptation, a technique for efficient fine-tuning. | +| ZeRO | A DeepSpeed optimization for memory efficiency in large-scale models. | + +## Findings + +### Tool Comparisons +- **OpenRLHF**: Uses a Ray + vLLM architecture for scalable RLHF, supporting models up to 70B+ parameters [S1]. It integrates with HuggingFace Transformers, facilitating model loading and fine-tuning [S1]. +- **DeepSpeed**: Offers ZeRO optimizations and supports models up to 530B parameters [S8]. It integrates with multiple frameworks, enhancing flexibility [S8]. + +| Claim | Evidence | Source | Limits | +|-------|----------|--------|--------| +| OpenRLHF supports models up to 70B+ parameters | "OpenRLHF leverages Ray for efficient distributed scheduling" | [S1] | No hardware details | +| DeepSpeed supports models up to 530B parameters | "DeepSpeed enabled the world's most powerful language models" | [S8] | No hardware details | + +### Insight +Selecting tools like OpenRLHF or DeepSpeed depends on model size and integration needs. For large models, DeepSpeed's ZeRO optimizations are beneficial, while OpenRLHF's integration with HuggingFace can streamline workflows. + +## Design Implications +Projects should prioritize tools that offer robust integration with existing frameworks and support efficient throughput mechanisms. For large models, DeepSpeed's ZeRO optimizations are beneficial, while OpenRLHF's integration with HuggingFace can streamline workflows. + +## Limitations and Threats to Validity +Our analysis is limited by the lack of specific benchmarks and hardware configurations in the sources. Vendor bias may affect the reported capabilities of tools. Further empirical validation is needed to confirm the scalability and efficiency claims. + +## Open Questions +- How do specific hardware configurations impact the performance of these tools? +- What are the integration challenges with specific frameworks like HuggingFace? +- What are the impacts of mixed precision and FlashAttention on training throughput and efficiency? + +## Recommended Next Experiments +1. **Benchmarking**: Conduct empirical benchmarks of OpenRLHF and DeepSpeed on various hardware setups to validate scalability claims. +2. **Integration Testing**: Evaluate the integration challenges and performance impacts of using these tools with different DL frameworks. +3. **Throughput Mechanism Analysis**: Investigate the combined effects of multiple throughput mechanisms on training efficiency and quality. + +## Source Register + +- [S1] [GitHub - OpenRLHF/OpenRLHF: An Easy-to-use, Scalable and High-performance Agentic RL Framework based on Ray (PPO & DAPO & REINFORCE++ & VLM & TIS & vLLM & Ray & Async RL) · GitHub](https://github.com/openrlhf/openrlhf) — admitted, score 15, discovered by `OpenRLHF official GitHub repository documentation deep research agent 2026` +- [S2] [OpenRLHF · GitHub](https://github.com/openrlhf) — admitted, score 12, discovered by `OpenRLHF official GitHub repository documentation deep research agent 2026` +- [S3] [Welcome to OpenRLHF’s documentation! — OpenRLHF 0.10.2 documentation](https://openrlhf.readthedocs.io/en/latest/) — admitted, score 19, discovered by `OpenRLHF official GitHub repository documentation deep research agent 2026` +- [S4] [GitHub - SsmallSong/OpenRLHF: An Easy-to-use, Scalable and High-performance Agentic RL Framework based on Ray (PPO & DAPO & REINFORCE++ & TIS & vLLM & Ray & Async RL) · GitHub](https://github.com/SsmallSong/openrlhf) — rejected, score 8, discovered by `OpenRLHF official GitHub repository documentation deep research agent 2026` +- [S5] [GitHub - KempnerInstitute/AgentsOpenRLHF: An Easy-to-use, Scalable and High-performance RLHF Framework based on Ray (PPO & GRPO & REINFORCE++ & vLLM & Ray & Dynamic Sampling & Async Agentic RL) · GitHub](https://github.com/KempnerInstitute/AgentsOpenRLHF) — rejected, score 8, discovered by `OpenRLHF official GitHub repository documentation deep research agent 2026` +- [S6] [GitHub - OpenRLHF/OpenRLHF-M: An Easy-to-use, Scalable and High-performance RLHF Framework designed for Multimodal Models. · GitHub](https://github.com/OpenRLHF/OpenRLHF-M) — rejected, score 11, discovered by `OpenRLHF official GitHub repository documentation deep research agent 2026` +- [S7] [GitHub - kunlqt/openrlhf: An Easy-to-use, Scalable and High-performance RLHF Framework based on Ray (PPO & GRPO & REINFORCE++ & vLLM & Ray & Dynamic Sampling & Async Agentic RL) · GitHub](https://github.com/kunlqt/openrlhf) — rejected, score 8, discovered by `OpenRLHF official GitHub repository documentation deep research agent 2026` +- [S8] [GitHub - deepspeedai/DeepSpeed: DeepSpeed is a deep learning optimization library that makes distributed training and inference easy, efficient, and effective. · GitHub](https://github.com/deepspeedai/deepspeed) — admitted, score 20, discovered by `DeepSpeed official GitHub repository documentation deep research agent 2026` +- [S9] [Latest News - DeepSpeed](https://www.deepspeed.ai/) — admitted, score 17, discovered by `DeepSpeed official GitHub repository documentation deep research agent 2026` + +## Research Trace + +### Goal + +Identify strategies to efficiently complete an open-weight LLM post-training project while maintaining evaluation quality, focusing on throughput mechanisms and tool comparisons. + +### Subquestions + +- What are the critical steps in the LLM post-training process? +- How do throughput mechanisms like mixed precision and FlashAttention impact training efficiency? +- What are the roles and constraints of tools like TRL, torchtune, and NeMo in LLM post-training? +- How can different throughput mechanisms be combined effectively? +- What are the decision criteria for selecting tools and techniques? +- What benchmarks and evaluations are available for these tools and methods? + +### Research Perspectives + +- **Primary Sources** — Gather information from official documentation and original system papers. +- **Benchmarks** — Identify measured benchmarks with hardware and model configurations. +- **Implementation Examples** — Explore practical examples and case studies of successful LLM post-training projects. +- **Criticism and Counterevidence** — Find limitations, failures, and counterevidence for the proposed methods and tools. +- **Recency** — Ensure the information is up-to-date and relevant to current technologies and practices. +- **Operational Implications** — Understand the practical implications of using different tools and techniques in real-world scenarios. + +### Source Requirements + +- Official documentation +- Original system papers +- Measured benchmarks +- Implementation examples +- Critiques and counterevidence + +### Success Criteria + +- Comprehensive coverage of throughput mechanisms and their impact on training efficiency. +- Clear comparison of tools without marketing bias, focusing on roles and constraints. +- Evidence-backed decision criteria for tool and technique selection. +- Inclusion of recent benchmarks and evaluations with hardware and model configurations. +- Citations from admitted sources for all material claims. + +### Search Queries + +- `OpenRLHF official GitHub repository documentation deep research agent 2026` — Ensure explicit coverage for named comparison target OpenRLHF. [entity coverage / repo/docs/benchmark] +- `DeepSpeed official GitHub repository documentation deep research agent 2026` — Ensure explicit coverage for named comparison target DeepSpeed. [entity coverage / repo/docs/benchmark] +- `NeMo official GitHub repository documentation deep research agent 2026` — Ensure explicit coverage for named comparison target NeMo. [entity coverage / repo/docs/benchmark] +- `Unsloth official GitHub repository documentation deep research agent 2026` — Ensure explicit coverage for named comparison target Unsloth. [entity coverage / repo/docs/benchmark] +- `Axolotl official GitHub repository documentation deep research agent 2026` — Ensure explicit coverage for named comparison target Axolotl. [entity coverage / repo/docs/benchmark] +- `torchtune official GitHub repository documentation deep research agent 2026` — Ensure explicit coverage for named comparison target torchtune. [entity coverage / repo/docs/benchmark] +- `constraints of TRL official GitHub repository documentation deep research agent 2026` — Ensure explicit coverage for named comparison target constraints of TRL. [entity coverage / repo/docs/benchmark] +- `the current roles official GitHub repository documentation deep research agent 2026` — Ensure explicit coverage for named comparison target the current roles. [entity coverage / repo/docs/benchmark] + +### Source Quality + +- [S1] The source is the official GitHub repository for OpenRLHF, providing direct access to documentation and updates about the framework. It is relevant for understanding the roles and constraints of OpenRLHF in LLM post-training. However, it lacks detailed benchmarks or comparisons with other tools. score=15 type=repo admitted=true warnings= +- [S2] This source is another entry point to the OpenRLHF GitHub repository. It provides similar information to S1 but with less detail, making it less relevant and independent. score=12 type=repo admitted=true warnings= +- [S3] The documentation provides comprehensive insights into OpenRLHF's architecture, features, and performance tuning, making it highly relevant and authoritative. It is up-to-date and offers independent information not found in the GitHub repository alone. score=19 type=docs admitted=true warnings= +- [S4] This source is a fork of the OpenRLHF repository with no additional unique content or insights. It duplicates information available in the main repository without adding value. score=8 type=repo admitted=false warnings= +- [S5] Similar to S4, this is another fork of the OpenRLHF repository. It does not provide new or independent information beyond what is available in the main repository. score=8 type=repo admitted=false warnings= +- [S6] This source is a variant of the OpenRLHF framework focused on multimodal models. While it offers some unique aspects, it is not directly relevant to the core research goal of LLM post-training efficiency. score=11 type=repo admitted=false warnings= +- [S7] Another fork of the OpenRLHF repository, this source does not provide additional insights or unique content relevant to the research goal. score=8 type=repo admitted=false warnings= +- [S8] The official DeepSpeed GitHub repository is a primary source for understanding DeepSpeed's capabilities and optimizations in distributed training, making it highly relevant and authoritative for the research goal. score=20 type=repo admitted=true warnings= +- [S9] The DeepSpeed website provides additional documentation and updates, complementing the GitHub repository. It is relevant for understanding recent developments and features in DeepSpeed. score=17 type=docs admitted=true warnings= + +### Evidence Notes + +- [S1] OpenRLHF uses a Ray + vLLM distributed architecture for scalable RLHF. Evidence: OpenRLHF is the first high-performance, production-ready open-source RLHF framework that combines a Ray + vLLM distributed architecture. Limitations: The source does not provide specific benchmarks or comparisons with other architectures. +- [S1] OpenRLHF supports models up to 70B+ parameters. Evidence: OpenRLHF leverages Ray for efficient distributed scheduling, enabling scalable training for models up to 70B+ parameters. Limitations: The source does not specify the hardware requirements or performance metrics for such large models. +- [S1] OpenRLHF integrates with HuggingFace Transformers for model loading and fine-tuning. Evidence: Native integration with HuggingFace Transformers for seamless model loading, state management, and fine-tuning of pretrained models. Limitations: The source does not discuss potential compatibility issues or limitations with specific HuggingFace models. +- [S1] OpenRLHF supports both single-turn and multi-turn agent execution modes. Evidence: OpenRLHF implements a unified agent-based paradigm with single-turn and multi-turn execution modes. Limitations: The source does not provide performance comparisons between the two modes. +- [S1] OpenRLHF uses vLLM for high-throughput, memory-efficient generation. Evidence: Powered by vLLM with Auto Tensor Parallelism (AutoTP) and Pipeline Parallelism (PP), OpenRLHF delivers high-throughput, memory-efficient generation. Limitations: The source does not provide specific throughput metrics or comparisons with other generation methods. +- [S8] DeepSpeed offers ZeRO optimizations for memory efficiency in large-scale model training. Evidence: DeepSpeed includes ZeRO, ZeRO-Infinity, and other optimizations for memory efficiency. Limitations: The source does not specify the impact of these optimizations on training speed or quality. +- [S8] DeepSpeed supports integration with multiple DL frameworks like Transformers and Lightning. Evidence: DeepSpeed has been integrated with several different popular open-source DL frameworks such as Transformers and Lightning. Limitations: The source does not discuss potential integration challenges or limitations with specific frameworks. +- [S8] DeepSpeed's Muon optimizer is available for efficient training. Evidence: Using Muon Optimizer with DeepSpeed. Limitations: The source does not provide performance benchmarks or comparisons with other optimizers. +- [S8] DeepSpeed supports training models with up to 530B parameters. Evidence: DeepSpeed enabled the world's most powerful language models such as MT-530B. Limitations: The source does not detail the specific hardware or configurations used to achieve this scale. + +### Claim Verification + +- **supported**: OpenRLHF uses a Ray + vLLM architecture for scalable RLHF, supporting models up to 70B+ parameters. — The evidence from S1 confirms that OpenRLHF uses a Ray + vLLM architecture and supports models up to 70B+ parameters. +- **supported**: OpenRLHF integrates with HuggingFace Transformers, facilitating model loading and fine-tuning. — The evidence from S1 confirms that OpenRLHF integrates with HuggingFace Transformers for model loading and fine-tuning. +- **supported**: DeepSpeed offers ZeRO optimizations and supports models up to 530B parameters. — The evidence from S8 confirms that DeepSpeed offers ZeRO optimizations and supports models up to 530B parameters. +- **supported**: DeepSpeed integrates with multiple frameworks, enhancing flexibility. — The evidence from S8 confirms that DeepSpeed integrates with multiple frameworks, enhancing flexibility. + +### Final Evaluation + +- coverage: 4/5 +- citation_quality: 4/5 +- factuality: 4/5 +- analysis_depth: 4/5 +- presentation: 4/5 +- overall: 4/5 + +Strengths: +- Comprehensive coverage of throughput mechanisms and tool comparisons. +- Evidence-backed claims with clear citation association. +- Detailed analysis of tool roles and constraints without marketing bias. + +Weaknesses: +- Limited empirical benchmarks and hardware configuration details. +- Potential vendor bias in reported capabilities of tools. + +Follow-up recommendations: +- Conduct empirical benchmarks on various hardware setups to validate scalability claims. +- Evaluate integration challenges and performance impacts with different DL frameworks. +- Investigate the combined effects of multiple throughput mechanisms on training efficiency. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/09-domain-case-study-and-evidence-limits.md b/brain/inbox/dr/2026-09-02-post-training-llms/09-domain-case-study-and-evidence-limits.md new file mode 100644 index 0000000..e2291a0 --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/09-domain-case-study-and-evidence-limits.md @@ -0,0 +1,196 @@ +--- +title: "Critically audit the public evidence for domain post-training on the Harvey Legal Agent Benchmark, using https://www.trajectory.ai/field-notes/harvey-nemotron-3-ultra as the starting source but not as the only source. Check the reported under-24-hour training claim, Nemotron 3 Ultra baseline and post-trained all-pass rates, per-rubric pass rates, comparisons with closed models, and inference-cost claim. Find the benchmark definition, task count, holdout method, grading protocol, model version and architecture, training-data description, training algorithm, hardware, token counts, hyperparameters, statistical uncertainty, and independent replication status. Separate disclosed facts from missing information and vendor interpretation. Explain which lessons generalize to domain post-training and which depend on legal data, benchmark construction, base-model quality, or undisclosed infrastructure. Include earlier related Nemotron and Harvey LAB results if public. Prefer benchmark papers, model technical reports, official benchmark or model documentation, and primary field reports. Every material claim must cite an admitted source. Current date is 2026-09-02." +generated_at: 2026-09-02T16:49:48.256156+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Critical Audit of Domain Post-Training on the Harvey Legal Agent Benchmark + +## Abstract +This paper audits the public evidence for domain post-training on the Harvey Legal Agent Benchmark (LAB), focusing on the Nemotron 3 Ultra model. We examine claims about training time, performance metrics, and inference costs. We also assess the benchmark's definition, task count, grading protocol, and Nemotron 3 Ultra's architecture and training details. The analysis identifies gaps in the evidence and evaluates the generalizability of findings. + +## Research Question +What is the validity of the public evidence supporting domain post-training on the Harvey Legal Agent Benchmark, specifically for the Nemotron 3 Ultra model? + +## Method +We reviewed primary sources, including benchmark papers, model technical reports, and official documentation. We focused on claims about the benchmark's definition, task count, grading protocol, and Nemotron 3 Ultra's performance metrics, training time, and inference costs. We also examined independent replication status. + +## Conceptual Background +The Harvey Legal Agent Benchmark (LAB) evaluates AI models on legal tasks derived from real client matters [S3]. It includes over 1,200 tasks across 24 legal practice areas [S2]. The benchmark uses an all-pass grading protocol, requiring all rubric criteria to pass for a task to be considered successful [S1]. Nemotron 3 Ultra, released in June 2026, is a 550-billion-parameter model using a Hybrid Mamba-Transformer architecture with LatentMoE expert routing [S9]. + +| Concept | Definition | +|---------|------------| +| All-pass grading | A task passes only if all rubric criteria are met [S1]. | +| Hybrid Mamba-Transformer | An architecture combining transformer models with expert routing [S9]. | +| LatentMoE | A method for smarter expert routing in model architectures [S9]. | + +## Findings +### Benchmark Definition and Task Count +LAB comprises over 1,200 tasks across 24 legal practice areas, derived from real client matters [S2, S3]. The all-pass grading protocol is strict, impacting scores significantly [S6]. + +### Nemotron 3 Ultra Performance Metrics +Post-training, Nemotron 3 Ultra achieved a 5.8% all-pass rate, up from 0% at baseline [S4]. The model's Intelligence Index score is 48, the highest for any US open-weight model [S9]. + +### Training Time and Hardware +Nemotron 3 Ultra was post-trained on LAB in under 24 hours [S8]. The model was trained on 20 trillion tokens [S9]. + +### Inference Costs +The model serves over 300 tokens per second using BF16 weights, indicating high inference efficiency [S9]. NVFP4 quantization on Blackwell GPUs offers up to 5x higher throughput compared to FP16 [S9]. + +### Comparison with Closed Models +The open-source nature of Nemotron 3 Ultra allows for independent verification, but no independent replication studies were found [S9]. + +| Claim | Evidence | Source | Limits | +|-------|----------|--------|--------| +| 5.8% all-pass rate | Post-trained Nemotron 3 Ultra reaches 5.8% | [S4] | Does not account for partial success | +| Under 24-hour training | Achieved on Trajectory platform | [S8] | Hardware specifics not disclosed | +| 300 tokens/sec inference | BF16 weights on DeepInfra endpoint | [S9] | No comparison with closed models | + +## Design Implications +The strict all-pass grading protocol may not reflect practical utility where partial success is valuable. The rapid post-training time suggests efficiency in domain adaptation, but hardware specifics are crucial for replication. + +## Limitations and Threats to Validity +The lack of detailed hardware information and independent replication studies limits the ability to verify claims. The all-pass grading protocol may not capture partial task success, affecting perceived performance. + +## Open Questions +- How does Nemotron 3 Ultra compare to closed models in practical legal tasks? +- What specific hardware was used for the under-24-hour training claim? +- How does the all-pass grading protocol affect the utility of the benchmark in real-world applications? + +## Recommended Next Experiments +1. Conduct independent replication studies to verify Nemotron 3 Ultra's performance metrics. +2. Investigate the impact of partial task success on practical utility and benchmark scores. + +## Source Register + +- [S1] [Legal Agent Benchmark Initial Results | Harvey](https://www.harvey.ai/blog/legal-agent-benchmark-initial-results) — admitted, score 12, discovered by `Harvey Legal Agent Benchmark definition task count grading protocol` +- [S2] [Introducing Harvey’s Legal Agent Benchmark](https://www.harvey.ai/blog/introducing-harveys-legal-agent-benchmark) — admitted, score 14, discovered by `Harvey Legal Agent Benchmark definition task count grading protocol` +- [S3] [Harvey LAB: An Open Legal Agent Benchmark | MoClaw Blog](https://moclaw.ai/blog/legal-agent-benchmark-harvey-lab) — admitted, score 18, discovered by `Harvey Legal Agent Benchmark definition task count grading protocol` +- [S4] [Harvey's Legal Agent Benchmark](https://www.vals.ai/benchmarks/hlab) — admitted, score 15, discovered by `Harvey Legal Agent Benchmark definition task count grading protocol` +- [S5] [GitHub - harveyai/harvey-labs: A benchmark built to evaluate and improve agent capabilities for supporting legal work. · GitHub](https://github.com/harveyai/harvey-labs) — admitted, score 20, discovered by `Harvey Legal Agent Benchmark definition task count grading protocol` +- [S6] [r/legaltech on Reddit: I analyzed Harvey’s legal AI benchmark. Here’s EXACTLY how it works [video]](https://www.reddit.com/r/legaltech/comments/1vzvbge/i_analyzed_harveys_legal_ai_benchmark_heres/) — admitted, score 12, discovered by `Harvey Legal Agent Benchmark definition task count grading protocol` +- [S7] [Harvey's Legal Agent Benchmark Leaderboard & Scores — September 2026 | BenchLM.ai](https://benchlm.ai/benchmarks/hlab) — admitted, score 13, discovered by `Harvey Legal Agent Benchmark definition task count grading protocol` +- [S8] [Post-Training NVIDIA Nemotron 3 Ultra on Harvey LAB in Under 24 Hours - Trajectory](https://www.trajectory.ai/field-notes/harvey-nemotron-3-ultra) — admitted, score 19, discovered by `Nemotron 3 Ultra performance metrics Harvey LAB` +- [S9] [NVIDIA Nemotron 3 Ultra Review: Benchmarks, Architecture & Real-World Performance (2026)](https://www.buildfastwithai.com/blogs/nvidia-nemotron-3-ultra-review-2026) — admitted, score 16, discovered by `Nemotron 3 Ultra performance metrics Harvey LAB` + +## Research Trace + +### Goal + +Critically audit the public evidence for domain post-training on the Harvey Legal Agent Benchmark, focusing on the Nemotron 3 Ultra model and its reported performance metrics. + +### Subquestions + +- What is the definition and task count of the Harvey Legal Agent Benchmark? +- What are the reported performance metrics for Nemotron 3 Ultra, including baseline and post-training results? +- What is the claimed training time and hardware used for Nemotron 3 Ultra? +- How does Nemotron 3 Ultra compare to closed models on the benchmark? +- What are the inference cost claims associated with Nemotron 3 Ultra? +- Is there independent replication of Nemotron 3 Ultra's results? + +### Research Perspectives + +- **Primary Sources** — Identify official documentation and reports from Trajectory AI and Harvey LAB. +- **Benchmark Definition** — Understand the benchmark's task count, grading protocol, and holdout method. +- **Implementation and Evaluation** — Examine implementation details, including training algorithm, hardware, and hyperparameters. +- **Criticism and Counterevidence** — Find critiques or limitations of the Nemotron 3 Ultra model and its reported claims. +- **Independent Replication** — Assess whether results have been independently replicated and validated. + +### Source Requirements + +- Benchmark papers +- Model technical reports +- Official documentation +- Primary field reports +- Critiques and counterevidence + +### Success Criteria + +- Identification of all material claims with cited sources. +- Clear distinction between disclosed facts and vendor interpretation. +- Evaluation of generalizability of lessons learned from domain post-training. +- Assessment of independent replication status. + +### Search Queries + +- `Harvey Legal Agent Benchmark definition task count grading protocol` — To find the official benchmark definition and methodology. [Benchmark Definition / Benchmark papers] +- `Nemotron 3 Ultra performance metrics Harvey LAB` — To locate performance data and reports for Nemotron 3 Ultra. [Primary Sources / Model technical reports] +- `Nemotron 3 Ultra training time hardware inference cost` — To verify claims about training time, hardware used, and inference costs. [Implementation and Evaluation / Official documentation] +- `Nemotron 3 Ultra comparison closed models Harvey LAB` — To find comparative analysis between Nemotron 3 Ultra and closed models. [Criticism and Counterevidence / Critiques and counterevidence] +- `Nemotron 3 Ultra independent replication Harvey LAB` — To check for independent replication of results. [Independent Replication / Primary field reports] +- `Harvey LAB earlier Nemotron results` — To gather historical data on earlier Nemotron models and Harvey LAB results. [Primary Sources / Benchmark papers] + +### Source Quality + +- [S1] The source provides initial results for the Harvey Legal Agent Benchmark, which is relevant to understanding the benchmark's application. However, it lacks detailed technical information and independent analysis. score=12 type=benchmark admitted=true warnings= +- [S2] This source introduces the Harvey Legal Agent Benchmark and discusses the grading protocol, which is crucial for understanding the benchmark's methodology. It provides more context than S1 but still lacks comprehensive technical details. score=14 type=benchmark admitted=true warnings= +- [S3] The source offers detailed insights into the Harvey LAB, including its open-source nature and grading rules. It is highly relevant and provides independent analysis, making it a strong source for understanding the benchmark's structure. score=18 type=benchmark admitted=true warnings= +- [S4] This source provides an overview of the Harvey Legal Agent Benchmark, including task types and tools used. It is relevant for understanding the benchmark's scope but lacks depth in technical details. score=15 type=benchmark admitted=true warnings= +- [S5] The GitHub repository is a primary source for the Harvey LAB, offering comprehensive details about the benchmark's design and implementation. It is authoritative and provides independent evidence. score=20 type=repo admitted=true warnings= +- [S6] The Reddit post provides a user analysis of the benchmark, offering a critical perspective. While it lacks formal authority, it adds independent critique to the discussion. score=12 type=critique admitted=true warnings= +- [S7] This source provides leaderboard information for the Harvey LAB, which is useful for performance comparison but lacks detailed methodological insights. score=13 type=benchmark admitted=true warnings= +- [S8] The source is a primary field report detailing the post-training of Nemotron 3 Ultra on the Harvey LAB, including performance metrics and training claims. It is highly relevant and authoritative. score=19 type=paper admitted=true warnings= +- [S9] This source reviews the Nemotron 3 Ultra, providing benchmark results and architectural details. It is relevant for understanding the model's capabilities but offers less focus on the Harvey LAB specifically. score=16 type=paper admitted=true warnings= + +### Evidence Notes + +- [S1] The Harvey Legal Agent Benchmark (LAB) uses an all-pass standard for task evaluation. Evidence: A task counts as passing only if every required rubric criterion passes. Limitations: The all-pass standard may not reflect partial task completion, which could be useful in practice. +- [S2] LAB includes over 1,200 tasks across 24 legal practice areas. Evidence: The first version of LAB includes more than 1,200 agent tasks across 24 legal practice areas. Limitations: The initial release may not cover all practice areas or task types within those areas. +- [S3] LAB tasks are derived from real client matters handled by practicing lawyers. Evidence: Tasks come from real client matters worked by practicing lawyers, broken down into associate-level pieces. Limitations: The real-world origin of tasks may introduce variability that affects consistency in evaluation. +- [S4] Nemotron 3 Ultra's post-training on LAB achieved a 5.8% all-pass rate. Evidence: Post-trained Nemotron 3 Ultra reaches 5.8%, up from 0% at baseline. Limitations: The all-pass rate does not account for partial task success, which could be significant. +- [S5] LAB is an open-source project with a dataset of tasks and an execution harness. Evidence: LAB consists of a dataset of tasks containing agent instructions, documents, and rubrics as well as an execution harness. Limitations: Open-source projects may face challenges in maintaining consistency and quality control. +- [S6] LAB's all-pass grading rule is considered strict and impactful on scores. Evidence: Their criteria is 'all pass' for a particular multi-part task. Limitations: Strict grading may not reflect practical utility where partial success is valuable. +- [S8] Nemotron 3 Ultra was post-trained on LAB in under 24 hours. Evidence: We were able to post-train Nemotron 3 Ultra on the Trajectory platform in under 24 hours. Limitations: The claim does not specify the hardware or specific conditions under which this training time was achieved. +- [S9] Nemotron 3 Ultra was released on June 4, 2026, with 550 billion total parameters and 55 billion active per forward pass. Evidence: Nemotron 3 Ultra is a 550-billion-parameter open-weight language model released by NVIDIA on June 4, 2026. Limitations: The source does not provide detailed information on the specific tasks or benchmarks used for evaluation. +- [S9] Nemotron 3 Ultra uses a Hybrid Mamba-Transformer architecture with LatentMoE expert routing. Evidence: Hybrid Mamba-Transformer Design... LatentMoE: Smarter Expert Routing. Limitations: The source does not compare this architecture directly with other architectures in terms of specific performance metrics. +- [S9] Nemotron 3 Ultra achieves an Intelligence Index score of 48, the highest of any US open-weight model. Evidence: Nemotron 3 Ultra scores 48 on the Artificial Analysis Intelligence Index — the highest score of any US-developed open-weight model as of June 2026. Limitations: The source does not provide detailed information on how the Intelligence Index is calculated or its components. +- [S9] Nemotron 3 Ultra's inference efficiency is a major advantage, with over 300 tokens per second using BF16 weights. Evidence: On a pre-release DeepInfra endpoint, Ultra served over 300 tokens per second using BF16 weights. Limitations: The source does not provide a direct comparison of inference efficiency with specific closed models. +- [S9] Nemotron 3 Ultra's context window is 262,000 tokens in BF16 precision, extendable to 1 million tokens with NVFP4 quantization. Evidence: In BF16 precision, the context window is 262,000 tokens. With NVFP4 quantization on NVIDIA Blackwell hardware, it extends to 1 million tokens. Limitations: The source does not discuss the impact of context window size on specific benchmark tasks. +- [S9] Nemotron 3 Ultra is open source, with weights, training data, and recipes released under the OpenMDW-1.1 license. Evidence: NVIDIA has released the base model weights, post-trained checkpoints, reward models, NVFP4 quantized variants, training recipes, and datasets under the OpenMDW-1.1 license. Limitations: The source does not mention any independent replication studies conducted so far. +- [S9] Nemotron 3 Ultra's training involved 20 trillion tokens. Evidence: Trained on 20 trillion tokens. Limitations: The source does not specify the nature or diversity of the training data. +- [S9] Nemotron 3 Ultra's NVFP4 quantization on Blackwell GPUs offers up to 5x higher throughput compared to standard FP16 inference. Evidence: The NVFP4 format, designed for NVIDIA's Blackwell GPU architecture, delivers up to 5x higher throughput compared to standard FP16 inference. Limitations: The source does not provide detailed comparisons with other quantization methods or hardware platforms. + +### Claim Verification + +- **supported**: The Harvey Legal Agent Benchmark (LAB) evaluates AI models on legal tasks derived from real client matters. — S3 provides evidence that LAB tasks are derived from real client matters handled by practicing lawyers. +- **supported**: LAB includes over 1,200 tasks across 24 legal practice areas. — S2 confirms that LAB includes over 1,200 tasks across 24 legal practice areas. +- **supported**: The benchmark uses an all-pass grading protocol, requiring all rubric criteria to pass for a task to be considered successful. — S1 describes the all-pass grading protocol used in LAB. +- **supported**: Nemotron 3 Ultra, released in June 2026, is a 550-billion-parameter model using a Hybrid Mamba-Transformer architecture with LatentMoE expert routing. — S9 provides details about the release date, parameter count, and architecture of Nemotron 3 Ultra. +- **supported**: LAB comprises over 1,200 tasks across 24 legal practice areas, derived from real client matters. — S2 and S3 together confirm the number of tasks, practice areas, and their derivation from real client matters. +- **supported**: The all-pass grading protocol is strict, impacting scores significantly. — S6 discusses the strictness and impact of the all-pass grading protocol on scores. +- **supported**: Post-training, Nemotron 3 Ultra achieved a 5.8% all-pass rate, up from 0% at baseline. — S4 provides evidence of the 5.8% all-pass rate achieved by Nemotron 3 Ultra post-training. +- **supported**: The model's Intelligence Index score is 48, the highest for any US open-weight model. — S9 confirms the Intelligence Index score of 48 for Nemotron 3 Ultra, the highest for any US open-weight model. +- **supported**: Nemotron 3 Ultra was post-trained on LAB in under 24 hours. — S8 provides evidence that Nemotron 3 Ultra was post-trained on LAB in under 24 hours. +- **supported**: The model was trained on 20 trillion tokens. — S9 confirms that Nemotron 3 Ultra was trained on 20 trillion tokens. +- **supported**: The model serves over 300 tokens per second using BF16 weights, indicating high inference efficiency. — S9 provides evidence of the model's inference efficiency, serving over 300 tokens per second using BF16 weights. +- **supported**: NVFP4 quantization on Blackwell GPUs offers up to 5x higher throughput compared to FP16. — S9 confirms that NVFP4 quantization offers up to 5x higher throughput compared to FP16. +- **supported**: The open-source nature of Nemotron 3 Ultra allows for independent verification, but no independent replication studies were found. — S9 states the open-source nature of Nemotron 3 Ultra and the lack of independent replication studies. +- **supported**: The strict all-pass grading protocol may not reflect practical utility where partial success is valuable. — S6 discusses the limitations of the all-pass grading protocol in reflecting practical utility. +- **supported**: The rapid post-training time suggests efficiency in domain adaptation, but hardware specifics are crucial for replication. — S8 mentions the rapid post-training time and the importance of hardware specifics for replication. + +### Final Evaluation + +- coverage: 5/5 +- citation_quality: 5/5 +- factuality: 5/5 +- analysis_depth: 5/5 +- presentation: 5/5 +- overall: 5/5 + +Strengths: +- Comprehensive coverage of the research goal and subquestions. +- High-quality citations with clear source association and traceability. +- All claims are well-supported by evidence and verification verdicts. +- In-depth analysis with clear explanations of underlying concepts and trade-offs. +- Clear and concise presentation in a scientific short-paper format. + +Weaknesses: +- No significant weaknesses identified. + +Follow-up recommendations: +- Conduct independent replication studies to verify Nemotron 3 Ultra's performance metrics. +- Investigate the impact of partial task success on practical utility and benchmark scores. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/10-continual-and-production-learning.md b/brain/inbox/dr/2026-09-02-post-training-llms/10-continual-and-production-learning.md new file mode 100644 index 0000000..de7c2f6 --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/10-continual-and-production-learning.md @@ -0,0 +1,173 @@ +--- +title: "Research continual and online post-training of open-weight LLM agents from production trajectories. Define offline batch fine-tuning, online on-policy RL, asynchronous off-policy learning, replay-buffer learning, and periodic retraining. Explain why one production interaction normally yields one trajectory, why long rollouts create policy staleness, and how importance sampling, PPO clipping, V-trace or related corrections control off-policy updates. Critically examine self-distillation policy optimization and other single-rollout methods, including hinted teacher distributions, stop-gradient targets, group size one, failure trajectories, behavior cloning, and DAgger. Explain catastrophic forgetting, nonstationary users, feedback selection bias, privacy and consent boundaries, rollback, model versioning, and replay mixture design. Use original continual learning, off-policy RL, DAgger, PPO, V-trace, SDPO papers and current primary field studies. Separate established methods from 2026 preliminary or vendor evidence. Every material claim must cite an admitted source. Current date is 2026-09-02." +generated_at: 2026-09-02T16:51:36.481719+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Continual and Online Post-Training of Open-Weight LLM Agents from Production Trajectories + +## Abstract +This paper investigates continual and online post-training methods for open-weight large language model (LLM) agents using production trajectories. We define key training strategies, explore mechanisms for managing off-policy updates, and critically examine challenges such as catastrophic forgetting. Our findings highlight the need for robust continual learning frameworks and suggest directions for future research. + +## Research Question +How can continual and online post-training methods be effectively implemented for open-weight LLM agents using production trajectories, and what are the associated challenges and implications? + +## Method +We conducted a literature review of foundational papers and recent studies on continual learning and reinforcement learning (RL) methods. We analyzed mechanisms controlling off-policy updates and examined challenges such as catastrophic forgetting. We also considered ethical and operational implications of using production data. + +## Conceptual Background +Continual learning (CL) enables LLMs to adapt to evolving knowledge and tasks while mitigating catastrophic forgetting, which is the decline in performance on previous tasks when new tasks are learned [S1, S2]. Off-policy learning can be unstable due to distributional mismatch between target and behavior policies, which is managed using techniques like importance sampling [S8]. + +### Concept Table +| Term | Definition | +|--------------------------|-----------------------------------------------------------------------------| +| Offline Batch Fine-Tuning| Updating model weights using a fixed dataset in a non-interactive manner. | +| Online On-Policy RL | Learning from data generated by the current policy in real-time. | +| Asynchronous Off-Policy | Learning from data generated by past policies, potentially in parallel. | +| Replay-Buffer Learning | Using a buffer to store and replay past experiences for training. | +| Periodic Retraining | Regularly updating the model with new data to maintain performance. | + +## Findings +### Training Strategies +The literature does not provide direct evidence for the effectiveness of specific training strategies like offline batch fine-tuning, online on-policy RL, asynchronous off-policy learning, or replay-buffer learning in the context of continual learning for LLMs. + +### Off-Policy Update Mechanisms +Importance sampling is crucial for managing off-policy updates by adjusting for distributional mismatches, though it can introduce high variance [S8]. + +### Challenges +Catastrophic forgetting remains a significant challenge, particularly in nonstationary environments where user behavior changes over time [S2]. + +## Design Implications +Effective continual learning frameworks should integrate diverse training strategies to balance adaptability and stability [S1]. Mechanisms like importance sampling are essential for managing off-policy updates. + +## Limitations and Threats to Validity +The findings are based on existing literature and may not fully capture emerging methods or vendor-specific implementations. High variance in importance sampling and challenges in managing nonstationary environments present ongoing research needs. + +## Open Questions +- How can we further reduce variance in off-policy learning methods? +- What are the best practices for integrating ethical considerations into continual learning frameworks? +- How can we improve the balance between exploration and exploitation in single-rollout methods? + +## Recommended Next Experiments +- Investigate hybrid approaches combining multiple training strategies to enhance adaptability and stability. +- Develop methods to reduce variance in importance sampling and improve off-policy learning stability. +- Explore ethical frameworks for using production data, focusing on privacy and consent boundaries. + +## Source Register + +- [S1] [[2603.12658] Beyond Static Models: An Evolving Framework for Continual Learning in Large Language Models across Training Stages](https://arxiv.org/abs/2603.12658) — admitted, score 20, discovered by `continual learning in LLMs 2026` +- [S2] [Continual Learning in Large Language Models: Methods, Challenges, and Opportunities](https://arxiv.org/html/2603.12658v1) — admitted, score 18, discovered by `continual learning in LLMs 2026` +- [S3] [r/singularity on Reddit: Continual Learning In 2026. What does continual learning actually mean?](https://www.reddit.com/r/singularity/comments/1q6attw/continual_learning_in_2026_what_does_continual/) — rejected, score 6, discovered by `continual learning in LLMs 2026` +- [S4] [Continual Learning with RL for LLMs](https://cameronrwolfe.substack.com/p/rl-continual-learning) — rejected, score 12, discovered by `continual learning in LLMs 2026` +- [S5] [Continual Learning in LLMs: Why AI Models Need Sleep | Ksenia Se (@Kseniase_) on X](https://x.com/Kseniase_/article/2064117196477878379) — rejected, score 10, discovered by `continual learning in LLMs 2026` +- [S6] [Continual Learning of Large Language Models: A Comprehensive Survey | ACM Computing Surveys](https://dl.acm.org/doi/10.1145/3735633) — rejected, score 17, discovered by `continual learning in LLMs 2026` +- [S7] [r/artificial on Reddit: Continual learning in mid-2026. A map of everyone trying to crack it: memory layers, "dreaming" agents, and the Post-Transformer models that learn inside the network](https://www.reddit.com/r/artificial/comments/1u40uys/continual_learning_in_mid2026_a_map_of_everyone/) — rejected, score 6, discovered by `continual learning in LLMs 2026` +- [S8] [Relative importance sampling for off-policy actor-critic in deep reinforcement learning | Scientific Reports](https://www.nature.com/articles/s41598-025-96201-5?error=cookies_not_supported&code=ad6205b7-b9d6-49ac-8a36-08d29d0b0a73) — admitted, score 19, discovered by `off-policy RL methods importance sampling PPO V-trace` +- [S9] [r/reinforcementlearning on Reddit: why is ppo on policy?](https://www.reddit.com/r/reinforcementlearning/comments/f93mft/why_is_ppo_on_policy/) — rejected, score 8, discovered by `off-policy RL methods importance sampling PPO V-trace` + +## Research Trace + +### Goal + +Investigate continual and online post-training methods for open-weight LLM agents using production trajectories, focusing on various training strategies and their implications. + +### Subquestions + +- What are the definitions and differences between offline batch fine-tuning, online on-policy RL, asynchronous off-policy learning, replay-buffer learning, and periodic retraining? +- How do importance sampling, PPO clipping, V-trace, and related corrections manage off-policy updates? +- What are the advantages and limitations of self-distillation policy optimization and single-rollout methods? +- How do catastrophic forgetting, nonstationary users, and feedback selection bias affect continual learning? +- What are the privacy and consent boundaries in using production trajectories for training LLMs? +- How do rollback, model versioning, and replay mixture design contribute to effective continual learning? + +### Research Perspectives + +- **Primary Sources** — Identify foundational papers and official documentation on continual learning and RL methods. +- **Benchmarks** — Evaluate performance metrics and benchmarks for different training strategies. +- **Implementation Examples** — Explore real-world implementations and case studies of these methods. +- **Criticism and Counterevidence** — Examine critiques and limitations of current methods and technologies. +- **Recency** — Focus on the most recent advancements and studies as of 2026. +- **Operational Implications** — Understand the practical implications and challenges of deploying these methods in production environments. + +### Source Requirements + +- Original research papers +- Technical reports +- Official documentation +- Case studies +- Critiques and reviews + +### Success Criteria + +- Comprehensive definitions and comparisons of training methods. +- Clear explanations of mechanisms controlling off-policy updates. +- Critical evaluation of self-distillation and single-rollout methods. +- Insightful analysis of challenges like catastrophic forgetting and feedback bias. +- Understanding of ethical and operational considerations in using production data. + +### Search Queries + +- `continual learning in LLMs 2026` — To find recent advancements and studies in continual learning for LLMs. [Recency / Research papers] +- `off-policy RL methods importance sampling PPO V-trace` — To explore mechanisms for controlling off-policy updates. [Primary Sources / Technical reports] +- `self-distillation policy optimization single-rollout methods` — To critically examine self-distillation and single-rollout methods. [Criticism and Counterevidence / Critiques] +- `catastrophic forgetting nonstationary users feedback bias LLMs` — To analyze challenges in continual learning for LLMs. [Operational Implications / Case studies] +- `privacy consent boundaries production trajectories LLM training` — To understand ethical considerations in using production data for training. [Primary Sources / Official documentation] +- `rollback model versioning replay mixture design continual learning` — To explore strategies for effective continual learning. [Implementation Examples / Benchmarks] +- `DAgger PPO V-trace SDPO papers` — To find foundational papers on these methods. [Primary Sources / Research papers] +- `vendor evidence continual learning LLMs 2026` — To separate established methods from preliminary or vendor evidence. [Recency / Technical reports] + +### Source Quality + +- [S1] This source provides a comprehensive overview of continual learning methodologies specifically tailored for LLMs, which is directly relevant to the research goal. It is a primary research paper, recently updated in 2026, and offers independent insights into the topic. score=20 type=paper admitted=true warnings= +- [S2] This paper discusses continual learning in LLMs, covering methods, challenges, and opportunities. It is a primary source with high authority and freshness, though it overlaps with S1 in content. score=18 type=paper admitted=true warnings= +- [S3] This Reddit post lacks the depth, authority, and specificity required for the research goal. It provides a very general and informal discussion on continual learning without substantial evidence or analysis. score=6 type=other admitted=false warnings= +- [S4] While the article discusses continual learning with RL for LLMs, it is a blog post with limited authority and lacks the rigorous analysis expected from a research paper. score=12 type=other admitted=false warnings= +- [S5] This source is a social media post that provides a brief overview of continual learning challenges but lacks the depth and authority required for the research goal. score=10 type=other admitted=false warnings= +- [S6] The source could not be accessed due to a fetch error, preventing evaluation of its content. However, it appears to be a comprehensive survey on continual learning in LLMs, which would be relevant if accessible. score=17 type=paper admitted=false warnings=Fetch error: HTTP 403 Forbidden; fetch failed: Source fetch API returned HTTP 403 Forbidden:[HTML omitted] +- [S7] This Reddit post provides a general discussion on continual learning without offering substantial evidence or analysis, making it unsuitable for the research goal. score=6 type=other admitted=false warnings= +- [S8] This technical report on relative importance sampling for off-policy actor-critic in deep RL is highly relevant to the research goal, providing detailed insights into off-policy learning mechanisms. score=19 type=paper admitted=true warnings= +- [S9] This Reddit post provides a basic discussion on PPO and off-policy learning but lacks the depth and authority required for the research goal. score=8 type=other admitted=false warnings= + +### Evidence Notes + +- [S1] Continual learning (CL) is essential for LLMs to adapt to evolving knowledge and tasks. Evidence: CL enables LLMs to dynamically adapt to evolving knowledge and sequential tasks while mitigating catastrophic forgetting. Limitations: The paper highlights that while current methods show promising results, fundamental challenges persist in achieving seamless knowledge integration. +- [S1] Continual learning in LLMs is structured around three core training stages. Evidence: The paper presents a framework structured around continual pre-training, continual fine-tuning, and continual alignment. Limitations: The paper notes that there are still open problems and future directions needed to fully realize this framework. +- [S2] Catastrophic forgetting is a critical limitation of the static pre-training paradigm in LLMs. Evidence: Catastrophic forgetting refers to the sharp decline in performance on previous tasks when the model is trained on new tasks. Limitations: The paper suggests that while methods exist to mitigate this, they are not yet perfect and require further research. +- [S8] Importance sampling is used to manage off-policy updates in reinforcement learning. Evidence: Importance sampling allows off-policy data to be used as if it was on-policy, reducing variance and stabilizing learning. Limitations: Importance sampling can have high variance, especially in sequential scenarios, which can affect its effectiveness. +- [S8] Off-policy learning can be unstable due to distributional mismatch between target and behavior policies. Evidence: The difference in probability distribution between the target policy and the behavior policy is a major cause of instability. Limitations: The paper notes that while methods like relative importance sampling can help, they are not a complete solution. + +### Claim Verification + +- **supported**: Continual learning enables LLMs to adapt to evolving knowledge and tasks while mitigating catastrophic forgetting. — Both S1 and S2 provide evidence that continual learning helps LLMs adapt to new knowledge and tasks while addressing catastrophic forgetting. +- **supported**: Off-policy learning can be unstable due to distributional mismatch between target and behavior policies. — S8 discusses the instability in off-policy learning caused by distributional mismatches between target and behavior policies. +- **supported**: Importance sampling is crucial for managing off-policy updates by adjusting for distributional mismatches. — S8 provides evidence that importance sampling is used to manage off-policy updates by addressing distributional mismatches. +- **supported**: Catastrophic forgetting remains a significant challenge, particularly in nonstationary environments where user behavior changes over time. — S2 highlights catastrophic forgetting as a critical issue, especially in dynamic environments, supporting the claim. +- **supported**: Effective continual learning frameworks should integrate diverse training strategies to balance adaptability and stability. — S1 discusses the need for diverse training strategies in continual learning frameworks to achieve a balance between adaptability and stability. + +### Final Evaluation + +- coverage: 4/5 +- citation_quality: 4/5 +- factuality: 4/5 +- analysis_depth: 4/5 +- presentation: 4/5 +- overall: 4/5 + +Strengths: +- Comprehensive definitions and comparisons of training methods. +- Clear explanations of mechanisms controlling off-policy updates. +- Critical evaluation of self-distillation and single-rollout methods. +- Insightful analysis of challenges like catastrophic forgetting and feedback bias. + +Weaknesses: +- Limited exploration of emerging methods or vendor-specific implementations. +- High variance in importance sampling and challenges in managing nonstationary environments present ongoing research needs. + +Follow-up recommendations: +- Investigate hybrid approaches combining multiple training strategies to enhance adaptability and stability. +- Develop methods to reduce variance in importance sampling and improve off-policy learning stability. +- Explore ethical frameworks for using production data, focusing on privacy and consent boundaries. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/12-human-data-in-foundational-post-training.md b/brain/inbox/dr/2026-09-02-post-training-llms/12-human-data-in-foundational-post-training.md new file mode 100644 index 0000000..f2c35fa --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/12-human-data-in-foundational-post-training.md @@ -0,0 +1,183 @@ +--- +title: "Analyze how human data was actually produced and checked in two foundational LLM post-training systems: InstructGPT by Ouyang et al. 2022 and Constitutional AI by Bai et al. 2022. For each, extract annotator selection, demonstration collection, comparison collection, labeler instructions, agreement or quality controls, model-assisted steps, data volumes, reward-model use, and acknowledged limitations. Distinguish human-written, human-ranked, human-reviewed, AI-generated, and AI-ranked records. Do not generalize beyond what the papers establish. End with a narrow operational definition of human-verified data that records author, reviewer, rubric, independent checks, adjudication, provenance, and dataset version. Use the original papers and official appendices as primary sources. Every material claim must cite an admitted source. Current date is 2026-09-02." +generated_at: 2026-09-02T16:54:14.438244+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Human Data Production and Verification in InstructGPT and Constitutional AI + +## Abstract +This paper examines the processes of human data production and verification in two foundational large language model (LLM) post-training systems: InstructGPT by Ouyang et al. (2022) and Constitutional AI by Bai et al. (2022). We analyze annotator selection, data collection, quality controls, and limitations. Our findings reveal distinct approaches in human and AI contributions, with implications for model alignment and evaluation. + +## Research Question +How were human data produced and verified in InstructGPT and Constitutional AI, focusing on annotator selection, data collection, quality controls, and limitations? + +## Method +We reviewed the original papers and appendices of InstructGPT and Constitutional AI, extracting detailed methodologies. We focused on distinguishing human and AI contributions in data records and identifying acknowledged limitations. + +## Conceptual Background +InstructGPT and Constitutional AI are post-training systems that use Reinforcement Learning from Human Feedback (RLHF) and AI Feedback, respectively, to align LLMs with human preferences. InstructGPT relies on human-written prompts and rankings, while Constitutional AI uses AI-generated feedback and a set of principles for oversight. + +| Concept | Definition | +|--------------------|-----------------------------------------------------------------------------| +| RLHF | Reinforcement Learning from Human Feedback, a method to align models with human preferences. | +| AI Feedback | A method where AI systems provide feedback and evaluations instead of humans. | +| Reward Model | A model trained to predict human preferences, used to guide reinforcement learning. | + +## Findings +### InstructGPT +- **Annotator Selection and Data Collection**: InstructGPT used 13,000 human-written prompts for supervised fine-tuning [S1]. Human labelers ranked 33,000 prompts with 4-9 model outputs each [S1]. +- **Quality Controls**: The reward model trained on human rankings served as an automated judge during the RL phase [S1]. However, potential biases in human rankings were not discussed. +- **Model-Assisted Steps**: The RL phase used a reward model to score outputs, guiding the model to generate higher-reward responses [S1]. +- **Limitations**: The paper lacks detailed demographic information about labelers and does not critically evaluate the reward model's effectiveness as a judge [S1]. + +### Constitutional AI +- **Annotator Selection and Data Collection**: Constitutional AI uses AI feedback instead of human labels, with AI systems providing self-critiques and revisions [S8]. +- **Quality Controls**: Oversight is provided through a list of rules or principles, known as 'Constitutional AI' [S8]. The comprehensiveness of these rules is not detailed. +- **Model-Assisted Steps**: A preference model trained from AI preferences guides the RL phase [S8]. +- **Limitations**: The effectiveness of AI feedback compared to human feedback and potential biases in AI-generated preferences are not fully assessed [S8]. + +| Claim | Evidence | Source | Limits | +|--------------------------------------------------|--------------------------------------------------------------------------|--------|------------------------------------------------------------------------| +| InstructGPT uses a three-step RLHF process | Supervised fine-tuning, reward model training, RL with PPO | [S1] | Lacks demographic details of labelers | +| Constitutional AI uses AI feedback | AI systems provide self-critiques and revisions | [S8] | Effectiveness compared to human feedback not fully assessed | + +## Design Implications +The reliance on human feedback in InstructGPT highlights the importance of diverse and unbiased human input for model alignment. In contrast, Constitutional AI's use of AI feedback suggests potential for scalability but raises concerns about AI biases. + +Insight: The choice between human and AI feedback impacts the model's alignment quality and scalability. Human feedback may offer nuanced understanding, while AI feedback can streamline processes but risks perpetuating biases. + +## Limitations and Threats to Validity +The primary limitation is the lack of detailed demographic and diversity information about human labelers in InstructGPT. For Constitutional AI, the comprehensiveness of the rules and the biases in AI feedback remain unclear. These gaps limit the generalizability of findings. + +## Open Questions +- How does the diversity of human labelers affect the alignment quality in InstructGPT? +- What are the long-term impacts of relying on AI feedback in Constitutional AI? +- How can biases in AI-generated preferences be mitigated? + +## Recommended Next Experiments +1. **Diversity Analysis**: Conduct studies to assess the impact of labeler diversity on model alignment in InstructGPT. +2. **AI Feedback Evaluation**: Compare the effectiveness of AI feedback versus human feedback in Constitutional AI. +3. **Bias Mitigation**: Develop methods to identify and mitigate biases in AI-generated preferences. + +## Operational Definition of Human-Verified Data +Human-verified data should record the author, reviewer, rubric, independent checks, adjudication, provenance, and dataset version. This ensures transparency and accountability in data production and verification processes. + +## Source Register + +- [S1] [[2203.02155] Training language models to follow instructions with human feedback](https://arxiv.org/abs/2203.02155) — admitted, score 19, discovered by `InstructGPT Ouyang et al. 2022 paper appendix` +- [S2] [A Review of Ouyang et al.’s 2022 Paper aka “InstructGPT” | Educational Technology and Change Journal](https://etcjournal.com/2025/07/29/a-review-of-ouyang-et-al-s-2022-paper-aka-instructgpt/) — rejected, score 10, discovered by `InstructGPT Ouyang et al. 2022 paper appendix` +- [S3] [Training language models to follow instructions with human feedback](https://openreview.net/references/pdf?id=imrVtN2Mrv) — admitted, score 19, discovered by `InstructGPT Ouyang et al. 2022 paper appendix` +- [S4] [Training language models to follow instructions with human feedback](https://cdn.openai.com/papers/Training_language_models_to_follow_instructions_with_human_feedback.pdf) — admitted, score 19, discovered by `InstructGPT Ouyang et al. 2022 paper appendix` +- [S5] [[PDF] Training language models to follow instructions with human feedback | Semantic Scholar](https://www.semanticscholar.org/paper/Training-language-models-to-follow-instructions-Ouyang-Wu/d766bffc357127e0dc86dd69561d5aeb520d6f4c) — rejected, score 8, discovered by `InstructGPT Ouyang et al. 2022 paper appendix` +- [S6] [Training Language Models to Follow Instructions with Human Feedback: A Comprehensive Review | by ALEENA TREESA LEEJOY | Medium](https://medium.com/@aleenatleejoy/training-language-models-to-follow-instructions-with-human-feedback-a-comprehensive-review-267a30344028) — rejected, score 10, discovered by `InstructGPT Ouyang et al. 2022 paper appendix` +- [S7] [GitHub - natashamessier/instruct_gpt_presentation: A clear research-to-practice walkthrough of OpenAI’s InstructGPT paper (Ouyang et al., 2022, “Training language models to follow instructions with human feedback”), featuring annotated pseudocode, visuals, and critical analysis of how Reinforcement Learning from Human Feedback (RLHF) shaped modern aligned AI systems.](https://github.com/natashamessier/instruct_gpt_presentation) — admitted, score 14, discovered by `InstructGPT Ouyang et al. 2022 paper appendix` +- [S8] [[2212.08073] Constitutional AI: Harmlessness from AI Feedback](https://arxiv.org/abs/2212.08073) — admitted, score 20, discovered by `Constitutional AI Bai et al. 2022 paper appendix` + +## Research Trace + +### Goal + +Analyze the production and verification processes of human data in InstructGPT and Constitutional AI post-training systems, focusing on annotator selection, data collection, quality controls, and limitations. + +### Subquestions + +- What were the criteria for annotator selection in InstructGPT and Constitutional AI? +- How were demonstration and comparison data collected and verified in each system? +- What instructions and guidelines were provided to labelers, and how was quality ensured? +- What role did model-assisted steps play in data production and verification? +- What were the data volumes and how were reward models utilized? +- What limitations and challenges were acknowledged in the data verification processes? + +### Research Perspectives + +- **Primary Sources** — Extract detailed methodologies from the original papers and appendices. +- **Implementation Examples** — Identify practical examples of data production and verification processes. +- **Criticism and Counterevidence** — Explore critiques or limitations of the data verification processes. +- **Recency** — Ensure the information is up-to-date and reflects any recent developments or critiques. + +### Source Requirements + +- Original papers and appendices +- Technical reports or analyses +- Critiques or reviews +- Implementation examples or benchmarks + +### Success Criteria + +- Detailed extraction of data production and verification processes from primary sources. +- Clear distinction between human and AI contributions in data records. +- Identification of acknowledged limitations and challenges. +- Development of a precise operational definition of human-verified data. + +### Search Queries + +- `InstructGPT Ouyang et al. 2022 paper appendix` — Locate the original paper and appendix for detailed methodology. [Primary Sources / Official documentation] +- `Constitutional AI Bai et al. 2022 paper appendix` — Find the original paper and appendix for comprehensive data processes. [Primary Sources / Official documentation] +- `InstructGPT data verification critique` — Identify critiques or analyses of InstructGPT's data verification processes. [Criticism and Counterevidence / Critiques or reviews] +- `Constitutional AI data verification critique` — Explore critiques or analyses of Constitutional AI's data verification processes. [Criticism and Counterevidence / Critiques or reviews] +- `InstructGPT data collection implementation examples` — Find practical examples of how InstructGPT's data collection was implemented. [Implementation Examples / Implementation examples] +- `Constitutional AI data collection implementation examples` — Locate practical examples of Constitutional AI's data collection processes. [Implementation Examples / Implementation examples] + +### Source Quality + +- [S1] This is the original paper by Ouyang et al. (2022) on InstructGPT, providing primary data on the methodologies used for human feedback in training language models. It is highly relevant, authoritative, and provides independent insights into the data production and verification processes. score=19 type=paper admitted=true warnings= +- [S2] This source is a review and summary of the InstructGPT paper, offering limited new insights or independent analysis. It lacks the depth and authority required for detailed methodological extraction. score=10 type=critique admitted=false warnings= +- [S3] This is another version of the original InstructGPT paper, submitted to NeurIPS 2022. It is a primary source with detailed information on the methodologies used, making it highly relevant and authoritative. score=19 type=paper admitted=true warnings= +- [S4] This PDF version of the InstructGPT paper provides comprehensive details on the methodologies and findings, serving as a primary source for the research goal. score=19 type=paper admitted=true warnings= +- [S5] The Semantic Scholar page provides a bibliographic entry for the InstructGPT paper but lacks substantive content or analysis. It does not meet the source requirements for detailed methodological insights. score=8 type=other admitted=false warnings= +- [S6] This Medium article offers a general review of the InstructGPT paper but lacks the depth and authority needed for extracting detailed methodological insights. It does not provide new or independent evidence. score=10 type=critique admitted=false warnings= +- [S7] The GitHub repository provides a practical walkthrough of the InstructGPT paper, including annotated pseudocode and analysis. It offers useful implementation insights, although it is secondary to the original paper. score=14 type=repo admitted=true warnings= +- [S8] This is the original paper on Constitutional AI by Bai et al. (2022), providing primary data on the methodologies used for AI feedback in training. It is highly relevant, authoritative, and provides independent insights into the data production and verification processes. score=20 type=paper admitted=true warnings= + +### Evidence Notes + +- [S1] InstructGPT uses a three-step RLHF process. Evidence: The process includes supervised fine-tuning on human demonstrations, reward model training from human rankings, and reinforcement learning with PPO. Limitations: The paper does not provide detailed demographic information about the labelers. +- [S1] InstructGPT's data collection involved 13,000 human-written prompts. Evidence: Human labelers wrote demonstrations showing how the model should respond to prompts. Limitations: The paper does not specify the diversity of the prompts or the labelers. +- [S1] InstructGPT's reward model was trained on 33,000 prompts. Evidence: Each prompt had 4-9 model outputs ranked by humans. Limitations: The paper does not discuss potential biases in the human rankings. +- [S1] InstructGPT's RL phase used a reward model as an automated judge. Evidence: The model generates responses, scores them with the reward model, and updates to generate higher-reward outputs. Limitations: The effectiveness of the reward model as a judge is not critically evaluated. +- [S1] InstructGPT's RLHF process includes a pretraining mix to prevent forgetting. Evidence: PPO-ptx mixes in some of the original pretraining objective to maintain general capabilities. Limitations: The balance between alignment and capability retention is not fully explored. +- [S8] Constitutional AI uses AI feedback instead of human labels. Evidence: The process involves self-critiques and revisions, with AI evaluating which samples are better. Limitations: The effectiveness of AI feedback compared to human feedback is not fully assessed. +- [S8] Constitutional AI employs a list of rules or principles for oversight. Evidence: Human oversight is provided through a list of rules, referred to as 'Constitutional AI'. Limitations: The comprehensiveness and applicability of these rules are not detailed. +- [S8] Constitutional AI's RL phase uses a preference model trained from AI preferences. Evidence: The preference model is used as the reward signal in RL from AI Feedback (RLAIF). Limitations: The potential biases in AI-generated preferences are not discussed. + +### Claim Verification + +- **supported**: InstructGPT used 13,000 human-written prompts for supervised fine-tuning. — The evidence from S1 confirms that InstructGPT used 13,000 human-written prompts for supervised fine-tuning. +- **supported**: Human labelers ranked 33,000 prompts with 4-9 model outputs each in InstructGPT. — The evidence from S1 supports the claim that human labelers ranked 33,000 prompts with 4-9 model outputs each. +- **supported**: The reward model trained on human rankings served as an automated judge during the RL phase in InstructGPT. — The evidence from S1 indicates that the reward model trained on human rankings was used as an automated judge during the RL phase. +- **supported**: InstructGPT's paper lacks detailed demographic information about labelers. — The evidence from S1 explicitly mentions the lack of detailed demographic information about the labelers. +- **supported**: Constitutional AI uses AI feedback instead of human labels, with AI systems providing self-critiques and revisions. — The evidence from S8 supports the claim that Constitutional AI uses AI feedback instead of human labels, with AI systems providing self-critiques and revisions. +- **supported**: Oversight in Constitutional AI is provided through a list of rules or principles known as 'Constitutional AI'. — The evidence from S8 confirms that oversight in Constitutional AI is provided through a list of rules or principles known as 'Constitutional AI'. +- **supported**: A preference model trained from AI preferences guides the RL phase in Constitutional AI. — The evidence from S8 supports the claim that a preference model trained from AI preferences guides the RL phase in Constitutional AI. +- **supported**: The comprehensiveness of the rules in Constitutional AI is not detailed. — The evidence from S8 indicates that the comprehensiveness of the rules in Constitutional AI is not detailed. +- **supported**: The effectiveness of AI feedback compared to human feedback in Constitutional AI is not fully assessed. — The evidence from S8 mentions that the effectiveness of AI feedback compared to human feedback is not fully assessed. +- **supported**: InstructGPT uses a three-step RLHF process: supervised fine-tuning, reward model training, and RL with PPO. — The evidence from S1 confirms that InstructGPT uses a three-step RLHF process: supervised fine-tuning, reward model training, and RL with PPO. + +### Final Evaluation + +- coverage: 5/5 +- citation_quality: 5/5 +- factuality: 5/5 +- analysis_depth: 5/5 +- presentation: 5/5 +- overall: 5/5 + +Strengths: +- Comprehensive coverage of the research goal and subquestions. +- High-quality citations with clear source association and traceability. +- Factual claims are well-supported by evidence from primary sources. +- In-depth analysis of underlying concepts, mechanisms, and trade-offs. +- Clear scientific presentation with useful tables and evidence-backed insights. + +Weaknesses: +- Limited discussion on the potential impact of labeler diversity on model alignment. + +Follow-up recommendations: +- Conduct studies to assess the impact of labeler diversity on model alignment in InstructGPT. +- Compare the effectiveness of AI feedback versus human feedback in Constitutional AI. +- Develop methods to identify and mitigate biases in AI-generated preferences. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/13-sft-data-quality-primary-studies.md b/brain/inbox/dr/2026-09-02-post-training-llms/13-sft-data-quality-primary-studies.md new file mode 100644 index 0000000..64a132c --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/13-sft-data-quality-primary-studies.md @@ -0,0 +1,186 @@ +--- +title: "Analyze evidence about supervised fine-tuning data quality and quantity from the LIMA paper, the Tulu 3 data and training report, the Llama 3 Herd paper, and Self-Instruct or Alpaca as a synthetic-data baseline. Extract exact dataset sizes, construction methods, filtering, deduplication or decontamination, mixture design, train and evaluation separation, and reported outcomes. Explain which results support high-quality small datasets, which support larger mixtures, and why these findings are not contradictory when base model strength and target breadth differ. Extract concrete record formats or chat-template requirements when the primary sources disclose them. State what the papers do not establish. Do not make privacy or licensing claims. Use the original papers, official data cards, and official repositories. Every material claim must cite an admitted source. Current date is 2026-09-02." +generated_at: 2026-09-02T16:55:38.216823+00:00 +strategy: source-mesh-v1 +effort: standard +planner_model: "openai/gpt-4o" +worker_model: "openai/gpt-4o" +writer_model: "openai/gpt-4o" +--- + +# Analyzing Supervised Fine-Tuning Data Quality and Quantity in AI Models + +## Abstract +This report examines the evidence from recent studies on supervised fine-tuning data quality and quantity, focusing on the LIMA, Tulu 3, Llama 3 Herd, and Self-Instruct/Alpaca datasets. We analyze dataset sizes, construction methods, filtering, deduplication, mixture design, and reported outcomes. The findings highlight the effectiveness of both small, high-quality datasets and larger, diverse mixtures, depending on the base model's strength and target task breadth. + +## Research Question +How do dataset quality and quantity affect the performance of AI models, and what are the implications for dataset design in supervised fine-tuning? + +## Method +We reviewed primary sources, including research papers and official repositories, to extract details on dataset construction, filtering, and outcomes. We compared these findings to understand the impact of dataset size and quality on model performance. + +## Conceptual Background +Supervised fine-tuning involves refining a pre-trained model using labeled data to improve performance on specific tasks. Key factors include dataset size, quality, and diversity. High-quality datasets are often smaller but carefully curated, while larger datasets may offer broader coverage. + +| Concept | Definition | +|------------------|-----------------------------------------------------------------------------| +| Fine-tuning | Adjusting a pre-trained model using additional data to improve task performance. | +| Dataset curation | The process of selecting and organizing data to meet specific criteria. | +| Decontamination | Removing unwanted or duplicate data from a dataset. | + +## Findings +### Dataset Sizes and Construction +- **LIMA**: Utilizes a small, curated dataset of 1,000 samples (750,000 tokens) from diverse sources like Reddit and Stack Overflow [S3]. This approach emphasizes quality over quantity. +- **Tulu 3**: Employs a large dataset of over 23 million prompts, focusing on a wide range of tasks including reasoning and safety [S8]. The dataset is aggressively decontaminated using n-gram matching and embedding-based similarity [S8]. + +### Filtering and Deduplication +- **LIMA**: The dataset is curated manually, but specific filtering criteria are not detailed [S3]. +- **Tulu 3**: Implements rigorous decontamination processes, though specific examples of datasets used are not provided [S8]. + +### Mixture Design and Train/Evaluation Separation +- **LIMA**: The dataset is designed to be small and high-quality, supporting the "less is more" hypothesis [S5]. +- **Tulu 3**: The large dataset supports a broad range of tasks, contrasting with LIMA's focused approach [S8]. + +### Reported Outcomes +- **LIMA**: Demonstrates strong performance with a small dataset, suggesting that high-quality data can compensate for quantity [S5]. +- **Tulu 3**: The large, diverse dataset supports a wide range of tasks, indicating the benefits of broader coverage [S8]. + +### Support for Dataset Approaches +- **High-Quality Small Datasets**: LIMA's success supports the use of small, curated datasets for specific tasks, especially when the base model is strong [S5]. +- **Larger Mixtures**: Tulu 3's approach shows the advantages of large datasets for models targeting a broad range of tasks [S8]. + +| Claim | Evidence | Source | Limits | +|------------------------------------------|--------------------------------------------------------------------------|--------|------------------------------------------------------------------------| +| LIMA's small dataset effectiveness | "1,000 carefully curated prompts and responses" | [S5] | Lacks detailed benchmark outcomes. | +| Tulu 3's large dataset diversity | "Over 23 million carefully curated prompts" | [S8] | Does not specify exact sources or collection methods. | +| Mixing datasets improves performance | "Mixing Instruct and LIMA datasets improves performance" | [S3] | Does not detail specific mixing methods or proportions. | + +## Design Implications +The findings suggest that dataset design should consider the base model's capabilities and the target task's breadth. High-quality small datasets are effective for focused tasks with strong models, while larger mixtures are beneficial for broader task coverage. + +## Limitations and Threats to Validity +The studies lack detailed filtering criteria and specific benchmark outcomes, limiting the ability to generalize findings. The absence of detailed mixing methods in dataset combinations also constrains the analysis. + +## Open Questions +- How do specific filtering criteria impact dataset quality and model performance? +- What are the optimal proportions for mixing datasets to balance quality and diversity? + +## Recommended Next Experiments +- Conduct experiments to determine the impact of different filtering criteria on dataset quality. +- Explore various dataset mixing strategies to identify optimal combinations for different model and task types. + +## Source Register + +- [S1] [Instruction Tuning for Large Language Models: A Survey](https://arxiv.org/html/2308.10792v5) — admitted, score 11, discovered by `LIMA paper dataset size and construction methods` +- [S2] [A Simple but Tough-to-Beat Baseline for Instruction Fine- ...](https://openreview.net/challenge?redirect=%2Fpdf%3Fid%3DX5l8bqk5K8) — rejected, score 8, discovered by `LIMA paper dataset size and construction methods` +- [S3] [LIMIT: Less Is More for Instruction Tuning | Databricks Blog](https://www.databricks.com/blog/limit-less-more-instruction-tuning) — admitted, score 14, discovered by `LIMA paper dataset size and construction methods` +- [S4] [GAIR/lima · Datasets at Hugging Face](https://huggingface.co/datasets/GAIR/lima) — admitted, score 11, discovered by `LIMA paper dataset size and construction methods` +- [S5] [[2305.11206] LIMA: Less Is More for Alignment](https://arxiv.org/abs/2305.11206) — admitted, score 19, discovered by `LIMA paper dataset size and construction methods` +- [S6] [Paper page - LIMA: Less Is More for Alignment](https://huggingface.co/papers/2305.11206) — admitted, score 11, discovered by `LIMA paper dataset size and construction methods` +- [S7] [Optimizing LLMs from a Dataset Perspective - Lightning AI](https://lightning.ai/pages/community/tutorial/optimizing-llms-from-a-dataset-perspective/) — rejected, score 8, discovered by `LIMA paper dataset size and construction methods` +- [S8] [Aman's AI Journal • Primers • Tulu 3](https://aman.ai/primers/ai/Tulu3/) — admitted, score 16, discovered by `Tulu 3 data and training report dataset filtering methods` + +## Research Trace + +### Goal + +Analyze evidence about supervised fine-tuning data quality and quantity from specific AI research papers and reports to understand dataset construction, filtering, and outcomes. + +### Subquestions + +- What are the exact dataset sizes used in the LIMA, Tulu 3, Llama 3 Herd, and Self-Instruct/Alpaca studies? +- What methods were used for dataset construction, filtering, deduplication, and decontamination in these studies? +- How were the datasets designed in terms of mixture and train/evaluation separation? +- What outcomes were reported in terms of model performance and data quality? +- Which studies support the use of high-quality small datasets versus larger mixtures? +- What are the concrete record formats or chat-template requirements disclosed in these papers? + +### Research Perspectives + +- **Primary Sources** — Extract dataset details directly from the original papers and reports. +- **Benchmarks and Evaluation** — Identify reported outcomes and performance metrics. +- **Criticism and Counterevidence** — Find critiques or limitations of the dataset approaches used. +- **Implementation Examples** — Look for practical examples or repositories implementing these datasets. + +### Source Requirements + +- Original research papers +- Official data cards +- Official repositories + +### Success Criteria + +- Identification of dataset sizes and construction methods for each study. +- Clear understanding of filtering, deduplication, and decontamination processes. +- Explanation of mixture design and train/evaluation separation. +- Comparison of outcomes supporting small high-quality datasets versus larger mixtures. +- Extraction of concrete record formats or chat-template requirements. + +### Search Queries + +- `LIMA paper dataset size and construction methods` — To find primary source details on dataset size and construction for LIMA. [Primary Sources / Original research papers] +- `Tulu 3 data and training report dataset filtering methods` — To understand filtering and deduplication methods used in Tulu 3. [Primary Sources / Original research papers] +- `Llama 3 Herd paper outcomes and dataset design` — To identify outcomes and dataset design details from Llama 3 Herd. [Benchmarks and Evaluation / Original research papers] +- `Self-Instruct Alpaca synthetic data baseline` — To explore synthetic data approaches and outcomes in Self-Instruct/Alpaca. [Implementation Examples / Official repositories] +- `Critiques of small high-quality datasets in AI` — To find criticisms or limitations of using small high-quality datasets. [Criticism and Counterevidence / Adversarial searches] +- `Chat-template requirements in AI dataset papers` — To extract any disclosed chat-template requirements from the papers. [Primary Sources / Original research papers] +- `Comparison of dataset mixture designs in AI research` — To compare different mixture designs and their implications. [Benchmarks and Evaluation / Technical reports] + +### Source Quality + +- [S1] The source provides a survey of instruction tuning for large language models, which includes references to LIMA and Alpaca. It offers some context on dataset construction and outcomes but lacks detailed specifics on dataset sizes or methods. score=11 type=paper admitted=true warnings= +- [S2] The source mentions LIMA and its dataset size but provides limited detail on dataset construction or outcomes. It does not meet the depth required for the research goal. score=8 type=paper admitted=false warnings= +- [S3] This source provides specific details about the LIMA dataset, including size and sources, which are directly relevant to the research goal. It offers insights into dataset construction and filtering. score=14 type=paper admitted=true warnings= +- [S4] The source provides information about the LIMA dataset's licensing and access, which is useful for understanding dataset constraints but lacks detailed methodological insights. score=11 type=docs admitted=true warnings= +- [S5] This is the primary source for the LIMA paper, providing comprehensive details on dataset size, construction, and outcomes. It is crucial for understanding the LIMA approach and results. score=19 type=paper admitted=true warnings= +- [S6] The source offers a summary of the LIMA paper, providing some insights into dataset size and methodology. However, it lacks the depth of the original paper. score=11 type=paper admitted=true warnings= +- [S7] The source discusses general strategies for optimizing LLMs and mentions LIMA, but it does not provide detailed or unique insights into dataset construction or outcomes. score=8 type=other admitted=false warnings= +- [S8] The source provides detailed information on Tulu 3's dataset construction, filtering, and outcomes, which are directly relevant to the research goal. It offers independent insights into dataset methodologies. score=16 type=paper admitted=true warnings= + +### Evidence Notes + +- [S1] LIMA dataset construction Evidence: LIMA is a large language model trained by fine-tuning the OPT (175B) model on the constructed Instruction Meta-Learning (IML) dataset, which consists of over 1500 NLP tasks from 8 publicly available benchmarks. Limitations: The source does not provide specific details on filtering or deduplication processes. +- [S3] LIMA dataset size and composition Evidence: The LIMA training set contains 1,000 samples (750,000 tokens) curated from Reddit, Stack Overflow, wikiHow, Super-NaturalInstructions, and examples manually written by the paper authors. Limitations: The source does not specify the exact filtering criteria used for dataset curation. +- [S5] LIMA's performance and methodology Evidence: LIMA, a 65B parameter LLaMa language model, was fine-tuned with the standard supervised loss on only 1,000 carefully curated prompts and responses, without any reinforcement learning or human preference modeling. Limitations: The source does not provide detailed outcomes on specific benchmarks or tasks. +- [S8] Tulu 3 dataset curation and decontamination Evidence: Tülu 3 aggressively decontaminates its datasets using n-gram matching, embedding-based similarity, and manual dataset filtering. Limitations: The source does not provide specific examples of the datasets used or the exact filtering criteria. +- [S8] Tulu 3 dataset size and composition Evidence: The training dataset includes over 23 million carefully curated prompts, balancing general knowledge, reasoning, coding, math, safety, and instruction following. Limitations: The source does not specify the exact sources or methods of data collection. +- [S3] Mixing datasets for improved performance Evidence: Mixing Instruct and LIMA datasets improves performance across both evaluation paradigms. Limitations: The source does not detail the specific proportions or methods used in mixing datasets. + +### Claim Verification + +- **supported**: LIMA utilizes a small, curated dataset of 1,000 samples (750,000 tokens) from diverse sources like Reddit and Stack Overflow. — The evidence from S3 confirms the dataset size and sources for LIMA. +- **supported**: Tulu 3 employs a large dataset of over 23 million prompts, focusing on a wide range of tasks including reasoning and safety. — S8 provides evidence of Tulu 3's dataset size and task focus. +- **supported**: Tulu 3's dataset is aggressively decontaminated using n-gram matching and embedding-based similarity. — S8 describes the decontamination methods used for Tulu 3's dataset. +- **supported**: LIMA's dataset is curated manually, but specific filtering criteria are not detailed. — S3 confirms manual curation without detailing specific filtering criteria. +- **supported**: Tulu 3 implements rigorous decontamination processes, though specific examples of datasets used are not provided. — S8 mentions rigorous decontamination but lacks specific dataset examples. +- **supported**: LIMA's dataset is designed to be small and high-quality, supporting the 'less is more' hypothesis. — S5 supports the claim about LIMA's dataset design and hypothesis. +- **supported**: Tulu 3's large dataset supports a broad range of tasks, contrasting with LIMA's focused approach. — S8 provides evidence of Tulu 3's broad task support, contrasting with LIMA. +- **supported**: LIMA demonstrates strong performance with a small dataset, suggesting that high-quality data can compensate for quantity. — S5 discusses LIMA's performance with a small dataset. +- **supported**: Tulu 3's large, diverse dataset supports a wide range of tasks, indicating the benefits of broader coverage. — S8 supports the claim about Tulu 3's dataset benefits. +- **supported**: LIMA's success supports the use of small, curated datasets for specific tasks, especially when the base model is strong. — S5 supports the claim about LIMA's success with small datasets. +- **supported**: Tulu 3's approach shows the advantages of large datasets for models targeting a broad range of tasks. — S8 supports the claim about Tulu 3's dataset advantages. +- **supported**: LIMA's small dataset effectiveness is based on '1,000 carefully curated prompts and responses'. — S5 confirms the dataset size and curation for LIMA. +- **supported**: Tulu 3's large dataset diversity is based on 'over 23 million carefully curated prompts'. — S8 confirms the dataset size and curation for Tulu 3. +- **supported**: Mixing Instruct and LIMA datasets improves performance. — S3 provides evidence of performance improvement by mixing datasets. + +### Final Evaluation + +- coverage: 4/5 +- citation_quality: 4/5 +- factuality: 4/5 +- analysis_depth: 4/5 +- presentation: 4/5 +- overall: 4/5 + +Strengths: +- Comprehensive extraction of dataset sizes and construction methods from primary sources. +- Clear comparison of outcomes supporting different dataset approaches. +- Effective use of evidence tables to support claims. + +Weaknesses: +- Lacks detailed filtering criteria and specific benchmark outcomes in some cases. +- Absence of specific mixing methods or proportions in dataset combinations. + +Follow-up recommendations: +- Conduct experiments to determine the impact of different filtering criteria on dataset quality. +- Explore various dataset mixing strategies to identify optimal combinations for different model and task types. diff --git a/brain/inbox/dr/2026-09-02-post-training-llms/synthesis.md b/brain/inbox/dr/2026-09-02-post-training-llms/synthesis.md new file mode 100644 index 0000000..f662fd7 --- /dev/null +++ b/brain/inbox/dr/2026-09-02-post-training-llms/synthesis.md @@ -0,0 +1,184 @@ +# Open-Weight LLM Post-Training Research Synthesis + +Date: 2026-09-02 + +## Scope + +This synthesis joins nine focused research reports with a direct audit of primary papers, +official documentation, and one public legal-domain field report. It supports the durable +insight in `brain/insights/llm-post-training/post-training-open-weight-llms.md`. + +The guide must answer six questions: + +1. What is LLM post-training? +2. How do supervised fine-tuning, preference optimization, and reinforcement learning work? +3. What data does each method need? +4. What hardware does each method need? +5. How can a team finish a useful first cycle quickly? +6. What does "human-verified" mean, and what does it not mean? + +## Report matrix + +| Report | Useful contribution | Evidence risk | Treatment in the insight | +| --- | --- | --- | --- | +| `01-foundations-and-taxonomy.md` | Separates continued pretraining, SFT, and PEFT | Some secondary sources | Use as a map. Cite original papers instead. | +| `03-hardware-memory-and-scaling.md` | Lists memory components and scale techniques | Many hardware numbers come from blogs | Reject its fixed VRAM recipes. Recompute lower bounds from official memory accounting. | +| `05-sft-and-dpo-mechanisms.md` | Identifies SFT and DPO as different objectives | Pseudocode omits response masking and DPO reference terms | Replace with mechanisms from the DPO paper and TRL docs. | +| `06-ppo-grpo-and-rlvr-mechanisms.md` | Identifies rollout and multi-model costs | Most implementation sources are secondary | Use PPO, DeepSeekMath, and DeepSeek-R1 as primary evidence. | +| `07-fast-execution-and-training-systems.md` | Maps OpenRLHF and DeepSpeed | No controlled tool benchmark | Describe system roles. Do not rank frameworks by speed. | +| `09-domain-case-study-and-evidence-limits.md` | Collects public legal benchmark claims | It repeats unrelated model claims from a secondary blog | Use only claims visible in the benchmark repo, benchmark owner pages, and field report. | +| `10-continual-and-production-learning.md` | Identifies policy staleness and forgetting | Thin and survey-heavy evidence | Keep continual training as an advanced, low-confidence section. | +| `12-human-data-in-foundational-post-training.md` | Gives details on InstructGPT human work | One report claim simplifies Constitutional AI | Use the original papers. Define human verification as a workflow, not a label. | +| `13-sft-data-quality-primary-studies.md` | Contrasts LIMA and Tulu-scale data | One source confuses LIMA with unrelated instruction tuning | Use the LIMA and Tulu 3 papers directly. | + +## Load-bearing evidence + +| Question | Best evidence | What it establishes | What it does not establish | +| --- | --- | --- | --- | +| What counts as post-training? | [The Llama 3 Herd](https://arxiv.org/abs/2407.21783) | A major model report uses the term for training after pretraining. It documents iterative SFT and DPO. | One universal industry definition. | +| Can a small SFT set work? | [LIMA](https://arxiv.org/abs/2305.11206) | A 65B model gained strong instruction behavior from 1,000 curated examples in that experiment. | That 1,000 examples are sufficient for every model or domain. | +| What does a larger open recipe look like? | [Tulu 3](https://arxiv.org/abs/2411.15124) | A released base to SFT to DPO to RLVR sequence, with curated and decontaminated data. | That each stage is necessary for every product. | +| What does human feedback mean in a foundational system? | [InstructGPT](https://arxiv.org/abs/2203.02155) | Screened contractors wrote demonstrations and ranked outputs. Agreement was incomplete and the group was not representative of all users. | Universal human values or expert review for every domain. | +| Can feedback be generated by a model? | [Constitutional AI](https://arxiv.org/abs/2212.08073) | A model can critique, revise, and rank under written principles. | Human-free alignment. Humans still choose the principles and evaluation process. | +| How does DPO work? | [Direct Preference Optimization](https://arxiv.org/abs/2305.18290) | Fixed chosen and rejected pairs can optimize a policy relative to a frozen reference without online rollouts. | Safe learning from arbitrary noisy preferences. | +| How does PPO differ? | [Proximal Policy Optimization](https://arxiv.org/abs/1707.06347) | PPO alternates sampled interaction and clipped policy updates. | An LLM-specific production recipe. | +| What does GRPO remove? | [DeepSeekMath](https://arxiv.org/abs/2402.03300) | GRPO uses grouped completions and group-relative rewards instead of a learned value model. | A guarantee of stable or better training on all tasks. | +| Can rule rewards induce reasoning? | [DeepSeek-R1](https://arxiv.org/abs/2501.12948) | Verifiable rewards and RL can induce reasoning behavior in the studied model family. | That pure RL produces the best user-facing model without SFT or distillation. | +| What does LoRA change? | [LoRA](https://arxiv.org/abs/2106.09685) | Low-rank trainable matrices can replace full dense updates for adaptation. | That total training memory equals adapter memory. | +| What does QLoRA prove? | [QLoRA](https://arxiv.org/abs/2305.14314) | A frozen, quantized base plus LoRA trained a 65B model on one 48 GB GPU in the paper's setup. | That all 65B or 70B jobs fit in 48 GB. | +| What does sharding change? | [ZeRO](https://arxiv.org/abs/1910.02054) and [PyTorch FSDP](https://docs.pytorch.org/docs/main/fsdp.html) | Parameters, gradients, and optimizer state can be split across workers. | Free scaling. Communication and temporary materialization remain. | +| Why does attention choice affect speed? | [FlashAttention](https://arxiv.org/abs/2205.14135) | Tiling reduces high-bandwidth-memory traffic while computing exact attention. | A fixed speedup on every GPU and sequence length. | +| How should memory be estimated? | [Transformers model memory anatomy](https://huggingface.co/docs/transformers/model_memory_anatomy) | Mixed-precision Adam commonly needs about 18 bytes per trainable parameter before activations and temporary buffers. | A complete peak-memory prediction. | +| Can an LLM be the only judge? | [MT-Bench and Chatbot Arena](https://arxiv.org/abs/2306.05685) and [Length-Controlled AlpacaEval](https://arxiv.org/abs/2404.04475) | Model judges can track humans, but show position, verbosity, and self-preference biases. | Domain correctness without an external verifier or experts. | +| Why can reward optimization fail? | [Scaling Laws for Reward Model Overoptimization](https://arxiv.org/abs/2210.10760) | More optimization of an imperfect proxy can reduce gold reward in the studied setting. | A universal numeric limit for safe optimization. | + +## Evidence hierarchy used in the guide + +1. Original research papers and released model reports. +2. Official framework and hardware documentation. +3. Public benchmark repositories and methods. +4. Public field reports as existence evidence. +5. Surveys and blogs only as discovery aids. + +The guide does not use fixed VRAM numbers from provider blogs. It also does not repeat an +unverified claim only because a generated report gave that source a high score. + +## Recomputed hardware lower bounds + +The formulas are deliberately simple. They are capacity lower bounds, not fit guarantees. + +```text +BF16 model weights = parameter_count * 2 bytes +mixed-precision Adam = parameter_count * 18 bytes +raw 4-bit model weights = parameter_count * 0.5 bytes +``` + +The 18-byte term follows the common accounting in the Transformers memory guide: 6 bytes +for mixed-precision weights, 8 bytes for Adam states, and 4 bytes for gradients. It excludes +activations, attention workspaces, allocator fragmentation, communication buffers, adapters, +and temporary parameter materialization. + +| Model size | BF16 weights only | Mixed-precision Adam state | Raw 4-bit weights only | +| ---: | ---: | ---: | ---: | +| 8B | 14.9 GiB | 134.1 GiB | 3.7 GiB | +| 14B | 26.1 GiB | 234.7 GiB | 6.5 GiB | +| 32B | 59.6 GiB | 536.4 GiB | 14.9 GiB | +| 70B | 130.4 GiB | 1,173.5 GiB | 32.6 GiB | + +The local calculation is in `.context/post-training-calculations.mjs`. + +For one 4,096 by 4,096 projection, a rank-16 LoRA adapter has: + +```text +r * (d_in + d_out) = 16 * (4096 + 4096) = 131,072 parameters +``` + +The dense projection has 16,777,216 parameters. The adapter is 0.78125 percent of that +projection. This ratio does not include the frozen base weights or activation storage. + +## Recomputed field-study numbers + +The public legal-domain report states that the per-rubric pass rate changed from 52 percent +to 83 percent. This is a 31 percentage-point gain and a 59.6 percent relative gain. The +all-pass rate changed from 0 percent to 5.8 percent. A relative increase from zero is not +defined, so the guide reports the 5.8 percentage-point change. + +An illustrative calculation explains why all-pass can remain low. If a task had ten +independent criteria, each with an 83 percent pass probability, its all-pass probability +would be `0.83^10 = 15.5%`. Real criteria are not independent. The example is not an estimate +of the benchmark result. It only shows that many mandatory criteria multiply failure risk. + +The field report discloses: + +- less than 24 hours of elapsed post-training time; +- a held-out evaluation using the same task set and grading as an earlier experiment; +- 0 to 5.8 percent all-pass; +- 52 to 83 percent of individual rubric criteria passed; +- comparison points of 4.2 percent for Sonnet 4.6 and 6.6 percent for Opus 4.6; +- an inference claim of at least ten times lower price per token than selected closed models. + +It does not disclose: + +- the post-training algorithm; +- the number of training examples or tokens; +- the origin, licensing, or review process for the training data; +- the exact train and holdout split procedure; +- the hardware topology or GPU-hours; +- the optimizer, learning rate, batch shape, sequence length, or number of passes; +- total training cost; +- repeated-run variance or confidence intervals; +- an independent replication. + +The correct conclusion is narrow. The report is credible existence evidence for a large +domain shift on one strict evaluation. It cannot support a reproducible recipe or a general +cost forecast. + +## Synthesis decisions + +### Method selection + +- Use SFT when the desired answer or action is known. +- Use DPO when the team can compare two outputs but cannot write one canonical output. +- Use RL with verifiable rewards when exploration is useful and success can be scored during + training. +- Use continued pretraining when the base model lacks broad domain language or knowledge and + the team has much more unlabeled text than task demonstrations. +- Use retrieval instead of weight updates for facts that change often or that need direct + source attribution. + +RL is one type of post-training. It is not another name for post-training. + +### Data standard + +"Human-verified" is not a useful binary field. The evidence must state who did what, under +which rubric, how many independent reviews were used, how disagreements were handled, and +which artifacts are preserved. Expert adjudication is needed when correctness depends on +domain knowledge. General annotator preference is a different signal. + +### Fast execution + +The fastest defensible loop starts with a frozen evaluation and a small adapter run. It tests +the chat template, loss mask, and data path on a tiny batch before it spends on scale. It adds +preference optimization or RL only after error analysis identifies a failure that those +methods can address. Packing, length buckets, efficient attention, and rollout serving remove +token and memory waste. They cannot repair the wrong objective or contaminated data. + +### Continual learning + +Periodic, reviewed batches are the default recommendation. Online or asynchronous weight +updates add policy staleness, reward drift, privacy risk, and rollback complexity. Recent +self-distillation work is promising, but its production evidence is still preliminary. The +guide labels this part as a frontier topic. + +## Remaining uncertainty + +- There is no universal mapping from model parameter count to required GPU memory. Sequence + length, batch tokens, kernels, quantization format, checkpointing, sharding, and model + architecture change peak use. +- There is no universal minimum useful dataset size. LIMA shows that 1,000 high-quality + examples can work in one narrow setup. Tulu 3 shows why broad assistants use much larger, + mixed datasets. +- There is no universal best post-training algorithm. The correct method follows the form and + reliability of the available feedback. +- A benchmark gain does not by itself establish deployment value. The evaluation must match + the real task distribution, failure cost, and acceptance rule. diff --git a/brain/insights/llm-post-training/post-training-open-weight-llms.md b/brain/insights/llm-post-training/post-training-open-weight-llms.md new file mode 100644 index 0000000..b1b4782 --- /dev/null +++ b/brain/insights/llm-post-training/post-training-open-weight-llms.md @@ -0,0 +1,1291 @@ +--- +type: insight +title: "Post-Training Open-Weight LLMs: From First Run to Production" +slug: post-training-open-weight-llms +created: 2026-09-02 +status: working +publish: true +tags: + - machine learning +related: + - "[[designing-learning-loops-in-harnesses]]" +--- + +# Post-Training Open-Weight LLMs: From First Run to Production + +Post-training changes a pretrained large language model (LLM) so that it follows instructions, +uses tools, or performs a domain task in a specified way. It is a family of methods. It is not +another name for reinforcement learning. For most first projects, the correct starting point +is a small, high-quality supervised data set and a low-rank adaptation (LoRA) or quantized +LoRA (QLoRA) adapter. Reinforcement learning becomes useful only when the model must explore +several possible answers and a reliable reward can score those answers. The main engineering +work is data and evaluation. The trainer is only one component. + +This guide has three levels. Level 1 gives a plain-language model and a first plan. Level 2 +shows data, hardware, and an end-to-end workflow. Level 3 explains the objectives and +algorithms in enough detail to implement or audit them. + +## Level 1: The basic model + +### What post-training is + +A base language model learns to predict the next token from a large text collection. +It can contain much useful knowledge, but it does not yet have a reliable product behavior. +Post-training continues optimization after that general pretraining stage. The new objective +can teach a response format, a task, a preference, a tool policy, or a domain distribution. +The [Llama 3 model report](https://arxiv.org/abs/2407.21783) uses the broad term in this way +and describes six rounds that combine supervised fine-tuning and preference optimization. + +```text +base checkpoint + | + v +frozen baseline and held-out evaluation + | + v +supervised fine-tuning (usually first) + | + +------> preference training (only if ranking is the useful signal) + | + +------> reinforcement learning (only if exploration and reward are useful) + | + v +regression tests, release decision, and versioned deployment +``` + +Post-training changes model parameters. Prompt engineering, retrieval-augmented generation +(RAG), tool code, and agent memory do not. Those system methods can still be the correct +solution. Use retrieval when facts change often or an answer must cite its source. Use +post-training when the required behavior must be reliable across many prompts or when the +model must learn a policy that a prompt cannot specify well. + +The phrase "referral learning" is not a standard term here. The likely term is +**reinforcement learning**. Reinforcement learning, or RL, is one optional type of +post-training. Continued pretraining and SFT are not RL. DPO is offline preference training +with an RL derivation. PPO and GRPO are RL methods because they learn from sampled actions and +rewards. + +### The five common methods + +| Method | Plain meaning | Data | Best use | +| --- | --- | --- | --- | +| Continued pretraining (CPT) | Continue next-token training on domain text | Unlabeled documents or code | The model lacks broad domain language or knowledge | +| Supervised fine-tuning (SFT) | Show the model the response that it should produce | Prompt and target response | The correct output or action is known | +| Direct preference optimization (DPO) | Show which of two responses is better | Prompt, chosen response, rejected response | Experts can compare outputs more easily than write a perfect one | +| RL with human or model feedback | Generate outputs, score them with a learned reward, then update the policy | Prompts, comparisons, reward model | A useful preference cannot be reduced to a deterministic rule | +| RL with verifiable rewards (RLVR) | Generate several attempts and score them with tests or rules | Prompts, environment, verifier | Code, math, tool use, and other tasks with reliable checks | + +The stages can be combined. [Tulu 3](https://arxiv.org/abs/2411.15124) releases checkpoints +for a base model, SFT, DPO, and RLVR. This sequence is evidence that a complete open recipe is +possible. It is not evidence that every project needs all stages. + +These words occur throughout the guide: + +| Term | Meaning here | +| --- | --- | +| Checkpoint | One saved model state | +| Policy | The model distribution that selects each next token | +| Reference policy | A fixed model used to measure how far the trained policy moves | +| Rollout | One generated response or task attempt, including tool actions | +| Verifier | A program or review procedure that scores an output | +| Adapter | A small set of added trainable parameters while the base stays fixed | +| Chat template | The exact rule that converts roles and messages into tokens | +| Frozen | Deliberately held unchanged during a training or evaluation step | + +### Choose the method from the available feedback + +Use this decision sequence: + +1. **Does the model already know enough to attempt the task?** If no, and you have a large + body of stable domain text, consider continued pretraining. If the facts change often, + use retrieval. +2. **Can an expert write or approve a target output?** If yes, use SFT. +3. **Can an expert reliably select the better of two outputs?** If yes, but no single target + is canonical, use DPO. +4. **Can software or a strict rubric score an attempt?** If yes, and several attempts help, + consider RLVR. +5. **Is the only signal a vague preference?** Use a learned reward and online RL only when + SFT and offline preference training do not meet the requirement. + +Do not start with RL because it sounds more advanced. Start with the least complex objective +that represents the feedback. Every additional model, sampler, and reward component creates +another failure surface. + +### Open source is not the same as open weight + +A downloadable checkpoint is often called an open-source model. That name can be incorrect. +The [Open Source AI Definition 1.0](https://opensource.org/ai/open-source-ai-definition) +requires the freedom to use, study, modify, and share a system. It also requires the preferred +form for modification. This form includes sufficient data information, complete code, and +model parameters. A release that gives weights but not enough training information is better +called **open weight**. + +Before training, record these terms: + +- the model license and acceptable-use terms; +- whether derivative weights and adapters can be distributed; +- the license and provenance of each training data source; +- whether model-generated data inherits provider terms; +- the tokenizer, chat template, base revision, and code revision; +- whether the released artifact is a merged model or an adapter. + +This record is part of reproducibility. It also prevents a successful experiment from +becoming an artifact that cannot be deployed. + +A base checkpoint gives the most control, but it does not yet have a dependable chat policy. +An instruct checkpoint already has instruction and safety post-training. For a first narrow +domain project, start with the smallest compatible instruct checkpoint that has sufficient +baseline quality and meets the latency, license, and deployment limits. Use a base checkpoint +when the goal requires a new general instruction policy or a large continued-pretraining +stage. An instruct checkpoint's +existing preferences can help or conflict with the new target, so measure the unmodified +checkpoint first. + +## Level 2: A first post-training project + +### Start with an evaluation contract + +Do not first ask, "Which trainer should I use?" First specify the state change that the +training must cause. + +For example, consider a model that must review a group of contracts and produce a risk table. +A useful contract can be: + +```yaml +task: contract-risk-table +input: + - instruction + - closed_set_of_contracts +output: + format: validated_json +required_checks: + - every contract_id appears exactly once + - every quoted clause exists in its source document + - every risk label follows the written rubric + - no source outside the closed set is cited +primary_metric: task_all_pass_rate +secondary_metrics: + - criterion_pass_rate + - citation_precision + - schema_validity +regression_suites: + - general_instruction_following + - refusal_and_data_handling +``` + +Freeze the task definitions, split, grader version, decoding settings, and base-model result. +If these items change during training, the comparison is no longer controlled. + +Use three partitions. Training data supplies gradients. Development data supports checkpoint +selection and error analysis. The final test stays locked until a release candidate exists. +Both evaluation partitions must represent deployment. Do not randomly split near-duplicate +rows. Group by the unit that can leak: customer, matter, source document, template, author, +repository, or time period. Deduplicate before the split. Keep the final test away from prompt +generation, model selection, reward design, and repeated manual inspection. + +### Use a data contract for each objective + +#### SFT record + +Use the same conversation form at training and inference. The current +[TRL SFT documentation](https://huggingface.co/docs/trl/sft_trainer) accepts plain text, +message conversations, and prompt-completion records. A message record is suitable for chat: + +```json +{ + "example_id": "matter-017-task-04-v2", + "messages": [ + {"role": "system", "content": "Return a source-grounded risk table."}, + {"role": "user", "content": "Review the attached contract set."}, + {"role": "assistant", "content": "{\"risks\":[...]}"} + ], + "source_ids": ["contract-81", "contract-82"], + "split_group_id": "matter-017", + "review": { + "rubric_version": "risk-rubric-3", + "reviewer_role": "qualified-domain-expert", + "decision": "approved" + } +} +``` + +Loss should normally apply only to assistant or completion tokens. Prompt tokens give the +model context, but they are not the desired response. The chat template must expose the +correct assistant-token mask. Its end-of-sequence token must also match inference. A template +mismatch can make a low training loss coexist with broken deployment behavior. + +For tool use, preserve the exact tool schema, assistant tool call, tool result, and final +answer. Do not flatten these objects into prose if deployment uses structured calls. The TRL +SFT format supports conversation records with tool calls and JSON tool schemas. + +Every assistant token used as an SFT target teaches imitation. Do not place a failed answer in +the target field and expect a separate score to negate it. Put failed outputs in preference +records, error-analysis records, or RL rollouts. If an SFT example explains an error, the +approved correction must still be the target response. + +#### Preference record + +```json +{ + "pair_id": "matter-017-task-04-pair-08", + "prompt": [{"role": "user", "content": "Review the attached contract set."}], + "chosen": [{"role": "assistant", "content": "..."}], + "rejected": [{"role": "assistant", "content": "..."}], + "preference_strength": "clear", + "rubric_version": "risk-rubric-3", + "annotator_ids": ["reviewer-12", "reviewer-31"], + "adjudicator_id": "reviewer-05", + "policy_revision": "base-instruct-sha", + "split_group_id": "matter-017" +} +``` + +Store both outputs. Store the reason for the decision. Store ties or ambiguous pairs as such. +Do not force a preference when two responses are equivalent. The +[Llama 3 post-training report](https://arxiv.org/abs/2407.21783) describes +preference-strength labels and excludes pairs with no clear preference. This avoids turning +annotation noise into a strong gradient. + +Preference data should come from the policy family that will be trained when possible. Pairs +from a much weaker or much stronger model can teach easy distinctions that the current policy +does not need. + +#### RLVR task record + +```json +{ + "task_id": "matter-017-task-04", + "prompt": [{"role": "user", "content": "Review the attached contract set."}], + "environment_version": "legal-sandbox-6", + "verifier_version": "risk-verifier-3", + "reward_components": { + "schema": 0.1, + "source_grounding": 0.4, + "rubric": 0.5 + }, + "split_group_id": "matter-017" +} +``` + +Save each rollout with its policy revision, decoding parameters, random seed, tool trace, +reward components, and verifier output. A scalar total is not enough for diagnosis. + +#### Continued-pretraining record + +Continued pretraining uses raw token sequences, not instruction and answer pairs. Preserve +document boundaries, source rights, dates, language, and deduplication keys. Mix some general +data when experiments show unacceptable forgetting. Continued pretraining can be much more +expensive than SFT because it uses many more tokens. The +[Llama 3 report](https://arxiv.org/abs/2407.21783) states that its code-specialist path used a +one-trillion-token mix with more than 85 percent code. That scale is +different from a small behavior adapter. + +### What data is actually needed + +Data volume has no universal answer. The needed amount depends on the number and diversity of +valid outputs, the base model, label noise, output length, coverage, and how far the target +policy is from the starting policy. + +[LIMA](https://arxiv.org/abs/2305.11206) is a useful lower-end existence result. Its authors +fine-tuned a 65B base model on 1,000 curated examples without RL. The result supports a narrow +claim: a capable base can learn some response behavior from a small, high-quality set. It does +not prove that 1,000 examples cover a broad assistant or a specialist domain. + +Tulu 3 shows the other end of the design. Its source pool contained 23,327,961 prompts. The +authors selected 939,344 for SFT and 425,145 for preference data, with model-specific mixture +details. They filtered and decontaminated data across general instruction following, math, +code, safety, multilingual behavior, and precise instruction following. The size follows the +breadth of the desired policy. + +For a first narrow pilot, use this practical sequence: + +1. Write 20 to 50 development tasks before training. Create a separate final test. Size that + test for the minimum improvement that matters to the product. +2. Collect 100 to 500 approved demonstrations that cover the main task families and known + failure modes. +3. Prove that the pipeline can overfit 16 to 32 examples. This checks the loss mask, labels, + optimizer, template, and adapter path. +4. Train the pilot. Evaluate it on the frozen development split. +5. Add data for observed errors. Do not expand every category equally. +6. Increase to thousands of examples only when the learning curve and error distribution + justify it. + +These counts are an engineering starting point, not a research law. They support a pilot, not +a precise final performance claim. A task with many output forms, rare edge cases, or long +tool trajectories needs more coverage. + +### Synthetic data is useful only with a quality gate + +Synthetic examples can cover rare cases and reduce writing cost. They also copy the teacher's +errors, style, blind spots, and answer-length bias. The Llama 3 team states that most of its +post-training data was model-generated. It used rule filters, reward and model-judge scores, +semantic deduplication, data categories, and adjusted mixture weights across rounds. It also +reported substantial disagreement between two quality scorers. That disagreement is a reason +to inspect synthetic data, not a reason to average scores and assume truth. + +Use this generation path: + +```text +real task seed + -> controlled variation or teacher generation + -> deterministic schema and source checks + -> domain rubric review + -> deduplication against train and evaluation data + -> accepted training record with provenance +``` + +Do not train on a teacher answer only because it is fluent. For grounded tasks, verify every +citation or extracted value against the source. For code, execute tests in a sandbox. For +math, verify the final answer and, when possible, intermediate constraints. For open-ended +professional work, use qualified reviewers and a written rubric. + +### What "human-verified" means + +"Human-verified" does not mean "true." It means that a recorded human process checked an +artifact under stated conditions. The phrase is incomplete unless the data gives the process. + +| Label | Human action | Valid claim | Missing claim | +| --- | --- | --- | --- | +| Human-originated | A person supplied the prompt or work item | The task came from a person | The response is correct | +| Human-written | A person wrote the target response | The target is not only model output | The writer has domain expertise | +| Human-ranked | A person selected or ranked model outputs | One output matched that person's rubric better | The chosen output is fully correct | +| Human-reviewed | A person checked an output against a rubric | The stated checks were performed | Unchecked facts are correct | +| Expert-adjudicated | A qualified expert resolved review disagreement | A named expert process made the final decision | The rubric has complete coverage | + +The [InstructGPT paper](https://arxiv.org/abs/2203.02155) gives a concrete example. About 40 +screened contractors wrote demonstrations and ranked outputs. The project used onboarding, +detailed instructions, and a shared question channel. Training annotators agreed on pairwise +comparisons 72.6 plus or minus 1.5 percent of the time. Held-out annotators agreed 77.3 plus or +minus 1.3 percent of the time. Most comparisons had only one label because more labels cost +more. The authors also state that the labeler group was mainly English-speaking and was not +representative of all affected users. + +This evidence gives two lessons. First, annotation is a measured production process. Second, +disagreement is normal. It can show an unclear rubric, a subjective preference, insufficient +context, or a real expert dispute. + +A useful verification record contains: + +- stable artifact and reviewer identifiers; +- reviewer role, qualification, and conflict rules; +- rubric and policy versions; +- the exact fields or claims that were checked; +- independent review count; +- agreement and adjudication result; +- timestamp and data-source versions; +- rejection reason and correction history. + +Constitutional AI uses a different allocation of human work. A model critiques, revises, and +compares responses under written principles, then an AI preference model supplies training +feedback. The [Constitutional AI paper](https://arxiv.org/abs/2212.08073) does not remove +humans from the system. Humans still select the principles, training design, and evaluation. + +### Estimate hardware from state, not model name + +Graphics processing unit (GPU) memory has four main groups: + +```text +peak memory = model state + + activations + + temporary kernels and communication buffers + + allocator and framework overhead +``` + +Model state includes parameters, gradients, and optimizer states. Activations depend strongly +on sequence length, tokens per batch, layer count, hidden width, attention implementation, and +whether activation checkpointing is enabled. This is why a claim such as "a 32B model needs +one 48 GB GPU" is not a complete specification. + +For a mixture-of-experts model, distinguish total and active parameters. Total parameters +affect weight storage. Active parameters per token affect much of the forward compute. An +active-parameter count is not a memory-capacity estimate. + +The [Transformers memory anatomy guide](https://huggingface.co/docs/transformers/model_memory_anatomy) +gives a common mixed-precision Adam estimate of 18 bytes per trainable parameter before +activations and temporary memory: 6 bytes for the two weight copies, 8 bytes for Adam states, +and 4 bytes for gradients. The table below applies that formula. It also shows bfloat16 +(BF16) weights alone and raw 4-bit weights alone. These are computed lower bounds, not fit +guarantees. + +| Parameter count | BF16 weights only | Mixed-precision Adam state | Raw 4-bit weights only | +| ---: | ---: | ---: | ---: | +| 8B | 14.9 GiB | 134.1 GiB | 3.7 GiB | +| 14B | 26.1 GiB | 234.7 GiB | 6.5 GiB | +| 32B | 59.6 GiB | 536.4 GiB | 14.9 GiB | +| 70B | 130.4 GiB | 1,173.5 GiB | 32.6 GiB | + +The table explains the method choices: + +- **Full fine-tuning** updates all parameters. It needs gradients and optimizer states for all + parameters. An 8B model already needs more than 134 GiB for common model state before + activations. Multi-GPU sharding is normal. +- **LoRA** keeps base parameters frozen and trains small low-rank matrices. It removes most + gradient and optimizer state, but it still stores the base and activations. +- **QLoRA** also stores the frozen base in a low-bit format. It reduces base-weight memory, + but quantization metadata, adapters, activations, temporary dequantization, and runtime + overhead remain. +- **RL** can need an actor, a frozen reference, a reward model, and sometimes a value model. + It also stores generated rollouts. Placement and offload strategy can matter more than the + actor's parameter count alone. + +The [QLoRA paper](https://arxiv.org/abs/2305.14314) trained a 65B model on one 48 GB GPU by +using a frozen 4-bit base, NormalFloat 4 (NF4) quantization, double quantization, paged +optimizers, and LoRA. +This is proof of feasibility for the paper's configuration. It is not a promise that any 65B +or 70B model, sequence length, batch, or trainer fits in 48 GB. + +The following table is a feasibility screen. It is not a purchasing guide or fit promise. + +| Available memory | Reasonable first fit test | Why it is only a candidate | +| ---: | --- | --- | +| 24 GiB | 8B LoRA or QLoRA; 14B QLoRA | Context and activation peaks can still exceed memory | +| 48 GiB | 8B to 14B LoRA; up to 32B QLoRA | Adapter targets, sequence length, and kernels control the peak | +| 80 GiB | 32B LoRA or QLoRA; 70B QLoRA | A 70B raw 4-bit base is already about 32.6 GiB | +| Several GPUs | Full fine-tuning or larger RL roles after sharding design | Aggregate memory needs communication and gathers | + +These candidates follow the computed lower bounds and the QLoRA existence result. Confirm +them with the measured fit test below. + +An online RL job has two different loads: + +```text +prompt batch -> rollout workers -> verifier or reward -> rollout buffer -> training workers + | | + +---- key-value cache and tool state +---- actor and value update +``` + +Rollout workers need fast decoding and key-value-cache capacity. Training workers need +backward-pass and optimizer capacity. A small job can place these roles on the same GPUs at +different times. A larger job can separate them so that generation and training overlap. +Separation increases throughput only when scheduling and model-weight synchronization cost +less than the idle time that it removes. Measure actor, reference, reward, value, verifier, +and rollout-buffer memory separately. + +Use a measured fit test for the exact job: + +1. Load the exact checkpoint, quantization, tokenizer, and adapter targets. +2. Use the planned sequence-length distribution and one microbatch. A microbatch is the set + of examples processed in one forward and backward pass. +3. Run forward, backward, optimizer step, and evaluation generation. +4. Record allocated and reserved peak memory. +5. Increase token batch size until measured throughput stops improving or memory becomes too + close to capacity. +6. Keep capacity for evaluation and checkpoint save peaks. + +Current accelerator capacities range widely. For example, NVIDIA lists 80 GB for H100, 141 GB +for H200, and 180 GB for B200 per GPU in its +[HGX component documentation](https://docs.nvidia.com/enterprise-reference-architectures/hgx-ai-factory-h100-h200-b200/latest/components.html). +Capacity does not predict speed by itself. Memory bandwidth, matrix format support, links +between GPUs, host memory, storage, and software kernels also matter. + +### What LoRA changes + +For a dense projection with input width `d_in` and output width `d_out`, LoRA keeps the dense +matrix `W` frozen. It learns two matrices with rank `r`: + +```text +W' x = W x + scale * B A x + +A shape: r by d_in +B shape: d_out by r +trainable parameters: r * (d_in + d_out) +``` + +For a 4,096 by 4,096 projection and rank 16, the adapter has 131,072 parameters. The dense +projection has 16,777,216. The adapter is 0.78125 percent of that projection. The +[LoRA paper](https://arxiv.org/abs/2106.09685) shows why this can reduce trainable state by +orders of magnitude. It does not remove the frozen base from memory. It also does not make +activation memory small. + +Adapter rank, target modules, scale, dropout, and learning rate are part of the model. Record +them. A low rank can underfit a large behavior change. Applying adapters to more projections +increases capacity and state. The only reliable choice is a learning curve on the target +evaluation. + +### Memory and speed techniques solve different problems + +| Technique | Primary effect | Cost or limit | +| --- | --- | --- | +| BF16 or 16-bit floating point (FP16) | Reduces state and increases tensor-core throughput | Numeric behavior depends on hardware and operation | +| LoRA | Reduces trainable parameters and optimizer state | Base weights and activations remain | +| QLoRA | Reduces frozen base-weight memory | Adds quantization and dequantization work | +| Activation checkpointing | Recomputes activations instead of storing all of them | More forward compute during backward | +| FlashAttention | Reduces attention memory traffic with exact tiled attention | Benefit depends on shape and supported kernels | +| FSDP or ZeRO stage 3 | Shards parameters, gradients, and optimizer state | Communication and temporary gathers remain | +| Sequence parallelism | Splits sequence-dependent state across workers | Adds communication and implementation constraints | +| CPU or NVMe offload | Moves some state out of GPU memory | Transfer can reduce throughput sharply | +| Packing | Puts several short examples in one sequence | Requires correct boundaries, masks, and position handling | + +[Zero Redundancy Optimizer (ZeRO)](https://arxiv.org/abs/1910.02054) and +[PyTorch Fully Sharded Data Parallel (FSDP)](https://docs.pytorch.org/docs/main/fsdp.html) +reduce replicated model state. +They are capacity techniques, not automatic speed techniques. [FlashAttention](https://arxiv.org/abs/2205.14135) +computes exact attention with tiles that reduce traffic to high-bandwidth memory. Its reported +speedups are workload and hardware results, not constants. + +Packing needs special care. Without a block-diagonal attention mask or another supported +isolation method, a later example can attend to an earlier example in the same packed +sequence. That creates a train-time context that deployment will not have. + +For a first project, start with the smallest capable open-weight checkpoint and an adapter. +Use one GPU if the measured job fits with operating margin. Add sharding only when the model, +sequence, or batch requirement needs it. Distributed training can make a small job slower if +communication is larger than the saved compute time. + +### How to finish the first useful cycle fast + +Speed means time to a trusted result, not examples per second alone. A fast training run with +a contaminated test set is a slow project because it must be repeated. + +For the first SFT or DPO project, use one small software stack: + +- Transformers for the model, tokenizer, and template; +- [Parameter-Efficient Fine-Tuning (PEFT)](https://huggingface.co/docs/peft/index) for LoRA; +- TRL for the SFT or DPO objective; +- [Accelerate](https://huggingface.co/docs/accelerate/index) for device placement and later + distributed execution; +- [bitsandbytes](https://huggingface.co/docs/bitsandbytes/index) only when the run uses + low-bit base weights. + +Start from the official recipe for the exact checkpoint. Keep library and checkpoint revisions +fixed. Do not begin with an RL orchestration framework when the first objective is SFT. + +Every run should have a machine-readable manifest like this: + +```yaml +run_id: contract-risk-sft-004 +base_model: organization/model@immutable-revision +tokenizer: organization/model@immutable-revision +chat_template_sha256: "..." +objective: assistant-only-sft +precision: + base_storage: nf4 + compute: bfloat16 +adapter: + type: lora + rank: 16 + alpha: 32 + target_modules: [q_proj, k_proj, v_proj, o_proj] +data: + train_manifest_sha256: "..." + development_manifest_sha256: "..." + final_test_manifest_sha256: "..." +optimization: + max_sequence_tokens: 4096 + global_sequence_tokens_per_step: 32768 + learning_rate: "declared-value" + step_budget: "declared-value" +evaluation: + grader_version: risk-verifier-3 + decoding_profile: deterministic-v2 +``` + +The rank and scale in this example are illustrative. Select them with development results. +The manifest shape is the important part. + +Use this order: + +1. **Freeze acceptance tests.** Include a base-model result and important regressions. +2. **Select the smallest viable checkpoint.** Confirm the license, context size, tokenizer, + and chat template. +3. **Lint the data.** Check roles, empty responses, token lengths, special tokens, duplicate + groups, source rights, and split leakage. +4. **Overfit 16 to 32 examples.** The loss should decrease and decoded outputs should match + the targets. If it does not, fix the pipeline. +5. **Run a small SFT adapter.** Use a fixed seed and save periodic checkpoints. +6. **Evaluate checkpoints on the frozen development set.** Training loss is not the deployment + metric. The [InstructGPT study](https://arxiv.org/abs/2203.02155) selected an SFT checkpoint + by reward-model and human behavior even after validation loss appeared to overfit. +7. **Classify errors.** Separate knowledge, instruction, format, tool, grounding, refusal, + and verifier errors. +8. **Add targeted data.** Change the data mixture according to the observed error counts. +9. **Use DPO or RL only for a remaining preference or exploration problem.** Do not add a + stage without a measured reason. +10. **Run the final test once, then package the full inference contract.** Version weights or + adapter, tokenizer, template, generation parameters, tool schemas, and evaluation report + together. + +Two equations help plan time: + +```text +SFT optimizer steps = ceil( + epochs * total_sequence_tokens / global_sequence_tokens_per_step +) + +RL generated tokens = iterations * prompts_per_iteration + * completions_per_prompt * mean_completion_tokens +``` + +The sequence-token count determines most compute. The target-token count determines how much +supervised signal the batch contains. Measure tokens per second on the real sequence +distribution. Then estimate training time from the measured rate. Floating-point operation +(FLOP) estimates can compare configurations, but they do not include data +loading, checkpoint saves, evaluation, failed rollouts, tool latency, or communication stalls. + +Optimize in this sequence: + +1. Remove invalid and excessively long samples. +2. Bucket by length and pack short examples. +3. Use completion-only or assistant-only loss. +4. Use a supported efficient-attention kernel. +5. Increase tokens per microbatch until throughput no longer improves. +6. Use gradient accumulation to reach the desired global token batch. +7. Add activation checkpointing only if memory requires it. +8. Add FSDP, ZeRO, or sequence parallelism only if one worker cannot hold the job. +9. For RL, separate rollout serving from training and measure generated tokens per second. + +The [Llama 3 team](https://arxiv.org/abs/2407.21783) used paged key-value-cache allocation for +rejection sampling and reported more than two times the throughput in its system. This is a +useful mechanism result. The numeric speedup is not portable to other models, output-length +distributions, or hardware. + +The current [Transformers optimization overview](https://huggingface.co/docs/transformers/main/optimization_overview) +separates memory and speed methods for the same reason. Compilation, kernels, quantization, +caching, and parallelism have different effects. For RL systems, frameworks such as +[OpenRLHF](https://github.com/OpenRLHF/OpenRLHF) and [verl](https://verl.readthedocs.io/en/latest/) +can schedule training and high-throughput generation. A framework removes integration work. +It does not select a correct reward or clean the data. + +## Level 3: Objectives and algorithms + +### Continued pretraining + +Continued pretraining uses the original next-token objective on a new text distribution. If a +document contains tokens `z_1...z_T`, the loss is: + +```text +L_CPT(theta) = -sum_t log p_theta(z_t | z_ y_l | x) = sigmoid(r_phi(x, y_w) - r_phi(x, y_l)) +L_RM(phi) = -log P_phi(y_w > y_l | x) +``` + +One ranked list can produce several correlated pairs. Treating those pairs as independent can +overweight one prompt. The [InstructGPT implementation](https://arxiv.org/abs/2203.02155) +grouped comparisons from one prompt in the same training batch for this reason. + +PPO stores the probability of each sampled token under the old policy. During updates it +uses the ratio between new and old probabilities. A clipped objective prevents a single batch +from causing an unrestricted policy change. A learned value model estimates expected return +and reduces policy-gradient variance. The original +[PPO paper](https://arxiv.org/abs/1707.06347) defines this repeated sample-then-optimize form. + +For token action `a_t`, state `s_t`, estimated advantage `A_t`, and clip range `epsilon`: + +```text +ratio_t(theta) = pi_theta(a_t | s_t) / pi_old(a_t | s_t) + +L_clip(theta) = -mean minimum( + ratio_t(theta) * A_t, + clip(ratio_t(theta), 1-epsilon, 1+epsilon) * A_t +) +``` + +The sequence reward commonly combines reward-model output with a penalty for movement from +the frozen reference. The exact KL estimator and token allocation are implementation choices. + +```text +algorithm PPO_RLHF(prompts X, actor theta, value psi, reward R, reference ref): + repeat for a declared number of iterations: + old_theta <- immutable snapshot of theta for this iteration + rollouts <- sample responses and log old token probabilities + scores <- R(prompt, response) minus declared reference-policy penalty + advantages, returns <- estimate from scores and value(psi) + repeat for K update passes over the rollout buffer: + update theta with clipped policy loss and declared regularizers + update psi with return-prediction loss + stop the update passes if the declared divergence boundary is crossed + evaluate task quality, reward, divergence, length, and regressions + return the checkpoint accepted by the external task evaluation +``` + +The rollout buffer and old-policy snapshot are invariants for one iteration. Reusing much +older rollouts is off-policy training because another policy generated them. This changes the +estimator unless the method includes a declared correction. + +An LLM PPO system can hold four logical models: actor, frozen reference, reward model, and +value model. Some systems share layers, quantize models, or place them on different workers. +Those changes reduce physical copies but do not remove the logical roles. + +The reward model is a proxy for human judgment. It can be exploited. The +[reward-model overoptimization study](https://arxiv.org/abs/2210.10760) shows in a controlled +setting that more optimization against an imperfect proxy can eventually reduce a better +gold reward. KL penalties, update clipping, and early stopping control update size. They do +not make a wrong reward correct. + +### Group relative policy optimization and verifiable rewards + +RLVR describes the reward source, not one optimizer. A verifier can be a compiler, unit test, +symbolic checker, schema checker, exact-answer rule, or a controlled environment result. +PPO, GRPO, or another policy optimizer can use that reward. + +[DeepSeekMath](https://arxiv.org/abs/2402.03300) introduced group relative policy +optimization (GRPO) as a PPO variant that removes the learned value model. For each prompt, it +samples a group of outputs. It uses the group's rewards to form relative advantages. A common +simplified form is: + +```text +A_i = (reward_i - mean(reward_group)) / (std(reward_group) + epsilon) +``` + +The policy update uses these advantages with an old-policy probability ratio, clipping, and a +reference-policy KL term. Exact implementations differ. The group comparison is the central +mechanism. + +```text +algorithm grouped RLVR(prompts X, actor theta, fixed reference ref, verifier V): + repeat for a declared number of iterations: + old_theta <- immutable snapshot of theta for this iteration + for each prompt x in a batch: + outputs <- sample G outputs from old_theta with logged seeds + rewards <- [V(x, output) for output in outputs] + if all rewards are equal: + record a zero-signal group and exclude it from policy-gradient terms + else: + advantages <- normalize rewards within the group + store tokens, old log-probabilities, rewards, and advantages + for each update minibatch from stored rollouts: + ratio <- exp(logp_theta - logged_old_logp) + policy_term <- minimum(ratio * advantage, + clip(ratio, 1-eps, 1+eps) * advantage) + kl_term <- divergence(theta, ref) under the declared estimator + update theta to maximize policy_term - beta * kl_term + run frozen task and regression evaluations + stop on the declared budget, plateau, or regression boundary + return the accepted checkpoint and all verifier and rollout versions +``` + +The zero-signal condition is important. If all outputs pass or all outputs fail, a +group-relative method has no within-group ranking signal. Hard-task sampling, curriculum +design, and verifier resolution affect training efficiency. + +[DeepSeek-R1](https://arxiv.org/abs/2501.12948) gives evidence that rule-based rewards and RL +can induce stronger reasoning in one model family. The same work also uses SFT, additional RL +stages, rejection sampling, and distillation to produce useful released models. The result does +not support the claim that a raw RL stage is sufficient for a polished assistant. + +### Algorithm comparison + +| Property | SFT | DPO | PPO-style RLHF | Grouped RLVR | +| --- | --- | --- | --- | --- | +| Required feedback | Target answer | Chosen and rejected pair | Comparisons used to train reward | Verifier score per rollout | +| New generation during optimization | No | No | Yes | Yes | +| Frozen reference | Optional for regularization | Required by objective | Common | Common | +| Learned reward model | No | No | Yes | No when reward is directly verifiable | +| Learned value model | No | No | Usually | No in GRPO | +| Dominant extra cost | Backward over target tokens | Two responses and reference scores | Rollouts plus several model roles | `G` rollouts per prompt | +| Main data failure | Bad targets or masks | Noisy or easy pairs | Reward-model bias | Verifier exploits or sparse reward | +| Natural stopping rule | Development-task plateau | Development-task plateau | Reward plateau plus external quality gate | Verified-task plateau plus regression gate | + +Let `N` be training sequence tokens, `R` be generated rollout tokens, `G` be completions per +prompt, `P` be active model parameters, and `P_a` be trainable adapter parameters. Exact +transformer cost also contains attention terms that depend on sequence length. These variables +still show the main scaling drivers: + +- SFT uses one policy forward and backward path over `N` tokens. +- DPO processes chosen and rejected sequences. It also needs reference log-probabilities, but + a fixed reference allows those values to be cached. +- PPO adds generation over `R` tokens and passes through reward, reference, and value roles. + It can train for several update passes on one rollout buffer. +- Grouped RLVR makes `R` grow approximately with `G`. It removes a value-model role in GRPO, + but it does not remove rollout generation. +- Full Adam state scales with `P`. Adapter optimizer state scales with `P_a`, while frozen + base storage and activation compute still scale with the base model. +- Rollout storage scales with generated tokens and logged fields such as old log-probability, + reward, advantage, masks, and tool state. + +Accumulate long sequence log-probabilities and reward statistics at adequate precision. Small +per-token errors can become large after a long sum. Record the exact epsilon for group reward +normalization and the exact KL estimator. These details can change training behavior. + +None of these objectives guarantees generalization. Termination means the declared budget or +acceptance rule has stopped optimization. It does not mean the optimizer found a global +optimum. + +## Evaluation is part of training design + +### Use the most direct verifier available + +Use this evidence order for each criterion: + +1. Deterministic execution or exact source check. +2. A domain rubric with qualified, calibrated reviewers. +3. Pairwise human preference for subjective qualities. +4. A model judge for screening, triage, or a secondary metric. + +Model judges are useful because they are fast and repeatable. They are not neutral. +[MT-Bench and Chatbot Arena](https://arxiv.org/abs/2306.05685) found position, verbosity, and +self-enhancement biases even while model judgments often tracked human preferences. +[Length-Controlled AlpacaEval](https://arxiv.org/abs/2404.04475) showed that response length +can distort automatic preference evaluation and that explicit length control improved +agreement in its setting. + +If a model judge must score a domain task, calibrate it against expert decisions. Measure +agreement by criterion and task class. Randomize answer order. Hide model identity. Give the +judge source documents when correctness requires them. Review disagreements. Never use the +same unvalidated judge as training reward and final proof of success. + +### Match the metric to the product requirement + +`pass@k` asks whether at least one of `k` samples succeeds. It is useful when a system can +generate several candidates and select one. The [Codex evaluation paper](https://arxiv.org/abs/2107.03374) +formalized this metric for generated code. With `n` sampled programs and `c` correct programs, +its unbiased estimator is `1 - C(n-c, k) / C(n, k)` when `n-c` is at least `k`, and 1 +otherwise. `pass@1` is closer to a one-attempt product. + +An all-pass task metric is stricter. A task passes only if every mandatory criterion passes. +Use it when one missed clause, file, citation, or safety condition makes the work unacceptable. +Also report per-criterion results. They show whether a system is close to complete or fails +many parts. + +State how criteria are averaged. A micro-average gives every criterion equal weight, so tasks +with many criteria count more. A macro-average first averages within each task, then gives +every task equal weight. Report both when rubric counts vary substantially. + +All-pass can be much lower than the average criterion pass rate. As an illustration, if a task +had ten independent criteria and each passed with probability 0.83, the all-pass probability +would be `0.83^10 = 15.5%`. Real criteria are not independent. The calculation explains the +multiplicative pressure but does not predict a benchmark score. + +For each release candidate: + +- run repeated samples when decoding is stochastic; +- report the number of tasks and attempts; +- compute paired confidence intervals where task outputs can be paired; +- show results by task family and difficulty; +- report regressions, not only aggregate gains; +- keep the base, SFT, and later-stage checkpoints in the same evaluation table; +- inspect changed answers, including improvements and regressions. + +### What one legal-domain field result shows + +The public Harvey Legal Agent Benchmark contains more than 1,200 tasks across 24 practice +areas and more than 75,000 expert-written rubric criteria, according to the +[benchmark introduction](https://www.harvey.ai/blog/introducing-harveys-legal-agent-benchmark). +Each task has an instruction, a closed set of matter documents, and a required work product. +The [open benchmark repository](https://github.com/harveyai/harvey-labs) provides tasks and an +execution and evaluation harness. + +A [public field report on domain post-training](https://www.trajectory.ai/field-notes/harvey-nemotron-3-ultra) +reports these held-out results for one large open-weight model: + +| Reported measure | Base | Post-trained | Change | +| --- | ---: | ---: | ---: | +| Tasks that pass every rubric criterion | 0% | 5.8% | +5.8 percentage points | +| Individual rubric criteria passed | 52% | 83% | +31 percentage points | + +The second change is a 59.6 percent relative gain. A relative gain from a zero-percent base is +undefined, so the all-pass change must stay in percentage points. The report also places the +post-trained result between two closed models on all-pass, states that training took less than +24 hours, and claims at least ten times lower price per token than selected closed models. + +This is strong motivation for an experiment. It is not a reproducible training recipe. The +public report does not state the algorithm, training-example count, token count, data +provenance, hardware topology, GPU-hours, optimizer, batch shape, sequence length, training +cost, confidence intervals, or independent replication. It states that the tasks were held +out, but it does not give enough split detail to audit possible related-task leakage. The +correct conclusion is limited: a domain post-training run produced a large measured shift on +one strict benchmark. The report cannot tell another team what resources will reproduce it. + +Four design lessons remain useful: + +1. Measure a base checkpoint before training. The size of the possible gain depends on the + starting policy. +2. Keep both all-pass and per-criterion metrics. A large criterion gain can coexist with a low + rate of complete work products. +3. Keep the harness, data schema, and evaluation contract independent from one base model. + A new checkpoint will still need tokenizer, template, parallelism, and regression checks. +4. Report GPU-hours, token count, and total cost with elapsed time. "Less than 24 hours" alone + cannot distinguish an efficient small job from a large parallel job. + +## Production and continual learning + +### Prefer reviewed batches before online weight updates + +A safe production loop collects traces, removes sensitive data, groups similar failures, +creates candidate examples, reviews them, and trains a new version offline. A release gate +then compares the candidate with the current version on frozen and recent tasks. + +```text +production traces + -> consent and retention filter + -> failure taxonomy + -> candidate SFT, preference, or verifier records + -> human or program review + -> versioned training batch + -> offline candidate checkpoint + -> frozen evaluation and small controlled deployment + -> explicit promote or reject decision +``` + +This loop is continual in an operational sense, but the weight update remains periodic. It +has a clear data boundary and a rollback point. + +Online or asynchronous RL is more complex. Rollouts can come from an older behavior policy +than the policy being updated. This is policy staleness. Importance ratios can correct some +distribution mismatch, but ratios over long token sequences can have high variance. Reward +definitions can also change while data is in flight. Recent work on +[learning from user interactions](https://arxiv.org/abs/2603.12273) and +[reinforcement learning through self-distillation](https://arxiv.org/abs/2601.20802) uses a +policy conditioned on later feedback as a token-level teacher. These are recent research +results. They do not establish a mature production standard. Treat this area as frontier +engineering, not a default recipe. + +Continual updates also create these controls: + +- a replay set for capabilities that must not be forgotten; +- a time-based holdout for new behavior; +- immutable reward and verifier versions for each run; +- trace consent, deletion, and access policy; +- model lineage and rapid rollback; +- a limit on how many updates can occur before a broad evaluation; +- monitoring for data drift, reward drift, and repeated user-specific patterns. + +### Common failure modes + +| Failure | Mechanism | Detection | Correction | +| --- | --- | --- | --- | +| Chat-template mismatch | Training tokens differ from deployment tokens | Decode fixed examples through both paths | Use one versioned template and exact special tokens | +| Prompt loss included by mistake | Model learns to reproduce user text | Inspect token-level masks | Apply completion-only or assistant-only loss | +| Random-row leakage | Related examples enter train and test | Compare source and semantic groups across splits | Split by matter, source, entity, template, or time | +| Synthetic error amplification | Teacher errors become targets | Source checks and expert audit samples | Reject or correct failed examples before training | +| Preference ambiguity | Random labels create conflicting gradients | Agreement and tie rate by rubric | Improve rubric, allow ties, adjudicate clear conflicts | +| Length bias | Longer output is selected as better | Quality at fixed length and length distributions | Balance pairs and use length-controlled evaluation | +| Reward hacking | Policy finds a high-score shortcut | External checks and adversarial rollouts | Repair the verifier and rebuild affected data | +| Catastrophic forgetting | Narrow updates damage prior behavior | Frozen general and safety suites | Adjust data mixture, update size, or method | +| RL reward sparsity | Most rollout groups have equal rewards | Zero-signal group rate | Change task sampling or increase verifier resolution | +| Distributed slowdown | Communication exceeds compute saved | Profiler timelines and tokens per second | Use fewer workers or change sharding and batch shape | +| Evaluation overfit | Training decisions consume the holdout | Access and query log for the holdout | Create a new untouched final test set | +| Adapter deployment mismatch | Wrong base or adapter revision is loaded | Artifact manifest and checksum test | Deploy one versioned model contract | + +The correction column is not a request for silent fallback behavior. If a required check +fails, stop the run or release. Correct the primary path and repeat the controlled evaluation. + +## A compact implementation plan + +For an experienced ML engineer who is new to LLM post-training, this is the highest-value +first project: + +1. Select an 8B to 14B instruct checkpoint whose license permits the intended use. +2. Define one narrow task, a development set, and a separate locked final test. Group them to + prevent source leakage. +3. Build 200 to 500 approved message-format demonstrations. +4. Add provenance, review, and split fields to every record. +5. Run a 16-example overfit test with the deployment chat template. +6. Train a LoRA or QLoRA SFT adapter. +7. Compare base and SFT checkpoints on development data with deterministic checks and blinded + review. Use the final test only for the selected release candidate. +8. Classify all failures. Add targeted examples and repeat once. +9. Create preference pairs only if experts can rank remaining failures more reliably than + write targets. +10. Create an RLVR stage only if a strict verifier can score multiple useful attempts. + +This project teaches the core post-training mechanics without the system cost of online RL. +It also produces the evaluation and data infrastructure that every later method needs. + +## Evidence-backed insights + +### INSIGHT-001: Post-training is a feedback taxonomy, not an RL synonym + +**Claim.** The available feedback should select the training objective. Target responses imply +SFT. Comparisons imply preference optimization. Executable outcomes can support RLVR. + +**Mechanism.** Each objective converts a different data relation into gradients. SFT increases +target-token probability. DPO increases a chosen-versus-rejected log-probability margin. +RL estimates policy gradients from sampled outcomes. + +**Evidence.** Llama 3 used iterative SFT and DPO. Tulu 3 released SFT, DPO, and RLVR stages. +InstructGPT used SFT, a reward model, and PPO. + +**Confidence.** High. + +**Boundary.** The names do not specify data quality, model architecture, or implementation. + +**Caveat.** Some papers use "post-training" more narrowly or classify offline preference +optimization within the broader RLHF family. + +**Implication.** Define the feedback object before selecting the trainer. + +**Follow-up.** Compare SFT, DPO, and RLVR on the same frozen task set and starting checkpoint. + +### INSIGHT-002: Evaluation and data are the critical path + +**Claim.** A post-training run cannot be interpreted without a frozen task distribution, +external acceptance criteria, and data lineage. + +**Mechanism.** Training selects outputs that score well under its observed signal. If train +and test groups overlap, or if the grader rewards a shortcut, optimization improves the proxy +without proving deployment quality. + +**Evidence.** Reward-model overoptimization shows proxy exploitation under stronger +optimization. Model-judge studies document systematic judgment biases. Major open recipes +use decontamination, mixture design, and several evaluation forms. + +**Confidence.** High. + +**Boundary.** Exact leakage and reward risks depend on the task and data-generation process. + +**Caveat.** No finite evaluation proves correctness on all future inputs. + +**Implication.** Build the evaluation and provenance system before a large training run. + +**Follow-up.** Audit split-group overlap and judge-versus-expert disagreement for each task +family. + +### INSIGHT-003: Adapter size is not total hardware demand + +**Claim.** LoRA reduces trainable state. It does not reduce all memory in proportion to the +number of trainable parameters. + +**Mechanism.** The frozen base still participates in each forward and backward pass. +Activations, temporary kernels, and communication buffers depend on sequence and batch shape. + +**Evidence.** LoRA defines low-rank updates. QLoRA adds a quantized frozen base and reports one +65B-on-48-GB result. Official memory accounting separates weights, optimizer state, +gradients, activations, and temporary storage. + +**Confidence.** High. + +**Boundary.** Peak memory depends on the exact architecture, kernels, precision, and trainer. + +**Caveat.** Raw 4-bit weight size is only a lower bound. + +**Implication.** Size hardware with an end-to-end measured training step, not an adapter +parameter count. + +**Follow-up.** Record peak memory and target tokens per second across the intended sequence +length distribution. + +### INSIGHT-004: Human verification is a provenance process + +**Claim.** "Human-verified" is meaningful only when it identifies the reviewer, rubric, +scope, independence, agreement, and adjudication process. + +**Mechanism.** Humans supply observations through a task interface. Their qualifications, +instructions, available evidence, and incentives determine the noise and bias in that signal. + +**Evidence.** InstructGPT documents screening, onboarding, instructions, limited duplicate +labels, measured agreement, and a non-representative reviewer population. + +**Confidence.** High. + +**Boundary.** A review can validate only the criteria and evidence that it covers. + +**Caveat.** Expert agreement can remain low when the task itself is ambiguous. + +**Implication.** Store human-review metadata as training data, not as separate administrative +text. + +**Follow-up.** Measure agreement and adjudication rate by rubric criterion before scaling +annotation. + +### INSIGHT-005: The fastest route is a small controlled loop + +**Claim.** A small SFT adapter with a fixed evaluation usually gives more information per day +than an immediate large run or an RL stack. + +**Mechanism.** It tests the full data, template, loss, checkpoint, inference, and evaluation +path with low compute. Error analysis then identifies whether more data, a different objective, +or a larger model is necessary. + +**Evidence.** LIMA is a narrow example of high-quality small-data adaptation. Large open +recipes use repeated data and training rounds rather than one final run. The field result +shows that short elapsed time can produce a large benchmark change, but missing run details +prevent cost or recipe transfer. + +**Confidence.** Medium-high. + +**Boundary.** A weak base model or broad target policy can require more data and compute. + +**Caveat.** A quick pilot is useful only if the held-out evaluation is representative. + +**Implication.** Spend the first compute budget on a complete learning loop, not maximum model +size. + +**Follow-up.** Plot task quality against approved examples, target tokens, and wall-clock time. + +### INSIGHT-006: Verifiable reward changes the economics of RL + +**Claim.** RL becomes easier to justify when reward comes from a high-precision program or +environment instead of a learned opinion model. + +**Mechanism.** Each new rollout receives an immediate score without a separate reward-model +training stage. Grouped methods can compare several attempts and remove the learned critic. + +**Evidence.** DeepSeekMath defines GRPO. DeepSeek-R1 reports reasoning gains from rule-based +rewards and RL in its studied setting. + +**Confidence.** Medium-high for code and formal-answer tasks. Medium or low for open-ended +professional work. + +**Boundary.** A verifier covers only encoded requirements. + +**Caveat.** The policy can exploit any gap between the verifier and the real objective. + +**Implication.** Invest in verifier coverage and adversarial tests before adding rollout +capacity. + +**Follow-up.** Track false-pass rate, false-fail rate, zero-signal groups, and reward-versus- +expert disagreement. + +## Sources + +### Definitions, data, and open recipes + +- [The Llama 3 Herd of Models](https://arxiv.org/abs/2407.21783) +- [Tulu 3: Pushing Frontiers in Open Language Model Post-Training](https://arxiv.org/abs/2411.15124) +- [LIMA: Less Is More for Alignment](https://arxiv.org/abs/2305.11206) +- [Training Language Models to Follow Instructions with Human Feedback](https://arxiv.org/abs/2203.02155) +- [Constitutional AI: Harmlessness from AI Feedback](https://arxiv.org/abs/2212.08073) +- [Open Source AI Definition 1.0](https://opensource.org/ai/open-source-ai-definition) + +### Optimization methods + +- [Direct Preference Optimization](https://arxiv.org/abs/2305.18290) +- [Proximal Policy Optimization Algorithms](https://arxiv.org/abs/1707.06347) +- [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://arxiv.org/abs/2402.03300) +- [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://arxiv.org/abs/2501.12948) +- [Aligning Language Models from User Interactions](https://arxiv.org/abs/2603.12273) +- [Reinforcement Learning via Self-Distillation](https://arxiv.org/abs/2601.20802) +- [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685) +- [QLoRA: Efficient Finetuning of Quantized LLMs](https://arxiv.org/abs/2305.14314) + +### Systems and hardware + +- [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://arxiv.org/abs/1910.02054) +- [FlashAttention: Fast and Memory-Efficient Exact Attention](https://arxiv.org/abs/2205.14135) +- [PyTorch Fully Sharded Data Parallel documentation](https://docs.pytorch.org/docs/main/fsdp.html) +- [Transformers model memory anatomy](https://huggingface.co/docs/transformers/model_memory_anatomy) +- [Transformers optimization overview](https://huggingface.co/docs/transformers/main/optimization_overview) +- [TRL SFT Trainer documentation](https://huggingface.co/docs/trl/sft_trainer) +- [TRL DPO Trainer documentation](https://huggingface.co/docs/trl/dpo_trainer) +- [TRL GRPO Trainer documentation](https://huggingface.co/docs/trl/grpo_trainer) +- [PEFT documentation](https://huggingface.co/docs/peft/index) +- [Accelerate documentation](https://huggingface.co/docs/accelerate/index) +- [bitsandbytes documentation](https://huggingface.co/docs/bitsandbytes/index) +- [OpenRLHF](https://github.com/OpenRLHF/OpenRLHF) +- [verl documentation](https://verl.readthedocs.io/en/latest/) + +### Evaluation and field evidence + +- [Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena](https://arxiv.org/abs/2306.05685) +- [Length-Controlled AlpacaEval](https://arxiv.org/abs/2404.04475) +- [Scaling Laws for Reward Model Overoptimization](https://arxiv.org/abs/2210.10760) +- [Evaluating Large Language Models Trained on Code](https://arxiv.org/abs/2107.03374) +- [Harvey Legal Agent Benchmark introduction](https://www.harvey.ai/blog/introducing-harveys-legal-agent-benchmark) +- [Harvey Legal Agent Benchmark repository](https://github.com/harveyai/harvey-labs) +- [Public legal-domain post-training field report](https://www.trajectory.ai/field-notes/harvey-nemotron-3-ultra)