Model Optimization

5 posts

line4 min readCurated summary

Image Content Moderation in Large-Scale Service Environments (feat. Multimodal LLM)

Image content moderation has evolved from simple rule-based filtering into an AI-powered decision system capable of handling visual context, text, and policy complexity. At large platforms, the challenge is not only accuracy but also latency, cost, scalability, and adaptability to changing policies. LY Corporation addresses these demands through optimized traditional ML models, a hybrid ML–multimodal LLM pipeline, and modular decision-making that combines OCR, visual analysis, and contextual reasoning. ## The Evolution of Content Moderation - Early systems relied on keyword matching, rule-based filters, and predefined patterns. - Machine learning enabled broader pattern recognition and detection of modified or less explicit violations. - Modern systems combine: - Deep learning for text and image classification - Multimodal models for joint image–text understanding - LLMs for context-sensitive judgments - Separate prediction and policy layers for operational flexibility - Despite these advances, image moderation remains difficult because images lack explicit structure and their meaning often depends on context. ## Why Image Moderation Is Difficult - **Visual complexity:** Backgrounds, objects, people, colors, and composition interact in ways that simple object detection cannot fully interpret. - **Context dependency:** Symbols, gestures, and imagery may have different meanings across cultures; embedded text can also determine whether an image is harmful. - **Evasion and variation:** Memes, composites, partially obscured images, and AI-generated edits continually challenge existing detectors. - **Scale requirements:** Platforms may receive millions or tens of millions of images daily, requiring high accuracy alongside low latency, reliability, and cost efficiency. ## LY Corporation’s Moderation API - LY Corporation operates a monitoring platform designed to process large-scale traffic and enforce diverse content policies. - Its image moderation API detects: - Adult content - Violent or graphic scenes - Offensive or disturbing imagery - Identity documents containing personal information - Social media screenshots and other policy-sensitive images - The system is designed to apply service-specific policies consistently while maintaining high throughput. ## Improving Accuracy, Speed, and Cost ### Traditional ML Model Optimization - A PyTorch-based image classification model was selected with latency, cost, and throughput in mind. - The model was converted to ONNX and optimized with FP16 precision. - ONNX Runtime improved execution efficiency, while FP16 reduced memory usage and inference time. - These changes increased throughput by up to **4.3 times**. ### Hybrid ML and Multimodal LLM Architecture - The traditional classifier acts as a fast first-stage filter. - Clear cases are resolved immediately by the image model. - Ambiguous cases are sent to a multimodal LLM for deeper analysis. - More than 90% of production data could be classified by the traditional model alone. - Since multimodal LLM throughput was over 100 times lower than that of the traditional model, routing every image to the LLM would have significantly increased GPU usage and cost. - The hybrid approach preserves high-quality reasoning where necessary while avoiding unnecessary LLM calls. ### vLLM-Based LLM Optimization The team optimized multimodal LLM serving with vLLM, using characteristics such as repeated prompts, predictable token lengths, and prefill-heavy workloads. - **`enable_prefix_caching`:** Reuses KV-cache blocks for repeated system prompts and templates, reducing prefill computation. - **`max_model_len`:** Limits the maximum input-plus-output length to avoid excessive KV-cache allocation. - **`max_num_seqs`:** Controls concurrent requests, balancing throughput against per-request latency and resource contention. - **`max_num_batched_tokens`:** Sets the token budget per scheduling step; larger values can improve throughput for prefill-heavy workloads. - Regularly updating vLLM is recommended because new releases add improvements such as asynchronous scheduling, CUDA graph support, and broader quantization options. ## Moving Beyond Single-Model Policy Prediction - Earlier end-to-end vision models directly predicted final policy categories from images. - This worked for visually obvious violations, such as detecting smoking, but struggled with complex behaviors such as tobacco sales. - Sales-related judgments may require combining: - Product presence - Prices - Sales language - Contact information - Encouragement to purchase - Directly learning every combination of national regulations, service policies, and exceptions created overly complex output classes. - It also made the model harder to extend and maintain, while limiting the use of text embedded in images. ## Hybrid Decision-Making with OCR and Multimodal Reasoning - The redesigned system separates visual and textual information rather than forcing one model to learn every policy combination. - OCR extracts text from images when relevant. - Extracted text helps identify policy-violating behavior or intent. - Visual signals and textual evidence are then combined with a multimodal LLM. - This allows the system to reason about context and intent beyond simple object detection, while making policy logic more modular and adaptable. The practical recommendation is to avoid routing all traffic through expensive general-purpose models. Use fast specialized models for clear cases, reserve multimodal LLMs for ambiguity, optimize serving according to workload characteristics, and separate content understanding from policy decisions so the system can evolve as requirements change.

