Operator Affinity Optimization for Large Models: A Practical Guide

    This guide explains how to apply operator affinity optimization to large dense and mixture-of-experts models. It covers a three-layer profiling approach for locating bottlenecks, operator fusion strategies, memory layout and tiling choices, pipeline and parallelism tuning, numerical precision trade-offs, and benchmark regression gates. Readers will find practical decision principles and configuration examples for turning peak hardware compute into stable, repeatable throughput gains.

    1. Why Operator Affinity Optimization Matters

    In real deployments of large dense and mixture-of-experts (MoE) models, peak hardware compute is often left unused. The cause is usually not the individual operator implementation, but a mismatch between the compute graph structure and the hardware execution model: operators that are too fine-grained increase launch overhead, intermediate tensors repeatedly moving in and out of global memory create bandwidth bottlenecks, memory access patterns are unfriendly to on-chip cache hierarchies, and parallel partitioning does not match the communication topology.

    The goal of operator affinity optimization is to make the compute graph align more closely with hardware characteristics at operator boundaries, memory hierarchies, and parallel dimensions, turning “it runs” into “it runs stably and saturates the hardware.”

    Affinity optimization is not a magic switch for a specific hardware model. It is a transferable methodology: quantify the bottleneck first, then choose fusion, layout, pipelining, and communication strategies, and finally validate the gains with reproducible benchmarks.

    2. Locate Bottlenecks Before Optimizing

    All optimization should rest on trustworthy measurement. A three-layer observability system is recommended:

    • End-to-end layer: throughput, time to first token, tail latency, cost per request.
    • Operator layer: time share per operator, launch counts, memory traffic, cache hit behavior.
    • System layer: compute unit utilization, memory bandwidth usage, interconnect link load, stall and pipeline bubble ratios.

    A simplified analysis approach:

    1. # Pseudocode: aggregate time and memory traffic per operator to find top bottlenecks
    2. profile = capture_profile(model, sample_inputs)
    3. stats = {}
    4. for op in profile.ops:
    5. s = stats.setdefault(op.name, {"time": 0.0, "bytes": 0, "calls": 0})
    6. s["time"] += op.duration
    7. s["bytes"] += op.read_bytes + op.write_bytes
    8. s["calls"] += 1
    9. top = sorted(stats.items(), key=lambda kv: kv[1]["time"], reverse=True)[:10]
    10. for name, s in top:
    11. print(f"{name:30s} time={s['time']:.2f}ms "
    12. f"calls={s['calls']} avg_bytes={s['bytes']/max(s['calls'],1):.0f}")

    How to read the results: if a class of small operators has a high cumulative launch count but low per-call time, prioritize fusion; if a few operators move huge amounts of data and bandwidth is near its limit, prioritize layout and tiling; if compute utilization is high but there are regular bubbles, prioritize adjusting the pipeline and parallel partitioning.

    3. Operator Fusion: Fewer Boundaries and Round Trips

    Fusion reduces the number of operator boundaries and round trips to global memory. Common, reliably beneficial directions include:

    1. Elementwise chain fusion: merge elementwise operations such as normalization, activation, scaling, and bias into adjacent compute kernels so intermediate tensors never land in memory.
    2. Normalization and residual fusion: combine normalization with the residual add and the input preparation of the following linear transform to cut reads and writes.
    3. Attention fusion: organize scaling, masking, softmax, and weighted summation into a unified execution flow to shrink intermediate results.
    4. Feed-forward network fusion: coordinate gating, elementwise multiply, and down-projection under a tiling strategy to reduce large temporary buffers.

    Fusion must respect correctness boundaries: numerical stability (such as subtracting the max before softmax), accumulation precision (use higher-precision accumulation when necessary), and differentiability for backpropagation. Illustrative configuration:

    1. fusion_policy = {
    2. "enable_elementwise_chain": True,
    3. "fuse_norm_with_residual": True,
    4. "attention_fuse_scale_mask_softmax": True,
    5. "accumulate_in_high_precision": True,
    6. }
    7. graph = optimize_graph(model, policy=fusion_policy)

    4. Memory and Data Layout: Spend Bandwidth Where It Counts

    Memory access optimization focuses on three things: access contiguity, tile size, and cache reuse distance.

    • Layout choice: benchmark channels-first against channels-last, pick the layout that best matches the main compute kernel, and avoid frequent rearrangements.
    • Tiling and partitioning: size tiles to fit on-chip cache capacity so a tile’s data is reused across multiple computations instead of streaming through once.
    • Lifetime management: pool long-lived tensors and large temporary buffers for reuse to reduce allocation and release jitter.
    1. layout = choose_layout(graph, candidates=["channel_last", "channel_first"])
    2. graph = apply_layout(graph, layout)
    3. graph = tile_and_schedule(graph, tile_size="auto", reuse_scope="block")

    Practical note: layout conversion itself has a cost. Evaluate the net gain of “conversion count × cost per conversion” against “speedup of the benefiting kernels” globally, and avoid letting a local optimum drag down the whole graph.

    5. Pipelines and Parallelism: Minimize Bubbles

    Large model workloads often mix compute-intensive and memory-intensive stages, and serial execution amplifies bubbles. Stage splitting and multi-stage pipelining let different stages overlap in time. On the parallel dimension, tensor partitioning, pipeline partitioning, and load balance of expert routing need to be considered together.

    • Match partitioning to topology: place high-frequency communication on link dimensions with more headroom to reduce cross-domain round trips.
    • Overlap communication with computation: push synchronization points as late as possible and overlap asynchronous transfers with computation.
    • Load balance: for routing-based structures, monitor load skew across branches and adjust the capacity factor and drop policy when needed.
    1. stage0: [compute]----[comm]--
    2. stage1: --[compute]----[comm]
    3. overlap: ^^^^^^^^^^

    6. Numerics and Precision: Performance Without Losing Usability

    Affinity optimization is often combined with low-precision and mixed-precision strategies. The principle: keep higher precision for sensitive steps such as accumulation and reduction, and use lower precision for elementwise operations and projections to trade for bandwidth and throughput. In parallel, maintain a dual regression of per-layer error and task-level metrics to keep precision loss within an acceptable range.

    7. Validation and Regression: Make Gains Reproducible

    Fix a benchmark suite and a gate: pin the input distribution and random seed, record throughput, latency percentiles, resource utilization, and accuracy metrics, then run an automatic regression after every graph optimization or scheduling change and block the merge if a key metric degrades. Keep a rollback switch for fast mitigation in production.

    1. benchmark:
    2. dataset: fixed_sample
    3. metrics: [throughput, p99_latency, mem_bw_util, accuracy]
    4. gate:
    5. throughput_min_gain: 0.03
    6. accuracy_max_drop: 0.001
    7. rollback_switch: enabled

    8. Adoption Roadmap

    1. Build the three-layer observability system and a unified benchmark; define optimization goals and red lines.
    2. Start with low-risk fusion and layout optimizations to capture stable gains quickly.
    3. Then advance pipeline and parallelism adjustments to reduce bubbles and communication overhead.
    4. Finally introduce coordinated precision and scheduling tuning to approach the usable hardware limit.
    5. Safeguard stability throughout with automatic regression and rollback mechanisms.

    The value of operator affinity optimization is turning hardware characteristics into reusable engineering constraints, making performance improvement a sustainable iteration rather than occasional parameter tweaking. In related technical practice at Baidu AI Cloud, the same recommendation applies: start from quantified observability, use regression gates as guardrails, and steadily unlock the real capability of high-compute platforms.