Read original(opens in new tab)
meta4 min readCurated summary

Ranking Engineer Agent (REA): The Autonomous AI Agent Accelerating Meta’s Ads Ranking Innovation

Meta’s Ranking Engineer Agent (REA) autonomously manages much of the ads-ranking ML experimentation lifecycle, from generating hypotheses and launching training jobs to debugging failures and analyzing results. Unlike session-based AI assistants, REA maintains context across workflows lasting days or weeks, while engineers retain oversight at strategic checkpoints. In its first production rollout, REA doubled average model accuracy across six models and helped three engineers produce launch proposals for eight models—about five times the historical engineering output. ## The Bottleneck in Traditional ML Experimentation - Meta’s advertising systems rely on large, complex ML models serving billions of users across Facebook, Instagram, Messenger, and WhatsApp. - Improving these models traditionally requires engineers to: - Form hypotheses - Design experiments - Launch training jobs - Debug failures - Analyze results - Iterate on promising approaches - Each cycle can take days or weeks, and mature models make meaningful improvements increasingly difficult to find. - The sequential, hands-on process became a bottleneck to experimentation and innovation. ## REA as an Autonomous ML Agent - Existing ML AI tools generally assist with isolated tasks such as drafting hypotheses, writing configurations, or interpreting logs. - REA instead coordinates the full experimentation process and advances it without continuous prompting. - Its design addresses three central challenges: - **Long-running workflows:** Persistent state and memory allow REA to manage multiday or multiweek experiments. - **Hypothesis quality:** It combines historical experiment data with current ML research. - **Operational resilience:** It handles failures and compute limits within engineer-approved safeguards. ## Hibernate-and-Wake Workflow Management - Training jobs may run for hours or days, so REA delegates waiting to a background system. - It hibernates to conserve resources and automatically wakes when jobs finish. - This lets it preserve context and continue experiments without constant human supervision. - REA is built on Meta’s Confucius agent framework, which provides: - Code-generation capabilities - Integration with job schedulers - Experiment tracking - Codebase navigation tools ## Dual-Source Hypothesis Generation - REA draws ideas from two systems: - **Historical Insights Database:** A repository of previous experiments, successes, and failures used for pattern recognition and in-context learning. - **ML Research Agent:** A research component that examines baseline configurations and proposes new optimization strategies. - Combining these sources produces configurations that may not emerge from either source alone. - Some of REA’s strongest improvements resulted from combining model architecture changes with training-efficiency techniques. ## Three-Phase Experiment Planning - Before running experiments, REA proposes an exploration plan, estimates GPU costs, and obtains engineer confirmation. - Its typical strategy includes: - **Validation:** Test individual hypotheses in parallel to establish baselines. - **Combination:** Combine promising ideas to identify synergistic effects. - **Exploitation:** Intensively optimize the strongest candidates within the approved compute budget. ## Autonomous Failure Handling and Safeguards - REA adapts to infrastructure problems, unexpected errors, poor results, and compute constraints without escalating every issue to an engineer. - It uses runbooks and diagnostic reasoning to: - Exclude jobs with clear out-of-memory failures - Detect training instability, such as exploding losses - Debug preliminary infrastructure failures - Reprioritize experiments when results are weak - Its autonomy is constrained by: - Access limited to Meta’s ads-ranking codebase - Explicit engineer approval through preflight reviews - Confirmed GPU budgets - Automatic pausing or stopping when thresholds are reached ## Production Results - Across six models, REA-driven iterations achieved approximately **2× the average model accuracy** compared with baseline. - Three engineers produced proposals to launch improvements for eight models. - Historically, that volume of work would have required roughly two engineers per model, resulting in about **5× greater engineering output** with REA. REA demonstrates that autonomous agents can improve ML experimentation by handling long-running execution, generating broader hypotheses, and recovering from routine failures. The most effective deployment model combines substantial agent autonomy with explicit compute limits, codebase restrictions, and human review at major strategic decisions.

Read original(opens in new tab)
dropbox3 min readCurated summary

How low-bit inference enables efficient AI

Low-bit inference reduces the memory, compute, and energy required to serve modern AI models by representing values with fewer bits. Quantization can substantially increase GPU throughput, but its benefits depend on model accuracy, hardware support, and whether workloads prioritize latency or throughput. The article presents low-bit inference as a production trade-off rather than a universally optimal technique. ## The Rising Cost of Modern Models - Models are growing rapidly, increasing demand for: - Memory capacity - Compute power - Energy - Low-latency serving infrastructure - Dropbox uses attention-based models for Dash and other capabilities involving: - Text, image, video, and audio understanding - Search and summarization - Reasoning over large collections of content - Production deployment requires balancing model capability with hardware utilization, cost, and responsiveness. ## Where Inference Compute Is Spent - Most computation comes from repeated matrix multiplications in two areas: - **Linear layers**, including attention projections, MLP layers, and final output layers. - **Attention mechanisms**, which calculate relationships between input tokens and become increasingly expensive with longer contexts. - GPUs accelerate these operations using specialized hardware: - NVIDIA Tensor Cores - AMD Matrix Cores - These cores execute matrix multiply-accumulate operations much faster than general-purpose CUDA cores. ## How Lower Precision Improves Efficiency - Quantization reduces the number of bits used to represent model values. - Converting values from 16-bit to 8-bit or 4-bit formats: - Reduces memory usage - Lowers memory-transfer costs - Can increase matrix-operation throughput - Reduces energy consumption - GPU throughput generally improves as precision decreases; halving precision can approximately double the number of operations performed per second in suitable workloads. - Eight-bit quantization maps values into 256 discrete levels. Formats below 8 bits typically require **bitpacking**, combining multiple values into types such as `uint8` or `int32` because 4-bit values are not normally stored as native hardware types. - Newer hardware, such as Blackwell GPUs with FP4 support, can provide major energy savings compared with higher-precision systems like the H100. ## Limits of Extremely Low-Bit Formats - Binary and ternary quantization restricts weights to two or three possible values, offering greater theoretical savings. - These formats are not well matched to today’s GPUs because they cannot fully use Tensor or Matrix Cores. - Specialized accelerators could make them more practical, but adoption remains limited by: - Weak ecosystem support - Hardware availability - Concerns about model quality - Practical gains therefore depend not only on bit width, but also on how well the format is supported by existing hardware and software. ## Quantization Formats and Deployment Trade-offs - Quantization is a family of techniques with different choices for: - Numerical representation - Scaling - Execution strategy - These choices affect: - Model accuracy - Inference speed - Memory consumption - Hardware utilization - Different workloads have different priorities: - Latency-sensitive applications need fast individual requests. - Throughput-oriented workloads prioritize processing large volumes efficiently. - Depending on the workload, inference may be limited by software overhead, memory bandwidth, or specialized GPU compute units. ## Pre-MXFP and MXFP Approaches - The article divides modern low-bit formats into two broad groups following the introduction of **MXFP microscaling**: - **Pre-MXFP formats** rely on software-managed scaling and explicit dequantization. - **MXFP formats** move scaling and related operations into Tensor Core hardware. - MXFP aims to standardize low-bit data types while making them more directly usable by modern GPUs. - The choice between these approaches depends on the hardware generation and the specific performance requirements of each production workload. Low-bit inference is most effective when quantization formats, model quality, and hardware capabilities are considered together. Teams should select formats based on the actual bottleneck—memory, bandwidth, latency, or compute—rather than assuming that the fewest possible bits will always deliver the best result.

Read original(opens in new tab)
google3 min readCurated summary

​Sequential Attention: Making AI models leaner and faster without sacrificing accuracy

Sequential Attention is a greedy subset-selection method designed to make large machine-learning models smaller and faster without materially reducing accuracy. It selects features, layers, blocks, or weights one at a time using attention scores that are recalculated after each choice, allowing the model to account for nonlinear interactions and redundancy. By integrating selection into a single training process, it aims to retain the quality of traditional greedy methods while avoiding their prohibitive computational cost. ## The Subset-Selection Challenge - Feature selection removes irrelevant or redundant inputs, but finding the optimal subset is NP-hard. - Deep neural networks make selection harder because: - A feature that seems unimportant alone may be essential in combination with others. - Features that appear valuable individually may become redundant when selected together. - The same problem applies beyond input features: - Selecting embedding dimensions or chunks. - Pruning entries or blocks from weight matrices. - Choosing layers or other model components. ## How Sequential Attention Works - The method builds a subset step by step rather than weighting all candidates at once. - At each stage: - Previously selected candidates provide context. - Attention scores estimate the importance of every remaining candidate. - The highest-scoring candidate is added permanently. - The model recalculates scores to reflect the candidate’s marginal contribution. - This adaptive process can identify high-order nonlinear interactions that simpler filter methods may miss. - It uses softmax-based attention scores for ranking, but applies them sequentially instead of in a single pass. - Although greedy selection can be expensive when each candidate requires model retraining or evaluation, Sequential Attention performs selection within one training process, greatly reducing overhead. ## Main Benefits - **Efficiency and accuracy:** Candidates can be evaluated in parallel once attention scores are available, while sequential updates preserve adaptive selection. - **Interpretability:** Attention scores provide a view into which inputs or components the model considered important. - **Scalability:** The approach is intended for large candidate sets and modern deep-learning architectures. - **Reduced redundancy:** Recalculating scores after each selection helps prevent the model from repeatedly choosing overlapping or unnecessary components. ## Feature Selection - Traditional greedy feature selection repeatedly retrains or reevaluates a model for every possible feature at every step. - Sequential Attention replaces these expensive marginal-gain calculations with the model’s internal attention weights. - The algorithm: - Scores all unselected features. - Adds the feature with the highest score. - Reruns the model and updates the scores for the remaining features. - The method reportedly achieved state-of-the-art or competitive results across proteomics, image, and activity-recognition benchmarks. - Its one-pass implementation makes greedy-style selection substantially faster. - For linear regression, Sequential Attention is mathematically equivalent to Orthogonal Matching Pursuit (OMP), an established method with theoretical reliability and performance guarantees. ## Block Sparsification - Neural-network pruning removes unnecessary weights to reduce model size and improve deployment efficiency. - Block sparsification removes groups of parameters rather than individual weights, making the resulting sparsity more compatible with hardware acceleration. - Earlier approaches generally fell into two categories: - **Differentiable pruning**, which learns continuous importance proxies. - **Combinatorial optimization**, which searches directly for sparse structures. - The referenced work, “SequentialAttention++ for Block Sparsification,” aims to combine these differentiable and combinatorial approaches into a unified pruning framework. Sequential Attention is best understood as an adaptive, attention-based alternative to costly repeated subset searches. It is particularly promising when model components interact nonlinearly and when hardware-friendly sparsity or feature reduction is needed at scale.

Read original(opens in new tab)
googleOriginal article

Google Research at Google I/O 2025 (opens in new tab)

Google Research at I/O 2025 showcases the "research to reality" transition, highlighting how years of foundational breakthroughs are now being integrated into Gemini models and specialized products. By focusing on multimodal capabilities, pedagogy, and extreme model efficiency, Google aims to democratize access to advanced AI while ensuring it remains grounded and useful across global contexts. ## Specialized Healthcare Models: MedGemma and AMIE * **MedGemma:** This new open model, based on Gemma 3, is optimized for multimodal medical tasks such as radiology image analysis and clinical data summarization. It is available in 4B and 27B sizes, performing similarly to much larger models on the MedQA benchmark while remaining small enough for efficient local fine-tuning. * **AMIE (Articulate Medical Intelligence Explorer):** A research AI agent designed for diagnostic medical reasoning. Its latest multimodal version can now interpret and reason about visual medical information, such as skin lesions or medical imaging, to assist clinicians in diagnostic accuracy. ## Educational Optimization through LearnLM * **Gemini 2.5 Pro Integration:** The LearnLM family of models, developed with educational experts, is now integrated into Gemini 2.5 Pro. This fine-tuning enhances STEM reasoning, multimodal understanding, and pedagogical feedback. * **Interactive Learning Tools:** A new research-optimized quiz experience allows students to generate custom assessments from their own notes, providing specific feedback on right and wrong answers rather than just providing solutions. * **Global Assessment Pilots:** Through partnerships like the one with Kayma, Google is testing the automatic assessment of short and long-form content in regions like Ghana to scale quality educational tools. ## Multilingual Expansion and On-Device Gemma Models * **Gemma 3 and 3n:** Research breakthroughs have expanded Gemma 3’s support to over 140 languages. The introduction of **Gemma 3n** targets extreme efficiency, capable of running on devices with as little as 2GB of RAM while maintaining low latency and low energy consumption. * **ECLeKTic Benchmark:** To assist the developer community, Google introduced this novel benchmark specifically for evaluating how well large language models transfer knowledge across different languages. ## Model Efficiency and Factuality in Search * **Inference Techniques:** Google Research continues to set industry standards for model speed and accessibility through technical innovations like **speculative decoding** and **cascades**, which reduce the computational cost of generating high-quality responses. * **Grounded Outputs:** Significant focus remains on factual consistency, ensuring that the AI models powering features like AI Overviews in Search provide reliable and grounded information to users. As Google continues to shrink the gap between laboratory breakthroughs and consumer products, the emphasis remains on making high-performance AI accessible on low-cost hardware and across diverse linguistic landscapes. Developers and researchers can now leverage these specialized tools via platforms like HuggingFace and Vertex AI to build more targeted, efficient applications.