Commit df469fe677 for aom

commit df469fe677cbd51ba72bffae9730333a17749293
Author: Frank Galligan <fgalligan@google.com>
Date:   Tue Nov 24 15:15:59 2026 -0800

    rd: vectorize CDF token cost table generation

    Extend the RTCD CDF batch cost primitives in av1/encoder/cost.c and
    av1/encoder/x86/cost_avx2.c (AVX2 for 2..16 symbols, 5..16 for
    inverse-mapped, with portable C fallback outside that range):

    - Add RTCD av1_cost_tokens_from_cdf_batch and
      av1_cost_tokens_from_cdf_inv_batch with C and AVX2 implementations
      using strictly bounded loads and stores and inv_map caching/bounds
      checks.
    - Optimize av1_cost_tokens_from_cdf_{2,4}_batch_avx2 with gather-free
      and transpose-free <8 tail paths (cost_2_cdf4_avx2, cost_4_cdf2_avx2,
      and cost_1_cdf4_from_vec) while keeping cost_tokens_cdf{2,4}_x8 +
      MIN_OVERLAP_TAIL (gated on n >= 8) and av1_prob_cost mantissa lookup.
    - Route av1_fill_mode_rates(), fill_inter_tx_type_costs(),
      fill_deferred_inter_mode_rates(), and av1_fill_coeff_costs() (all
      modes, removing is_realtime) through batch primitives, batching
      wedge_idx_cost and sequence-level filter-intra ranges, caching CfL
      alpha costs, and reusing luma txb_skip_cost for chroma.
    - Add unit tests, FillModeAndCoeffCostsParity integration check, and
      DISABLED_Batch*Speed benchmarks in test/cost_test.cc.

    Speedup (AMD EPYC 7B13, Clang 21, bit-exact):
    - vs 433c8742ce: -10.88% (1T) RT speed 8 VGA (niklas 90f) and -1.56%
      (1T) 1080p allintra speed 6; prior 5381b9a7a6: -10.09% (1T) /
      -6.82% (8T) RT speed 8 VGA.
    - test_libaom AVX2 vs C kernel speedups: 2.07x-3.51x (2/4-sym),
      2.44x-5.87x (general, 3.98x mixed), and 1.65x-2.70x (inv-mapped).
    Binary size (x86_64 -O3): libaom.a .text -5.5 KiB (-0.07%),
      .rodata +0.1 KiB (+0.01%); stripped aomenc -4.0 KiB (-0.04%).
    Memory (peak RSS, 1080p allintra): 1T -72 KiB (-0.16%),
      8T -692 KiB (-1.32%); 720p good 1T -148 KiB (-0.06%),
      rt 1T +236 KiB (+0.56%).

    TAG=agy
    CONV=4b696004-0036-42b2-b3fa-d1c7d63a973c
    Change-Id: I5217188c29b613fa7127426196b11fa05ccd222e

diff --git a/av1/common/av1_rtcd_defs.pl b/av1/common/av1_rtcd_defs.pl
index 1bb08ffe2a..dc844ffc96 100644
--- a/av1/common/av1_rtcd_defs.pl
+++ b/av1/common/av1_rtcd_defs.pl
@@ -316,6 +316,12 @@ if (aom_config("CONFIG_AV1_ENCODER") eq "yes") {
   add_proto qw/void av1_cost_tokens_from_cdf_4_batch/, "int *costs, int costs_stride, const uint16_t *cdf, int cdf_stride, int n";
   specialize qw/av1_cost_tokens_from_cdf_4_batch avx2/;

+  add_proto qw/void av1_cost_tokens_from_cdf_batch/, "int *costs, int costs_stride, const uint16_t *cdf, int cdf_stride, int nsyms, int n";
+  specialize qw/av1_cost_tokens_from_cdf_batch avx2/;
+
+  add_proto qw/void av1_cost_tokens_from_cdf_inv_batch/, "int *costs, int costs_stride, const uint16_t *cdf, int cdf_stride, const int *inv_map, int nsyms, int n";
+  specialize qw/av1_cost_tokens_from_cdf_inv_batch avx2/;
+
   add_proto qw/void av1_quantize_fp/, "const tran_low_t *coeff_ptr, intptr_t n_coeffs, const int16_t *zbin_ptr, const int16_t *round_ptr, const int16_t *quant_ptr, const int16_t *quant_shift_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan";
   specialize qw/av1_quantize_fp sse2 avx2 neon/;

diff --git a/av1/encoder/cost.c b/av1/encoder/cost.c
index 81988cfff8..6129039fb8 100644
--- a/av1/encoder/cost.c
+++ b/av1/encoder/cost.c
@@ -14,12 +14,13 @@

 #include "aom_dsp/entcode.h"
 #include "aom_ports/aom_once.h"
+#include "aom_ports/mem.h"
 #include "av1/encoder/cost.h"
 #include "av1/common/entropy.h"

 // round(-log2(i/256.) * (1 << AV1_PROB_COST_SHIFT)); i = 128~255 (plus 128th
 // duplicate for 256).
-const uint16_t av1_prob_cost[129] = {
+DECLARE_ALIGNED(32, const uint16_t, av1_prob_cost[129]) = {
   512, 506, 501, 495, 489, 484, 478, 473, 467, 462, 456, 451, 446, 441, 435,
   430, 425, 420, 415, 410, 405, 400, 395, 390, 385, 380, 375, 371, 366, 361,
   356, 352, 347, 343, 338, 333, 329, 324, 320, 316, 311, 307, 302, 298, 294,
@@ -69,8 +70,15 @@ void av1_cost_tokens_from_cdf(int *costs, const aom_cdf_prob *cdf,
 void av1_cost_tokens_from_cdf_2_batch_c(int *costs, int costs_stride,
                                         const uint16_t *cdf, int cdf_stride,
                                         int n) {
-  for (int i = 0; i < n; ++i)
+  assert(n >= 0);
+  if (n == 0) return;
+  assert(costs != NULL && cdf != NULL);
+  assert(costs_stride >= 2);
+  assert(n <= 1 || cdf_stride >= 2);
+  for (int i = 0; i < n; ++i) {
+    assert(cdf[i * cdf_stride + 1] == 0);
     av1_cost_tokens_from_cdf_2(costs + i * costs_stride, cdf + i * cdf_stride);
+  }
 }

 // Fills N=4 costs for `n` CDFs: costs[k*costs_stride + 0..3] gets the four
@@ -78,6 +86,65 @@ void av1_cost_tokens_from_cdf_2_batch_c(int *costs, int costs_stride,
 void av1_cost_tokens_from_cdf_4_batch_c(int *costs, int costs_stride,
                                         const uint16_t *cdf, int cdf_stride,
                                         int n) {
+  assert(n >= 0);
+  if (n == 0) return;
+  assert(costs != NULL && cdf != NULL);
+  assert(costs_stride >= 4);
+  assert(n <= 1 || cdf_stride >= 4);
   for (int i = 0; i < n; ++i)
     av1_cost_tokens_from_cdf_4(costs + i * costs_stride, cdf + i * cdf_stride);
 }
+
+// Fills `nsyms` symbol costs for `n` CDFs (inv_map is implicitly NULL).
+void av1_cost_tokens_from_cdf_batch_c(int *costs, int costs_stride,
+                                      const uint16_t *cdf, int cdf_stride,
+                                      int nsyms, int n) {
+  assert(nsyms >= 2);
+  assert(n >= 0);
+  if (n == 0) return;
+  assert(costs != NULL && cdf != NULL);
+  assert(costs_stride >= nsyms);
+  assert(n <= 1 || cdf_stride >= nsyms);
+  for (int c = 0; c < n; ++c) {
+    int *const dst = costs + c * costs_stride;
+    const uint16_t *const src = cdf + c * cdf_stride;
+    assert(nsyms != 2 || src[1] == 0);
+    int prev_icdf = CDF_PROB_TOP;
+    int i = 0;
+    do {
+      const int cur_icdf = src[i];
+      const int p15 =
+          clamp(prev_icdf - cur_icdf, EC_MIN_PROB, CDF_PROB_TOP - 1);
+      prev_icdf = cur_icdf;
+      dst[i] = av1_cost_symbol_clamped(p15);
+    } while (++i != nsyms);
+  }
+}
+
+// Fills `nsyms` symbol costs for `n` CDFs, scattering output via `inv_map`.
+// Caller guarantees 0 <= inv_map[i] < costs_stride for all 0 <= i < nsyms.
+void av1_cost_tokens_from_cdf_inv_batch_c(int *costs, int costs_stride,
+                                          const uint16_t *cdf, int cdf_stride,
+                                          const int *inv_map, int nsyms,
+                                          int n) {
+  assert(nsyms >= 2);
+  assert(n >= 0);
+  if (n == 0) return;
+  assert(costs != NULL && cdf != NULL && inv_map != NULL);
+  assert(costs_stride >= nsyms);
+  assert(n <= 1 || cdf_stride >= nsyms);
+  for (int c = 0; c < n; ++c) {
+    int *const dst = costs + c * costs_stride;
+    const uint16_t *const src = cdf + c * cdf_stride;
+    int prev_icdf = CDF_PROB_TOP;
+    int i = 0;
+    do {
+      const int cur_icdf = src[i];
+      const int p15 =
+          clamp(prev_icdf - cur_icdf, EC_MIN_PROB, CDF_PROB_TOP - 1);
+      prev_icdf = cur_icdf;
+      assert(inv_map[i] >= 0 && inv_map[i] < costs_stride);
+      dst[inv_map[i]] = av1_cost_symbol_clamped(p15);
+    } while (++i != nsyms);
+  }
+}
diff --git a/av1/encoder/cost.h b/av1/encoder/cost.h
index e2f068217b..29ba0e0e1f 100644
--- a/av1/encoder/cost.h
+++ b/av1/encoder/cost.h
@@ -16,6 +16,7 @@

 #include "aom_dsp/entcode.h"
 #include "aom_dsp/prob.h"
+#include "aom_ports/mem.h"
 #include "aom/aom_integer.h"

 #ifdef __cplusplus
@@ -26,7 +27,7 @@ extern "C" {
 // COST_LUT_LOW * 2 B = 8 KB.
 #define COST_LUT_LOW 4096

-extern const uint16_t av1_prob_cost[129];
+DECLARE_ALIGNED(32, extern const uint16_t, av1_prob_cost[129]);
 extern uint16_t av1_cost_lut_low[COST_LUT_LOW];  // filled by av1_init_cost_luts

 // The factor to scale from cost in bits to cost in av1_prob_cost units.
@@ -93,6 +94,18 @@ void av1_cost_tokens_from_cdf(int *costs, const aom_cdf_prob *cdf,
                               const int *inv_map);
 void av1_init_cost_luts(void);  // one-time fill of av1_cost_lut_low

+// Batch CDF cost helpers (av1_cost_tokens_from_cdf_{2,4}_batch,
+// av1_cost_tokens_from_cdf_batch, and av1_cost_tokens_from_cdf_inv_batch) are
+// declared via av1_rtcd_defs.pl in config/av1_rtcd.h.
+// Preconditions for all batch helpers:
+//   - n >= 0 (if n == 0, returns without reading cdf or writing costs)
+//   - nsyms >= 2, costs_stride >= nsyms, and cdf_stride >= nsyms when n > 1
+//   - For av1_cost_tokens_from_cdf_2_batch (and av1_cost_tokens_from_cdf_batch
+//     with nsyms == 2): each input CDF must end with cdf[k * cdf_stride + 1]
+//     == 0 (standard 2-symbol AV1 terminator).
+//   - For av1_cost_tokens_from_cdf_inv_batch: inv_map != NULL and every
+//     inv_map[i] for 0 <= i < nsyms satisfies 0 <= inv_map[i] < costs_stride.
+
 #ifdef __cplusplus
 }  // extern "C"
 #endif
diff --git a/av1/encoder/encodeframe_utils.c b/av1/encoder/encodeframe_utils.c
index 8fb46a88f6..fae4a7b87b 100644
--- a/av1/encoder/encodeframe_utils.c
+++ b/av1/encoder/encodeframe_utils.c
@@ -1820,8 +1820,7 @@ void av1_set_cost_upd_freq(AV1_COMP *cpi, ThreadData *td,
       if (skip_cost_update(cm->seq_params, tile_info, mi_row, mi_col,
                            cpi->sf.inter_sf.coeff_cost_upd_level))
         break;
-      av1_fill_coeff_costs(&x->coeff_costs, xd->tile_ctx, num_planes,
-                           cpi->oxcf.mode == REALTIME);
+      av1_fill_coeff_costs(&x->coeff_costs, xd->tile_ctx, num_planes);
       break;
     default: assert(0);
   }
diff --git a/av1/encoder/rd.c b/av1/encoder/rd.c
index 8653970aad..0afac8f030 100644
--- a/av1/encoder/rd.c
+++ b/av1/encoder/rd.c
@@ -86,9 +86,11 @@ static void fill_inter_tx_type_costs(ModeCosts *mode_costs,
   for (int i = TX_4X4; i < EXT_TX_SIZES; ++i) {
     for (int s = 1; s < EXT_TX_SETS_INTER; ++s) {
       if (use_inter_ext_tx_for_txsize[s][i]) {
-        av1_cost_tokens_from_cdf(
-            mode_costs->inter_tx_type_costs[s][i], fc->inter_ext_tx_cdf[s][i],
-            av1_ext_tx_inv[av1_ext_tx_set_idx_to_type[1][s]]);
+        const int tx_set_type = av1_ext_tx_set_idx_to_type[1][s];
+        av1_cost_tokens_from_cdf_inv_batch(
+            mode_costs->inter_tx_type_costs[s][i], TX_TYPES,
+            fc->inter_ext_tx_cdf[s][i], CDF_SIZE(TX_TYPES),
+            av1_ext_tx_inv[tx_set_type], av1_num_ext_tx_set[tx_set_type], 1);
       }
     }
   }
@@ -100,142 +102,174 @@ static void fill_deferred_inter_mode_rates(ModeCosts *mode_costs,
                                            int fill_inter_tx_type) {
   mode_costs->intra_only_skipped_inter_costs = 0;
   mode_costs->intra_only_skipped_inter_tx_type = 0;
-  for (int i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) {
-    av1_cost_tokens_from_cdf(mode_costs->switchable_interp_costs[i],
-                             fc->switchable_interp_cdf[i], NULL);
-  }
+  av1_cost_tokens_from_cdf_batch(
+      mode_costs->switchable_interp_costs[0], SWITCHABLE_FILTERS,
+      fc->switchable_interp_cdf[0], CDF_SIZE(SWITCHABLE_FILTERS),
+      SWITCHABLE_FILTERS, SWITCHABLE_FILTER_CONTEXTS);
   if (fill_inter_tx_type) fill_inter_tx_type_costs(mode_costs, fc);
-  for (int i = 0; i < SEG_TEMPORAL_PRED_CTXS; ++i) {
-    av1_cost_tokens_from_cdf(mode_costs->tmp_pred_cost[i], fc->seg.pred_cdf[i],
-                             NULL);
-  }
+  av1_cost_tokens_from_cdf_2_batch(mode_costs->tmp_pred_cost[0], 2,
+                                   fc->seg.pred_cdf[0], CDF_SIZE(2),
+                                   SEG_TEMPORAL_PRED_CTXS);
 }

 void av1_fill_mode_rates(AV1_COMMON *const cm, ModeCosts *mode_costs,
                          FRAME_CONTEXT *fc) {
-  int i, j;
+  int i;
   const int is_intra_only = frame_is_intra_only(cm);

-  for (i = 0; i < PARTITION_CONTEXTS; ++i)
-    av1_cost_tokens_from_cdf(mode_costs->partition_cost[i],
-                             fc->partition_cdf[i], NULL);
+  static_assert(PARTITION_TYPES == 4, "");
+  static_assert(PARTITION_PLOFFSET == 4, "");
+  static_assert(PARTITION_CONTEXTS == 20, "");
+  av1_cost_tokens_from_cdf_4_batch(
+      mode_costs->partition_cost[0], EXT_PARTITION_TYPES, fc->partition_cdf[0],
+      CDF_SIZE(EXT_PARTITION_TYPES), PARTITION_PLOFFSET);
+  av1_cost_tokens_from_cdf_batch(
+      mode_costs->partition_cost[PARTITION_PLOFFSET], EXT_PARTITION_TYPES,
+      fc->partition_cdf[PARTITION_PLOFFSET], CDF_SIZE(EXT_PARTITION_TYPES),
+      EXT_PARTITION_TYPES, 3 * PARTITION_PLOFFSET);
+  static_assert(EXT_PARTITION_TYPES == 10, "");
+  av1_cost_tokens_from_cdf_batch(
+      mode_costs->partition_cost[4 * PARTITION_PLOFFSET], EXT_PARTITION_TYPES,
+      fc->partition_cdf[4 * PARTITION_PLOFFSET], CDF_SIZE(EXT_PARTITION_TYPES),
+      EXT_PARTITION_TYPES - 2, PARTITION_CONTEXTS - 4 * PARTITION_PLOFFSET);

   if (cm->current_frame.skip_mode_info.skip_mode_flag) {
-    for (i = 0; i < SKIP_MODE_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->skip_mode_cost[i],
-                               fc->skip_mode_cdfs[i], NULL);
-    }
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->skip_mode_cost[0], 2,
+                                     fc->skip_mode_cdfs[0], CDF_SIZE(2),
+                                     SKIP_MODE_CONTEXTS);
   } else {
     av1_zero(mode_costs->skip_mode_cost);
   }

-  for (i = 0; i < SKIP_CONTEXTS; ++i) {
-    av1_cost_tokens_from_cdf(mode_costs->skip_txfm_cost[i],
-                             fc->skip_txfm_cdfs[i], NULL);
-  }
+  av1_cost_tokens_from_cdf_2_batch(mode_costs->skip_txfm_cost[0], 2,
+                                   fc->skip_txfm_cdfs[0], CDF_SIZE(2),
+                                   SKIP_CONTEXTS);

-  for (i = 0; i < KF_MODE_CONTEXTS; ++i)
-    for (j = 0; j < KF_MODE_CONTEXTS; ++j)
-      av1_cost_tokens_from_cdf(mode_costs->y_mode_costs[i][j],
-                               fc->kf_y_cdf[i][j], NULL);
-
-  for (i = 0; i < BLOCK_SIZE_GROUPS; ++i)
-    av1_cost_tokens_from_cdf(mode_costs->mbmode_cost[i], fc->y_mode_cdf[i],
-                             NULL);
-  for (i = 0; i < CFL_ALLOWED_TYPES; ++i)
-    for (j = 0; j < INTRA_MODES; ++j)
-      av1_cost_tokens_from_cdf(mode_costs->intra_uv_mode_cost[i][j],
-                               fc->uv_mode_cdf[i][j], NULL);
-
-  av1_cost_tokens_from_cdf(mode_costs->filter_intra_mode_cost,
-                           fc->filter_intra_mode_cdf, NULL);
-  for (i = 0; i < BLOCK_SIZES_ALL; ++i) {
-    if (av1_filter_intra_allowed_bsize(cm, i))
-      av1_cost_tokens_from_cdf(mode_costs->filter_intra_cost[i],
-                               fc->filter_intra_cdfs[i], NULL);
+  for (i = 0; i < KF_MODE_CONTEXTS; ++i) {
+    av1_cost_tokens_from_cdf_batch(mode_costs->y_mode_costs[i][0], INTRA_MODES,
+                                   fc->kf_y_cdf[i][0], CDF_SIZE(INTRA_MODES),
+                                   INTRA_MODES, KF_MODE_CONTEXTS);
   }

-  for (i = 0; i < PALATTE_BSIZE_CTXS; ++i) {
-    av1_cost_tokens_from_cdf(mode_costs->palette_y_size_cost[i],
-                             fc->palette_y_size_cdf[i], NULL);
-    av1_cost_tokens_from_cdf(mode_costs->palette_uv_size_cost[i],
-                             fc->palette_uv_size_cdf[i], NULL);
-    for (j = 0; j < PALETTE_Y_MODE_CONTEXTS; ++j) {
-      av1_cost_tokens_from_cdf(mode_costs->palette_y_mode_cost[i][j],
-                               fc->palette_y_mode_cdf[i][j], NULL);
-    }
+  av1_cost_tokens_from_cdf_batch(mode_costs->mbmode_cost[0], INTRA_MODES,
+                                 fc->y_mode_cdf[0], CDF_SIZE(INTRA_MODES),
+                                 INTRA_MODES, BLOCK_SIZE_GROUPS);
+  static_assert(CFL_ALLOWED_TYPES == 2, "");
+  av1_cost_tokens_from_cdf_batch(
+      mode_costs->intra_uv_mode_cost[CFL_DISALLOWED][0], UV_INTRA_MODES,
+      fc->uv_mode_cdf[CFL_DISALLOWED][0], CDF_SIZE(UV_INTRA_MODES),
+      UV_INTRA_MODES - 1, INTRA_MODES);
+  av1_cost_tokens_from_cdf_batch(
+      mode_costs->intra_uv_mode_cost[CFL_ALLOWED][0], UV_INTRA_MODES,
+      fc->uv_mode_cdf[CFL_ALLOWED][0], CDF_SIZE(UV_INTRA_MODES), UV_INTRA_MODES,
+      INTRA_MODES);
+
+  av1_cost_tokens_from_cdf_batch(mode_costs->filter_intra_mode_cost,
+                                 FILTER_INTRA_MODES, fc->filter_intra_mode_cdf,
+                                 CDF_SIZE(FILTER_INTRA_MODES),
+                                 FILTER_INTRA_MODES, 1);
+  if (cm->seq_params->enable_filter_intra) {
+    // Blocks <= 32x32 form two contiguous ranges in BLOCK_SIZE:
+    // [BLOCK_4X4, BLOCK_32X32] and [BLOCK_4X16, BLOCK_32X8].
+    static_assert(BLOCK_4X4 == 0 && BLOCK_32X32 == 9, "");
+    static_assert(BLOCK_4X16 == 16 && BLOCK_32X8 == 19, "");
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->filter_intra_cost[BLOCK_4X4],
+                                     2, fc->filter_intra_cdfs[BLOCK_4X4],
+                                     CDF_SIZE(2), BLOCK_32X32 - BLOCK_4X4 + 1);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->filter_intra_cost[BLOCK_4X16],
+                                     2, fc->filter_intra_cdfs[BLOCK_4X16],
+                                     CDF_SIZE(2), BLOCK_32X8 - BLOCK_4X16 + 1);
   }

-  for (i = 0; i < PALETTE_UV_MODE_CONTEXTS; ++i) {
-    av1_cost_tokens_from_cdf(mode_costs->palette_uv_mode_cost[i],
-                             fc->palette_uv_mode_cdf[i], NULL);
-  }
+  av1_cost_tokens_from_cdf_batch(mode_costs->palette_y_size_cost[0],
+                                 PALETTE_SIZES, fc->palette_y_size_cdf[0],
+                                 CDF_SIZE(PALETTE_SIZES), PALETTE_SIZES,
+                                 PALATTE_BSIZE_CTXS);
+  av1_cost_tokens_from_cdf_batch(mode_costs->palette_uv_size_cost[0],
+                                 PALETTE_SIZES, fc->palette_uv_size_cdf[0],
+                                 CDF_SIZE(PALETTE_SIZES), PALETTE_SIZES,
+                                 PALATTE_BSIZE_CTXS);
+  av1_cost_tokens_from_cdf_2_batch(
+      mode_costs->palette_y_mode_cost[0][0], 2, fc->palette_y_mode_cdf[0][0],
+      CDF_SIZE(2), PALATTE_BSIZE_CTXS * PALETTE_Y_MODE_CONTEXTS);
+  av1_cost_tokens_from_cdf_2_batch(mode_costs->palette_uv_mode_cost[0], 2,
+                                   fc->palette_uv_mode_cdf[0], CDF_SIZE(2),
+                                   PALETTE_UV_MODE_CONTEXTS);

   for (i = 0; i < PALETTE_SIZES; ++i) {
-    for (j = 0; j < PALETTE_COLOR_INDEX_CONTEXTS; ++j) {
-      av1_cost_tokens_from_cdf(mode_costs->palette_y_color_cost[i][j],
-                               fc->palette_y_color_index_cdf[i][j], NULL);
-      av1_cost_tokens_from_cdf(mode_costs->palette_uv_color_cost[i][j],
-                               fc->palette_uv_color_index_cdf[i][j], NULL);
-    }
+    const int nsyms = i + PALETTE_MIN_SIZE;
+    av1_cost_tokens_from_cdf_batch(
+        mode_costs->palette_y_color_cost[i][0], PALETTE_COLORS,
+        fc->palette_y_color_index_cdf[i][0], CDF_SIZE(PALETTE_COLORS), nsyms,
+        PALETTE_COLOR_INDEX_CONTEXTS);
+    av1_cost_tokens_from_cdf_batch(
+        mode_costs->palette_uv_color_cost[i][0], PALETTE_COLORS,
+        fc->palette_uv_color_index_cdf[i][0], CDF_SIZE(PALETTE_COLORS), nsyms,
+        PALETTE_COLOR_INDEX_CONTEXTS);
   }

   int sign_cost[CFL_JOINT_SIGNS];
-  av1_cost_tokens_from_cdf(sign_cost, fc->cfl_sign_cdf, NULL);
+  av1_cost_tokens_from_cdf_batch(sign_cost, CFL_JOINT_SIGNS, fc->cfl_sign_cdf,
+                                 CDF_SIZE(CFL_JOINT_SIGNS), CFL_JOINT_SIGNS, 1);
+  int alpha_cost[CFL_ALPHA_CONTEXTS][CFL_ALPHABET_SIZE];
+  av1_cost_tokens_from_cdf_batch(
+      alpha_cost[0], CFL_ALPHABET_SIZE, fc->cfl_alpha_cdf[0],
+      CDF_SIZE(CFL_ALPHABET_SIZE), CFL_ALPHABET_SIZE, CFL_ALPHA_CONTEXTS);
   for (int joint_sign = 0; joint_sign < CFL_JOINT_SIGNS; joint_sign++) {
     int *cost_u = mode_costs->cfl_cost[joint_sign][CFL_PRED_U];
     int *cost_v = mode_costs->cfl_cost[joint_sign][CFL_PRED_V];
+    const int s_cost = sign_cost[joint_sign];
     if (CFL_SIGN_U(joint_sign) == CFL_SIGN_ZERO) {
-      memset(cost_u, 0, CFL_ALPHABET_SIZE * sizeof(*cost_u));
+      for (int u = 0; u < CFL_ALPHABET_SIZE; u++) cost_u[u] = s_cost;
     } else {
-      const aom_cdf_prob *cdf_u = fc->cfl_alpha_cdf[CFL_CONTEXT_U(joint_sign)];
-      av1_cost_tokens_from_cdf(cost_u, cdf_u, NULL);
+      const int *const au = alpha_cost[CFL_CONTEXT_U(joint_sign)];
+      for (int u = 0; u < CFL_ALPHABET_SIZE; u++) cost_u[u] = au[u] + s_cost;
     }
     if (CFL_SIGN_V(joint_sign) == CFL_SIGN_ZERO) {
       memset(cost_v, 0, CFL_ALPHABET_SIZE * sizeof(*cost_v));
     } else {
-      const aom_cdf_prob *cdf_v = fc->cfl_alpha_cdf[CFL_CONTEXT_V(joint_sign)];
-      av1_cost_tokens_from_cdf(cost_v, cdf_v, NULL);
+      memcpy(cost_v, alpha_cost[CFL_CONTEXT_V(joint_sign)],
+             CFL_ALPHABET_SIZE * sizeof(*cost_v));
     }
-    for (int u = 0; u < CFL_ALPHABET_SIZE; u++)
-      cost_u[u] += sign_cost[joint_sign];
   }

-  for (i = 0; i < MAX_TX_CATS; ++i)
-    for (j = 0; j < TX_SIZE_CONTEXTS; ++j)
-      av1_cost_tokens_from_cdf(mode_costs->tx_size_cost[i][j],
-                               fc->tx_size_cdf[i][j], NULL);
+  av1_cost_tokens_from_cdf_2_batch(
+      mode_costs->tx_size_cost[0][0], TX_SIZES, fc->tx_size_cdf[0][0],
+      CDF_SIZE(MAX_TX_DEPTH + 1), TX_SIZE_CONTEXTS);
+  av1_cost_tokens_from_cdf_batch(mode_costs->tx_size_cost[1][0], TX_SIZES,
+                                 fc->tx_size_cdf[1][0],
+                                 CDF_SIZE(MAX_TX_DEPTH + 1), MAX_TX_DEPTH + 1,
+                                 (MAX_TX_CATS - 1) * TX_SIZE_CONTEXTS);

-  for (i = 0; i < TXFM_PARTITION_CONTEXTS; ++i) {
-    av1_cost_tokens_from_cdf(mode_costs->txfm_partition_cost[i],
-                             fc->txfm_partition_cdf[i], NULL);
-  }
+  av1_cost_tokens_from_cdf_2_batch(mode_costs->txfm_partition_cost[0], 2,
+                                   fc->txfm_partition_cdf[0], CDF_SIZE(2),
+                                   TXFM_PARTITION_CONTEXTS);

   const int allow_intrabc = av1_allow_intrabc(cm);
   if (allow_intrabc) {
     fill_inter_tx_type_costs(mode_costs, fc);
-    av1_cost_tokens_from_cdf(mode_costs->intrabc_cost, fc->intrabc_cdf, NULL);
+    av1_cost_tokens_from_cdf_2(mode_costs->intrabc_cost, fc->intrabc_cdf);
   }
   for (i = TX_4X4; i < EXT_TX_SIZES; ++i) {
     for (int s = 1; s < EXT_TX_SETS_INTRA; ++s) {
       if (use_intra_ext_tx_for_txsize[s][i]) {
-        for (j = 0; j < INTRA_MODES; ++j) {
-          av1_cost_tokens_from_cdf(
-              mode_costs->intra_tx_type_costs[s][i][j],
-              fc->intra_ext_tx_cdf[s][i][j],
-              av1_ext_tx_inv[av1_ext_tx_set_idx_to_type[0][s]]);
-        }
+        const int tx_set_type = av1_ext_tx_set_idx_to_type[0][s];
+        av1_cost_tokens_from_cdf_inv_batch(
+            mode_costs->intra_tx_type_costs[s][i][0], TX_TYPES,
+            fc->intra_ext_tx_cdf[s][i][0], CDF_SIZE(TX_TYPES),
+            av1_ext_tx_inv[tx_set_type], av1_num_ext_tx_set[tx_set_type],
+            INTRA_MODES);
       }
     }
   }
-  for (i = 0; i < DIRECTIONAL_MODES; ++i) {
-    av1_cost_tokens_from_cdf(mode_costs->angle_delta_cost[i],
-                             fc->angle_delta_cdf[i], NULL);
-  }
-  for (i = 0; i < SPATIAL_PREDICTION_PROBS; ++i) {
-    av1_cost_tokens_from_cdf(mode_costs->spatial_pred_cost[i],
-                             fc->seg.spatial_pred_seg_cdf[i], NULL);
-  }
+  av1_cost_tokens_from_cdf_batch(
+      mode_costs->angle_delta_cost[0], 2 * MAX_ANGLE_DELTA + 1,
+      fc->angle_delta_cdf[0], CDF_SIZE(2 * MAX_ANGLE_DELTA + 1),
+      2 * MAX_ANGLE_DELTA + 1, DIRECTIONAL_MODES);
+  av1_cost_tokens_from_cdf_batch(mode_costs->spatial_pred_cost[0], MAX_SEGMENTS,
+                                 fc->seg.spatial_pred_seg_cdf[0],
+                                 CDF_SIZE(MAX_SEGMENTS), MAX_SEGMENTS,
+                                 SPATIAL_PREDICTION_PROBS);

   if (is_intra_only) {
     mode_costs->intra_only_skipped_inter_costs = 1;
@@ -243,106 +277,93 @@ void av1_fill_mode_rates(AV1_COMMON *const cm, ModeCosts *mode_costs,
   } else {
     fill_deferred_inter_mode_rates(mode_costs, fc, /*fill_inter_tx_type=*/1);

-    for (i = 0; i < COMP_INTER_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->comp_inter_cost[i],
-                               fc->comp_inter_cdf[i], NULL);
-    }
-
-    for (i = 0; i < REF_CONTEXTS; ++i) {
-      for (j = 0; j < SINGLE_REFS - 1; ++j) {
-        av1_cost_tokens_from_cdf(mode_costs->single_ref_cost[i][j],
-                                 fc->single_ref_cdf[i][j], NULL);
-      }
-    }
-
-    for (i = 0; i < COMP_REF_TYPE_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->comp_ref_type_cost[i],
-                               fc->comp_ref_type_cdf[i], NULL);
-    }
-
-    for (i = 0; i < UNI_COMP_REF_CONTEXTS; ++i) {
-      for (j = 0; j < UNIDIR_COMP_REFS - 1; ++j) {
-        av1_cost_tokens_from_cdf(mode_costs->uni_comp_ref_cost[i][j],
-                                 fc->uni_comp_ref_cdf[i][j], NULL);
-      }
-    }
-
-    for (i = 0; i < REF_CONTEXTS; ++i) {
-      for (j = 0; j < FWD_REFS - 1; ++j) {
-        av1_cost_tokens_from_cdf(mode_costs->comp_ref_cost[i][j],
-                                 fc->comp_ref_cdf[i][j], NULL);
-      }
-    }
-
-    for (i = 0; i < REF_CONTEXTS; ++i) {
-      for (j = 0; j < BWD_REFS - 1; ++j) {
-        av1_cost_tokens_from_cdf(mode_costs->comp_bwdref_cost[i][j],
-                                 fc->comp_bwdref_cdf[i][j], NULL);
-      }
-    }
-
-    for (i = 0; i < INTRA_INTER_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->intra_inter_cost[i],
-                               fc->intra_inter_cdf[i], NULL);
-    }
-
-    for (i = 0; i < NEWMV_MODE_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->newmv_mode_cost[i], fc->newmv_cdf[i],
-                               NULL);
-    }
-
-    for (i = 0; i < GLOBALMV_MODE_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->zeromv_mode_cost[i],
-                               fc->zeromv_cdf[i], NULL);
-    }
-
-    for (i = 0; i < REFMV_MODE_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->refmv_mode_cost[i], fc->refmv_cdf[i],
-                               NULL);
-    }
-
-    for (i = 0; i < DRL_MODE_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->drl_mode_cost0[i], fc->drl_cdf[i],
-                               NULL);
-    }
-    for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
-      av1_cost_tokens_from_cdf(mode_costs->inter_compound_mode_cost[i],
-                               fc->inter_compound_mode_cdf[i], NULL);
-    for (i = 0; i < BLOCK_SIZES_ALL; ++i)
-      av1_cost_tokens_from_cdf(mode_costs->compound_type_cost[i],
-                               fc->compound_type_cdf[i], NULL);
-    for (i = 0; i < BLOCK_SIZES_ALL; ++i) {
-      if (av1_is_wedge_used(i)) {
-        av1_cost_tokens_from_cdf(mode_costs->wedge_idx_cost[i],
-                                 fc->wedge_idx_cdf[i], NULL);
-      }
-    }
-    for (i = 0; i < BLOCK_SIZE_GROUPS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->interintra_cost[i],
-                               fc->interintra_cdf[i], NULL);
-      av1_cost_tokens_from_cdf(mode_costs->interintra_mode_cost[i],
-                               fc->interintra_mode_cdf[i], NULL);
-    }
-    for (i = 0; i < BLOCK_SIZES_ALL; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->wedge_interintra_cost[i],
-                               fc->wedge_interintra_cdf[i], NULL);
-    }
-    for (i = BLOCK_8X8; i < BLOCK_SIZES_ALL; i++) {
-      av1_cost_tokens_from_cdf(mode_costs->motion_mode_cost[i],
-                               fc->motion_mode_cdf[i], NULL);
-    }
-    for (i = BLOCK_8X8; i < BLOCK_SIZES_ALL; i++) {
-      av1_cost_tokens_from_cdf(mode_costs->motion_mode_cost1[i],
-                               fc->obmc_cdf[i], NULL);
-    }
-    for (i = 0; i < COMP_INDEX_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->comp_idx_cost[i],
-                               fc->compound_index_cdf[i], NULL);
-    }
-    for (i = 0; i < COMP_GROUP_IDX_CONTEXTS; ++i) {
-      av1_cost_tokens_from_cdf(mode_costs->comp_group_idx_cost[i],
-                               fc->comp_group_idx_cdf[i], NULL);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->comp_inter_cost[0], 2,
+                                     fc->comp_inter_cdf[0], CDF_SIZE(2),
+                                     COMP_INTER_CONTEXTS);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->single_ref_cost[0][0], 2,
+                                     fc->single_ref_cdf[0][0], CDF_SIZE(2),
+                                     REF_CONTEXTS * (SINGLE_REFS - 1));
+    av1_cost_tokens_from_cdf_2_batch(
+        mode_costs->comp_ref_type_cost[0], CDF_SIZE(COMP_REFERENCE_TYPES),
+        fc->comp_ref_type_cdf[0], CDF_SIZE(2), COMP_REF_TYPE_CONTEXTS);
+    av1_cost_tokens_from_cdf_2_batch(
+        mode_costs->uni_comp_ref_cost[0][0], CDF_SIZE(2),
+        fc->uni_comp_ref_cdf[0][0], CDF_SIZE(2),
+        UNI_COMP_REF_CONTEXTS * (UNIDIR_COMP_REFS - 1));
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->comp_ref_cost[0][0], 2,
+                                     fc->comp_ref_cdf[0][0], CDF_SIZE(2),
+                                     REF_CONTEXTS * (FWD_REFS - 1));
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->comp_bwdref_cost[0][0], 2,
+                                     fc->comp_bwdref_cdf[0][0], CDF_SIZE(2),
+                                     REF_CONTEXTS * (BWD_REFS - 1));
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->intra_inter_cost[0], 2,
+                                     fc->intra_inter_cdf[0], CDF_SIZE(2),
+                                     INTRA_INTER_CONTEXTS);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->newmv_mode_cost[0], 2,
+                                     fc->newmv_cdf[0], CDF_SIZE(2),
+                                     NEWMV_MODE_CONTEXTS);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->zeromv_mode_cost[0], 2,
+                                     fc->zeromv_cdf[0], CDF_SIZE(2),
+                                     GLOBALMV_MODE_CONTEXTS);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->refmv_mode_cost[0], 2,
+                                     fc->refmv_cdf[0], CDF_SIZE(2),
+                                     REFMV_MODE_CONTEXTS);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->drl_mode_cost0[0], 2,
+                                     fc->drl_cdf[0], CDF_SIZE(2),
+                                     DRL_MODE_CONTEXTS);
+    av1_cost_tokens_from_cdf_batch(
+        mode_costs->inter_compound_mode_cost[0], INTER_COMPOUND_MODES,
+        fc->inter_compound_mode_cdf[0], CDF_SIZE(INTER_COMPOUND_MODES),
+        INTER_COMPOUND_MODES, INTER_MODE_CONTEXTS);
+    static_assert(MASKED_COMPOUND_TYPES == 2, "");
+    av1_cost_tokens_from_cdf_2_batch(
+        mode_costs->compound_type_cost[0], MASKED_COMPOUND_TYPES,
+        fc->compound_type_cdf[0], CDF_SIZE(MASKED_COMPOUND_TYPES),
+        BLOCK_SIZES_ALL);
+    // Wedge-used block sizes form two contiguous ranges in BLOCK_SIZE:
+    // [BLOCK_8X8, BLOCK_32X32] and [BLOCK_8X32, BLOCK_32X8].
+    static_assert(BLOCK_8X8 == 3 && BLOCK_32X32 == 9, "");
+    static_assert(BLOCK_8X32 == 18 && BLOCK_32X8 == 19, "");
+    static_assert(sizeof(mode_costs->wedge_idx_cost[0]) == sizeof(int[16]), "");
+    static_assert(
+        sizeof(fc->wedge_idx_cdf[0]) == sizeof(aom_cdf_prob[CDF_SIZE(16)]), "");
+#ifndef NDEBUG
+    for (int bsize = 0; bsize < BLOCK_SIZES_ALL; ++bsize) {
+      const int in_ranges = (bsize >= BLOCK_8X8 && bsize <= BLOCK_32X32) ||
+                            (bsize >= BLOCK_8X32 && bsize <= BLOCK_32X8);
+      assert(!!av1_is_wedge_used((BLOCK_SIZE)bsize) == in_ranges);
     }
+#endif  // !NDEBUG
+    av1_cost_tokens_from_cdf_batch(mode_costs->wedge_idx_cost[BLOCK_8X8], 16,
+                                   fc->wedge_idx_cdf[BLOCK_8X8], CDF_SIZE(16),
+                                   16, BLOCK_32X32 - BLOCK_8X8 + 1);
+    av1_cost_tokens_from_cdf_batch(mode_costs->wedge_idx_cost[BLOCK_8X32], 16,
+                                   fc->wedge_idx_cdf[BLOCK_8X32], CDF_SIZE(16),
+                                   16, BLOCK_32X8 - BLOCK_8X32 + 1);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->interintra_cost[0], 2,
+                                     fc->interintra_cdf[0], CDF_SIZE(2),
+                                     BLOCK_SIZE_GROUPS);
+    static_assert(INTERINTRA_MODES == 4, "");
+    av1_cost_tokens_from_cdf_4_batch(
+        mode_costs->interintra_mode_cost[0], INTERINTRA_MODES,
+        fc->interintra_mode_cdf[0], CDF_SIZE(INTERINTRA_MODES),
+        BLOCK_SIZE_GROUPS);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->wedge_interintra_cost[0], 2,
+                                     fc->wedge_interintra_cdf[0], CDF_SIZE(2),
+                                     BLOCK_SIZES_ALL);
+    av1_cost_tokens_from_cdf_batch(mode_costs->motion_mode_cost[BLOCK_8X8],
+                                   MOTION_MODES, fc->motion_mode_cdf[BLOCK_8X8],
+                                   CDF_SIZE(MOTION_MODES), MOTION_MODES,
+                                   BLOCK_SIZES_ALL - BLOCK_8X8);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->motion_mode_cost1[BLOCK_8X8],
+                                     2, fc->obmc_cdf[BLOCK_8X8], CDF_SIZE(2),
+                                     BLOCK_SIZES_ALL - BLOCK_8X8);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->comp_idx_cost[0], 2,
+                                     fc->compound_index_cdf[0], CDF_SIZE(2),
+                                     COMP_INDEX_CONTEXTS);
+    av1_cost_tokens_from_cdf_2_batch(mode_costs->comp_group_idx_cost[0], 2,
+                                     fc->comp_group_idx_cdf[0], CDF_SIZE(2),
+                                     COMP_GROUP_IDX_CONTEXTS);
   }
 }

@@ -623,60 +644,54 @@ static void set_block_thresholds(const AV1_COMMON *cm, RD_OPT *rd,
   }
 }

-// In real-time mode, fill the coeff cost tables with the batched/SIMD
-// specializations; otherwise use the generic scalar path.
 void av1_fill_coeff_costs(CoeffCosts *coeff_costs, FRAME_CONTEXT *fc,
-                          const int num_planes, int is_realtime) {
+                          const int num_planes) {
+  static_assert(BR_CDF_SIZE == 4, "");
   const int nplanes = AOMMIN(num_planes, PLANE_TYPES);
-  for (int eob_multi_size = 0; eob_multi_size < 7; ++eob_multi_size) {
-    for (int plane = 0; plane < nplanes; ++plane) {
-      LV_MAP_EOB_COST *pcost = &coeff_costs->eob_costs[eob_multi_size][plane];
-
-      for (int ctx = 0; ctx < 2; ++ctx) {
-        aom_cdf_prob *pcdf;
-        switch (eob_multi_size) {
-          case 0: pcdf = fc->eob_flag_cdf16[plane][ctx]; break;
-          case 1: pcdf = fc->eob_flag_cdf32[plane][ctx]; break;
-          case 2: pcdf = fc->eob_flag_cdf64[plane][ctx]; break;
-          case 3: pcdf = fc->eob_flag_cdf128[plane][ctx]; break;
-          case 4: pcdf = fc->eob_flag_cdf256[plane][ctx]; break;
-          case 5: pcdf = fc->eob_flag_cdf512[plane][ctx]; break;
-          case 6:
-          default: pcdf = fc->eob_flag_cdf1024[plane][ctx]; break;
-        }
-        av1_cost_tokens_from_cdf(pcost->eob_cost[ctx], pcdf, NULL);
-      }
-    }
+  for (int plane = 0; plane < nplanes; ++plane) {
+    av1_cost_tokens_from_cdf_batch(coeff_costs->eob_costs[0][plane].eob_cost[0],
+                                   16, fc->eob_flag_cdf16[plane][0],
+                                   CDF_SIZE(5), 5, 2);
+    av1_cost_tokens_from_cdf_batch(coeff_costs->eob_costs[1][plane].eob_cost[0],
+                                   16, fc->eob_flag_cdf32[plane][0],
+                                   CDF_SIZE(6), 6, 2);
+    av1_cost_tokens_from_cdf_batch(coeff_costs->eob_costs[2][plane].eob_cost[0],
+                                   16, fc->eob_flag_cdf64[plane][0],
+                                   CDF_SIZE(7), 7, 2);
+    av1_cost_tokens_from_cdf_batch(coeff_costs->eob_costs[3][plane].eob_cost[0],
+                                   16, fc->eob_flag_cdf128[plane][0],
+                                   CDF_SIZE(8), 8, 2);
+    av1_cost_tokens_from_cdf_batch(coeff_costs->eob_costs[4][plane].eob_cost[0],
+                                   16, fc->eob_flag_cdf256[plane][0],
+                                   CDF_SIZE(9), 9, 2);
+    av1_cost_tokens_from_cdf_batch(coeff_costs->eob_costs[5][plane].eob_cost[0],
+                                   16, fc->eob_flag_cdf512[plane][0],
+                                   CDF_SIZE(10), 10, 2);
+    av1_cost_tokens_from_cdf_batch(coeff_costs->eob_costs[6][plane].eob_cost[0],
+                                   16, fc->eob_flag_cdf1024[plane][0],
+                                   CDF_SIZE(11), 11, 2);
   }
   for (int tx_size = 0; tx_size < TX_SIZES; ++tx_size) {
     for (int plane = 0; plane < nplanes; ++plane) {
       LV_MAP_COEFF_COST *pcost = &coeff_costs->coeff_costs[tx_size][plane];

-      if (is_realtime) {
+      if (plane == 0) {
         av1_cost_tokens_from_cdf_2_batch(pcost->txb_skip_cost[0], 2,
                                          fc->txb_skip_cdf[tx_size][0],
                                          CDF_SIZE(2), TXB_SKIP_CONTEXTS);
       } else {
-        for (int ctx = 0; ctx < TXB_SKIP_CONTEXTS; ++ctx)
-          av1_cost_tokens_from_cdf(pcost->txb_skip_cost[ctx],
-                                   fc->txb_skip_cdf[tx_size][ctx], NULL);
+        memcpy(pcost->txb_skip_cost,
+               coeff_costs->coeff_costs[tx_size][0].txb_skip_cost,
+               sizeof(pcost->txb_skip_cost));
       }

-      for (int ctx = 0; ctx < SIG_COEF_CONTEXTS_EOB; ++ctx)
-        av1_cost_tokens_from_cdf(pcost->base_eob_cost[ctx],
-                                 fc->coeff_base_eob_cdf[tx_size][plane][ctx],
-                                 NULL);
+      av1_cost_tokens_from_cdf_batch(pcost->base_eob_cost[0], 4,
+                                     fc->coeff_base_eob_cdf[tx_size][plane][0],
+                                     CDF_SIZE(3), 3, SIG_COEF_CONTEXTS_EOB);
       // base_cost[ctx] is int[8]; only [0..3] are filled here (stride 8).
-      if (is_realtime) {
-        av1_cost_tokens_from_cdf_4_batch(pcost->base_cost[0], 8,
-                                         fc->coeff_base_cdf[tx_size][plane][0],
-                                         CDF_SIZE(4), SIG_COEF_CONTEXTS);
-      } else {
-        for (int ctx = 0; ctx < SIG_COEF_CONTEXTS; ++ctx)
-          av1_cost_tokens_from_cdf(pcost->base_cost[ctx],
-                                   fc->coeff_base_cdf[tx_size][plane][ctx],
-                                   NULL);
-      }
+      av1_cost_tokens_from_cdf_4_batch(pcost->base_cost[0], 8,
+                                       fc->coeff_base_cdf[tx_size][plane][0],
+                                       CDF_SIZE(4), SIG_COEF_CONTEXTS);

       for (int ctx = 0; ctx < SIG_COEF_CONTEXTS; ++ctx) {
         pcost->base_cost[ctx][4] = pcost->base_cost[ctx][0];
@@ -688,21 +703,14 @@ void av1_fill_coeff_costs(CoeffCosts *coeff_costs, FRAME_CONTEXT *fc,
             pcost->base_cost[ctx][3] + av1_cost_literal(1);
       }

-      if (is_realtime) {
-        av1_cost_tokens_from_cdf_2_batch(pcost->eob_extra_cost[0], 2,
-                                         fc->eob_extra_cdf[tx_size][plane][0],
-                                         CDF_SIZE(2), EOB_COEF_CONTEXTS);
-      } else {
-        for (int ctx = 0; ctx < EOB_COEF_CONTEXTS; ++ctx)
-          av1_cost_tokens_from_cdf(pcost->eob_extra_cost[ctx],
-                                   fc->eob_extra_cdf[tx_size][plane][ctx],
-                                   NULL);
-      }
+      av1_cost_tokens_from_cdf_2_batch(pcost->eob_extra_cost[0], 2,
+                                       fc->eob_extra_cdf[tx_size][plane][0],
+                                       CDF_SIZE(2), EOB_COEF_CONTEXTS);

       if (tx_size == TX_4X4) {
-        for (int ctx = 0; ctx < DC_SIGN_CONTEXTS; ++ctx)
-          av1_cost_tokens_from_cdf(pcost->dc_sign_cost[ctx],
-                                   fc->dc_sign_cdf[plane][ctx], NULL);
+        av1_cost_tokens_from_cdf_2_batch(pcost->dc_sign_cost[0], 2,
+                                         fc->dc_sign_cdf[plane][0], CDF_SIZE(2),
+                                         DC_SIGN_CONTEXTS);
       } else {
         memcpy(pcost->dc_sign_cost,
                coeff_costs->coeff_costs[TX_4X4][plane].dc_sign_cost,
@@ -711,15 +719,9 @@ void av1_fill_coeff_costs(CoeffCosts *coeff_costs, FRAME_CONTEXT *fc,

       if (tx_size <= TX_32X32) {
         int br_rate_all[LEVEL_CONTEXTS][BR_CDF_SIZE];
-        if (is_realtime) {
-          av1_cost_tokens_from_cdf_4_batch(
-              br_rate_all[0], BR_CDF_SIZE, fc->coeff_br_cdf[tx_size][plane][0],
-              CDF_SIZE(BR_CDF_SIZE), LEVEL_CONTEXTS);
-        } else {
-          for (int ctx = 0; ctx < LEVEL_CONTEXTS; ++ctx)
-            av1_cost_tokens_from_cdf(
-                br_rate_all[ctx], fc->coeff_br_cdf[tx_size][plane][ctx], NULL);
-        }
+        av1_cost_tokens_from_cdf_4_batch(br_rate_all[0], BR_CDF_SIZE,
+                                         fc->coeff_br_cdf[tx_size][plane][0],
+                                         CDF_SIZE(BR_CDF_SIZE), LEVEL_CONTEXTS);
         for (int ctx = 0; ctx < LEVEL_CONTEXTS; ++ctx) {
           const int *br_rate = br_rate_all[ctx];
           int prev_cost = 0;
@@ -899,8 +901,7 @@ void av1_initialize_rd_consts(AV1_COMP *cpi) {
   // Frame level coefficient cost update
   if (is_frame_level_cost_upd_freq_set(cm, inter_sf->coeff_cost_upd_level,
                                        use_nonrd_pick_mode, frames_since_key))
-    av1_fill_coeff_costs(&x->coeff_costs, cm->fc, av1_num_planes(cm),
-                         cpi->oxcf.mode == REALTIME);
+    av1_fill_coeff_costs(&x->coeff_costs, cm->fc, av1_num_planes(cm));

   // Frame level mode cost update
   if (should_force_mode_cost_update(cpi) ||
diff --git a/av1/encoder/rd.h b/av1/encoder/rd.h
index 7326cdcd34..f0b667f523 100644
--- a/av1/encoder/rd.h
+++ b/av1/encoder/rd.h
@@ -424,7 +424,7 @@ void av1_fill_lr_rates(ModeCosts *mode_costs, FRAME_CONTEXT *fc);
 #endif

 void av1_fill_coeff_costs(CoeffCosts *coeff_costs, FRAME_CONTEXT *fc,
-                          const int num_planes, int is_realtime);
+                          const int num_planes);

 void av1_fill_mv_costs(const nmv_context *nmvc, int integer_mv, int usehp,
                        MvCosts *mv_costs);
diff --git a/av1/encoder/x86/cost_avx2.c b/av1/encoder/x86/cost_avx2.c
index bcea1be6ea..6cd430005d 100644
--- a/av1/encoder/x86/cost_avx2.c
+++ b/av1/encoder/x86/cost_avx2.c
@@ -9,39 +9,40 @@
  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
  */

+#include <assert.h>
 #include <immintrin.h>
+#include <string.h>

 #include "config/aom_config.h"
 #include "config/av1_rtcd.h"

 #include "av1/encoder/cost.h"

-// Below this many leftover contexts the scalar tail is cheaper than one more
-// 8-context SIMD group.
+// Below this many leftover contexts the vectorized < 8 tail is cheaper than
+// one more 8-context gather+transpose SIMD group.
 #define MIN_OVERLAP_TAIL 3

 // Vector form of av1_cost_symbol_clamped for 8 lanes. Bit-exact with the
 // scalar path:
 //   p15c  = clamp(p15, EC_MIN_PROB, CDF_PROB_TOP - 1)
 //   shift = (CDF_PROB_BITS - 1) - floor(log2(p15c))   // via float exponent
-//   idx   = min(((p15c << shift) + 64) >> 7, 255) - 128
+//   idx   = min(((p15c << shift) - 16320) >> 7, 127)  // via float mantissa
 //   cost  = av1_prob_cost[idx] + shift * 512
 // The scalar path can reach idx 128, which duplicates idx 127, so clamping to
 // 127 gives the same cost and keeps the 32-bit gather below within the table.
 static inline __m256i cost_symbol_x8(__m256i p15) {
   p15 = _mm256_max_epi32(p15, _mm256_set1_epi32(EC_MIN_PROB));
   p15 = _mm256_min_epi32(p15, _mm256_set1_epi32(CDF_PROB_TOP - 1));
-  // floor(log2(p15)) = (biased exponent) - 127; exact since p15 < 2^24.
-  const __m256i bits = _mm256_castps_si256(_mm256_cvtepi32_ps(p15));
-  const __m256i exp =
-      _mm256_and_si256(_mm256_srli_epi32(bits, 23), _mm256_set1_epi32(0xFF));
+  // Since 0 < p15 < 2^15, float conversion is exact with sign bit 0, biased
+  // exponent 127 + floor(log2(p15)), and mantissa ((p15 << shift) - 16384)<<9.
+  const __m256i u = _mm256_castps_si256(_mm256_cvtepi32_ps(p15));
   // shift = (CDF_PROB_BITS - 1) - (exp - 127) = 141 - exp.
-  const __m256i shift = _mm256_sub_epi32(_mm256_set1_epi32(141), exp);
-  const __m256i norm = _mm256_sllv_epi32(p15, shift);
-  __m256i prob =
-      _mm256_srli_epi32(_mm256_add_epi32(norm, _mm256_set1_epi32(64)), 7);
-  prob = _mm256_min_epi32(prob, _mm256_set1_epi32(255));
-  const __m256i idx = _mm256_sub_epi32(prob, _mm256_set1_epi32(128));
+  const __m256i shift =
+      _mm256_sub_epi32(_mm256_set1_epi32(141), _mm256_srli_epi32(u, 23));
+  const __m256i mant = _mm256_and_si256(u, _mm256_set1_epi32(0x7FFFFF));
+  __m256i idx =
+      _mm256_srli_epi32(_mm256_add_epi32(mant, _mm256_set1_epi32(32768)), 16);
+  idx = _mm256_min_epi32(idx, _mm256_set1_epi32(127));
   // 16-bit table read via 32-bit gather; mask off the adjacent entry (idx + 1
   // is at most 128, which is inside the 129-entry table).
   __m256i tbl = _mm256_i32gather_epi32((const int *)av1_prob_cost, idx, 2);
@@ -97,26 +98,181 @@ static inline void cost_tokens_cdf4_x8(int *costs, int costs_stride,
                    _mm256_extracti128_si256(q3, 1));
 }

+// 4-lane form of cost_symbol_x8 for odd/short tails.
+static inline __m128i cost_symbol_x4(__m128i p15) {
+  p15 = _mm_max_epi32(p15, _mm_set1_epi32(EC_MIN_PROB));
+  p15 = _mm_min_epi32(p15, _mm_set1_epi32(CDF_PROB_TOP - 1));
+  const __m128i u = _mm_castps_si128(_mm_cvtepi32_ps(p15));
+  const __m128i shift =
+      _mm_sub_epi32(_mm_set1_epi32(141), _mm_srli_epi32(u, 23));
+  const __m128i mant = _mm_and_si128(u, _mm_set1_epi32(0x7FFFFF));
+  __m128i idx = _mm_srli_epi32(_mm_add_epi32(mant, _mm_set1_epi32(32768)), 16);
+  idx = _mm_min_epi32(idx, _mm_set1_epi32(127));
+  __m128i tbl = _mm_i32gather_epi32((const int *)av1_prob_cost, idx, 2);
+  tbl = _mm_and_si128(tbl, _mm_set1_epi32(0xFFFF));
+  const __m128i lit = _mm_slli_epi32(shift, AV1_PROB_COST_SHIFT);
+  return _mm_add_epi32(tbl, lit);
+}
+
+static inline __m128i load_u16_3(const uint16_t *p) {
+  int32_t lo32;
+  memcpy(&lo32, p, sizeof(lo32));
+  return _mm_insert_epi16(_mm_cvtsi32_si128(lo32), (int16_t)p[2], 2);
+}
+
+// Computes symbol costs for one 3- or 4-symbol CDF packed in low 64 bits.
+static inline __m128i cost_1_cdf4_from_vec(__m128i c16) {
+  const __m128i vc = _mm_cvtepu16_epi32(c16);
+  const __m128i prev = _mm_blend_epi32(_mm_slli_si128(vc, 4),
+                                       _mm_set1_epi32(CDF_PROB_TOP), 0x01);
+  return cost_symbol_x4(_mm_sub_epi32(prev, vc));
+}
+
+// Computes symbol costs for two 4-symbol CDFs (reads 8 bytes from each).
+static inline __m256i cost_2_cdf4_avx2(const uint16_t *cdf0,
+                                       const uint16_t *cdf1) {
+  const __m128i c01 =
+      _mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i *)cdf0),
+                         _mm_loadl_epi64((const __m128i *)cdf1));
+  const __m256i vc = _mm256_cvtepu16_epi32(c01);
+  const __m256i prev = _mm256_blend_epi32(
+      _mm256_slli_si256(vc, 4), _mm256_set1_epi32(CDF_PROB_TOP), 0x11);
+  return cost_symbol_x8(_mm256_sub_epi32(prev, vc));
+}
+
+// Computes symbol costs for two 3-symbol CDFs (strictly reads 6 bytes each).
+static inline __m256i cost_2_cdf3_avx2(const uint16_t *cdf0,
+                                       const uint16_t *cdf1) {
+  const __m128i c01 = _mm_unpacklo_epi64(load_u16_3(cdf0), load_u16_3(cdf1));
+  const __m256i vc = _mm256_cvtepu16_epi32(c01);
+  const __m256i prev = _mm256_blend_epi32(
+      _mm256_slli_si256(vc, 4), _mm256_set1_epi32(CDF_PROB_TOP), 0x11);
+  return cost_symbol_x8(_mm256_sub_epi32(prev, vc));
+}
+
+// Computes up to 8 symbol costs from 8 packed uint16_t CDF entries.
+static inline __m256i cost_1_cdf8_from_vec(__m128i c16) {
+  const __m256i vc = _mm256_cvtepu16_epi32(c16);
+  const __m256i vprev =
+      _mm256_blend_epi32(_mm256_cvtepu16_epi32(_mm_slli_si128(c16, 2)),
+                         _mm256_set1_epi32(CDF_PROB_TOP), 0x01);
+  return cost_symbol_x8(_mm256_sub_epi32(vprev, vc));
+}
+
+static inline __m128i load_u16_5(const uint16_t *p) {
+  const __m128i v = _mm_loadl_epi64((const __m128i *)p);
+  return _mm_insert_epi16(v, (int16_t)p[4], 4);
+}
+
+static inline __m128i load_u16_6(const uint16_t *p) {
+  int32_t hi32;
+  memcpy(&hi32, p + 4, sizeof(hi32));
+  const __m128i v = _mm_loadl_epi64((const __m128i *)p);
+  return _mm_insert_epi32(v, hi32, 2);
+}
+
+static inline __m128i load_u16_7(const uint16_t *p) {
+  const __m128i v = load_u16_6(p);
+  return _mm_insert_epi16(v, (int16_t)p[6], 6);
+}
+
+static inline void store_i32_3(int *dst, __m128i v) {
+  _mm_storel_epi64((__m128i *)dst, v);
+  dst[2] = _mm_extract_epi32(v, 2);
+}
+
+static inline void store_i32_5(int *dst, __m256i v) {
+  _mm_storeu_si128((__m128i *)dst, _mm256_castsi256_si128(v));
+  dst[4] = _mm_cvtsi128_si32(_mm256_extracti128_si256(v, 1));
+}
+
+static inline void store_i32_6(int *dst, __m256i v) {
+  _mm_storeu_si128((__m128i *)dst, _mm256_castsi256_si128(v));
+  _mm_storel_epi64((__m128i *)(dst + 4), _mm256_extracti128_si256(v, 1));
+}
+
+static inline void store_i32_7(int *dst, __m256i v) {
+  const __m128i hi = _mm256_extracti128_si256(v, 1);
+  _mm_storeu_si128((__m128i *)dst, _mm256_castsi256_si128(v));
+  _mm_storel_epi64((__m128i *)(dst + 4), hi);
+  dst[6] = _mm_extract_epi32(hi, 2);
+}
+
+// Computes symbols [nsyms - 8 .. nsyms - 1] for 9 <= nsyms <= 16.
+static inline __m256i cost_cdf_tail8_avx2(const uint16_t *cdf, int nsyms) {
+  assert(nsyms >= 9 && nsyms <= 16);
+  const __m256i vprev = _mm256_cvtepu16_epi32(
+      _mm_loadu_si128((const __m128i *)(cdf + nsyms - 9)));
+  const __m256i vc = _mm256_cvtepu16_epi32(
+      _mm_loadu_si128((const __m128i *)(cdf + nsyms - 8)));
+  return cost_symbol_x8(_mm256_sub_epi32(vprev, vc));
+}
+
 void av1_cost_tokens_from_cdf_4_batch_avx2(int *costs, int costs_stride,
                                            const uint16_t *cdf, int cdf_stride,
                                            int n) {
-  const int s = cdf_stride;
-  // Per-lane element offset of the 8 CDFs processed together.
-  const __m256i lane =
-      _mm256_setr_epi32(0, s, 2 * s, 3 * s, 4 * s, 5 * s, 6 * s, 7 * s);
-
+  assert(n >= 0);
+  if (n == 0) return;
+  assert(costs != NULL && cdf != NULL);
+  assert(costs_stride >= 4);
+  assert(n <= 1 || cdf_stride >= 4);
   int c = 0;
-  for (; c + 8 <= n; c += 8)
-    cost_tokens_cdf4_x8(costs + c * costs_stride, costs_stride, cdf + c * s,
-                        lane);
-  if (c > 0 && n - c >= MIN_OVERLAP_TAIL) {
-    // Redoes the last 8 contexts; the overlapping ones get identical values.
-    cost_tokens_cdf4_x8(costs + (n - 8) * costs_stride, costs_stride,
-                        cdf + (n - 8) * s, lane);
-    return;
+  if (n >= 8) {
+    const int s = cdf_stride;
+    // Per-lane element offset of the 8 CDFs processed together.
+    const __m256i lane =
+        _mm256_setr_epi32(0, s, 2 * s, 3 * s, 4 * s, 5 * s, 6 * s, 7 * s);
+    for (; c + 8 <= n; c += 8)
+      cost_tokens_cdf4_x8(costs + c * costs_stride, costs_stride, cdf + c * s,
+                          lane);
+    if (n - c >= MIN_OVERLAP_TAIL) {
+      // Redoes the last 8 contexts; the overlapping ones get identical values.
+      cost_tokens_cdf4_x8(costs + (n - 8) * costs_stride, costs_stride,
+                          cdf + (n - 8) * s, lane);
+      return;
+    }
   }
-  for (; c < n; ++c)
-    av1_cost_tokens_from_cdf_4(costs + c * costs_stride, cdf + c * cdf_stride);
+  if (costs_stride == 4) {
+    for (; c + 2 <= n; c += 2) {
+      const uint16_t *const p = cdf + c * cdf_stride;
+      const __m256i res = cost_2_cdf4_avx2(p, p + cdf_stride);
+      _mm256_storeu_si256((__m256i *)(costs + c * 4), res);
+    }
+  } else {
+    for (; c + 2 <= n; c += 2) {
+      const uint16_t *const p = cdf + c * cdf_stride;
+      const __m256i res = cost_2_cdf4_avx2(p, p + cdf_stride);
+      int *const o = costs + c * costs_stride;
+      _mm_storeu_si128((__m128i *)o, _mm256_castsi256_si128(res));
+      _mm_storeu_si128((__m128i *)(o + costs_stride),
+                       _mm256_extracti128_si256(res, 1));
+    }
+  }
+  if (c < n) {
+    const uint16_t *const p = cdf + c * cdf_stride;
+    const __m128i res =
+        cost_1_cdf4_from_vec(_mm_loadl_epi64((const __m128i *)p));
+    _mm_storeu_si128((__m128i *)(costs + c * costs_stride), res);
+  }
+}
+
+// Computes symbol costs for four 2-symbol CDFs (reads p[0] at cdf_stride).
+// Valid 2-symbol AV1 CDFs end with p[1] == AOM_ICDF(CDF_PROB_TOP) == 0, so
+// the second symbol probability equals p[0] directly.
+static inline __m256i cost_4_cdf2_avx2(const uint16_t *p, int cdf_stride) {
+  assert(p[1] == 0 && p[cdf_stride + 1] == 0 && p[2 * cdf_stride + 1] == 0 &&
+         p[3 * cdf_stride + 1] == 0);
+  const uint32_t pair0 = (uint32_t)p[0] | ((uint32_t)p[cdf_stride] << 16);
+  const uint32_t pair1 =
+      (uint32_t)p[2 * cdf_stride] | ((uint32_t)p[3 * cdf_stride] << 16);
+  const __m128i c0 = _mm_cvtepu16_epi32(
+      _mm_insert_epi32(_mm_cvtsi32_si128((int)pair0), (int)pair1, 1));
+  const __m128i p0 = _mm_sub_epi32(_mm_set1_epi32(CDF_PROB_TOP), c0);
+  // Pack {p0[0], c0[0], p0[1], c0[1] | p0[2], c0[2], p0[3], c0[3]}.
+  const __m256i v = _mm256_inserti128_si256(
+      _mm256_castsi128_si256(_mm_unpacklo_epi32(p0, c0)),
+      _mm_unpackhi_epi32(p0, c0), 1);
+  return cost_symbol_x8(v);
 }

 // Fills the N=2 costs of 8 CDFs starting at cdf; lane holds their offsets.
@@ -155,21 +311,217 @@ static inline void cost_tokens_cdf2_x8(int *costs, int costs_stride,
 void av1_cost_tokens_from_cdf_2_batch_avx2(int *costs, int costs_stride,
                                            const uint16_t *cdf, int cdf_stride,
                                            int n) {
-  const int s = cdf_stride;
-  // Per-lane element offset of the 8 CDFs processed together.
-  const __m256i lane =
-      _mm256_setr_epi32(0, s, 2 * s, 3 * s, 4 * s, 5 * s, 6 * s, 7 * s);
-
+  assert(n >= 0);
+  if (n == 0) return;
+  assert(costs != NULL && cdf != NULL);
+  assert(costs_stride >= 2);
+  assert(n <= 1 || cdf_stride >= 2);
+#ifndef NDEBUG
+  for (int k = 0; k < n; ++k) assert(cdf[k * cdf_stride + 1] == 0);
+#endif
   int c = 0;
-  for (; c + 8 <= n; c += 8)
-    cost_tokens_cdf2_x8(costs + c * costs_stride, costs_stride, cdf + c * s,
-                        lane);
-  if (c > 0 && n - c >= MIN_OVERLAP_TAIL) {
-    // Redoes the last 8 contexts; the overlapping ones get identical values.
-    cost_tokens_cdf2_x8(costs + (n - 8) * costs_stride, costs_stride,
-                        cdf + (n - 8) * s, lane);
-    return;
+  if (n >= 8) {
+    const int s = cdf_stride;
+    // Per-lane element offset of the 8 CDFs processed together.
+    const __m256i lane =
+        _mm256_setr_epi32(0, s, 2 * s, 3 * s, 4 * s, 5 * s, 6 * s, 7 * s);
+    for (; c + 8 <= n; c += 8)
+      cost_tokens_cdf2_x8(costs + c * costs_stride, costs_stride, cdf + c * s,
+                          lane);
+    if (n - c >= MIN_OVERLAP_TAIL) {
+      // Redoes the last 8 contexts; the overlapping ones get identical values.
+      cost_tokens_cdf2_x8(costs + (n - 8) * costs_stride, costs_stride,
+                          cdf + (n - 8) * s, lane);
+      return;
+    }
   }
-  for (; c < n; ++c)
+  if (c + 4 <= n) {
+    if (costs_stride == 2) {
+      _mm256_storeu_si256((__m256i *)(costs + c * 2),
+                          cost_4_cdf2_avx2(cdf + c * cdf_stride, cdf_stride));
+    } else {
+      const __m256i res = cost_4_cdf2_avx2(cdf + c * cdf_stride, cdf_stride);
+      int *const o = costs + c * costs_stride;
+      const __m128i lo = _mm256_castsi256_si128(res);
+      const __m128i hi = _mm256_extracti128_si256(res, 1);
+      _mm_storel_epi64((__m128i *)(o + 0 * costs_stride), lo);
+      _mm_storel_epi64((__m128i *)(o + 1 * costs_stride),
+                       _mm_unpackhi_epi64(lo, lo));
+      _mm_storel_epi64((__m128i *)(o + 2 * costs_stride), hi);
+      _mm_storel_epi64((__m128i *)(o + 3 * costs_stride),
+                       _mm_unpackhi_epi64(hi, hi));
+    }
+    c += 4;
+  }
+  if (c + 2 <= n) {
+    const uint16_t *const p = cdf + c * cdf_stride;
+    const int c0 = p[0];
+    const int c1 = p[cdf_stride];
+    const __m128i v =
+        _mm_setr_epi32(CDF_PROB_TOP - c0, c0, CDF_PROB_TOP - c1, c1);
+    const __m128i res = cost_symbol_x4(v);
+    int *const o = costs + c * costs_stride;
+    if (costs_stride == 2) {
+      _mm_storeu_si128((__m128i *)o, res);
+    } else {
+      _mm_storel_epi64((__m128i *)o, res);
+      _mm_storel_epi64((__m128i *)(o + costs_stride),
+                       _mm_unpackhi_epi64(res, res));
+    }
+    c += 2;
+  }
+  if (c < n) {
     av1_cost_tokens_from_cdf_2(costs + c * costs_stride, cdf + c * cdf_stride);
+  }
+}
+
+void av1_cost_tokens_from_cdf_batch_avx2(int *costs, int costs_stride,
+                                         const uint16_t *cdf, int cdf_stride,
+                                         int nsyms, int n) {
+  assert(nsyms >= 2);
+  assert(n >= 0);
+  if (n == 0) return;
+  assert(costs != NULL && cdf != NULL);
+  assert(costs_stride >= nsyms);
+  assert(n <= 1 || cdf_stride >= nsyms);
+  switch (nsyms) {
+    case 2:
+      av1_cost_tokens_from_cdf_2_batch_avx2(costs, costs_stride, cdf,
+                                            cdf_stride, n);
+      return;
+    case 3: {
+      int c = 0;
+      for (; c + 2 <= n; c += 2) {
+        const uint16_t *const p = cdf + c * cdf_stride;
+        const __m256i res = cost_2_cdf3_avx2(p, p + cdf_stride);
+        int *const o = costs + c * costs_stride;
+        store_i32_3(o, _mm256_castsi256_si128(res));
+        store_i32_3(o + costs_stride, _mm256_extracti128_si256(res, 1));
+      }
+      if (c < n) {
+        const uint16_t *const p = cdf + c * cdf_stride;
+        store_i32_3(costs + c * costs_stride,
+                    cost_1_cdf4_from_vec(load_u16_3(p)));
+      }
+      return;
+    }
+    case 4:
+      av1_cost_tokens_from_cdf_4_batch_avx2(costs, costs_stride, cdf,
+                                            cdf_stride, n);
+      return;
+    case 5:
+      for (int c = 0; c < n; ++c) {
+        const __m128i c16 = load_u16_5(cdf + c * cdf_stride);
+        store_i32_5(costs + c * costs_stride, cost_1_cdf8_from_vec(c16));
+      }
+      return;
+    case 6:
+      for (int c = 0; c < n; ++c) {
+        const __m128i c16 = load_u16_6(cdf + c * cdf_stride);
+        store_i32_6(costs + c * costs_stride, cost_1_cdf8_from_vec(c16));
+      }
+      return;
+    case 7:
+      for (int c = 0; c < n; ++c) {
+        const __m128i c16 = load_u16_7(cdf + c * cdf_stride);
+        store_i32_7(costs + c * costs_stride, cost_1_cdf8_from_vec(c16));
+      }
+      return;
+    case 8:
+      for (int c = 0; c < n; ++c) {
+        const __m128i c16 =
+            _mm_loadu_si128((const __m128i *)(cdf + c * cdf_stride));
+        _mm256_storeu_si256((__m256i *)(costs + c * costs_stride),
+                            cost_1_cdf8_from_vec(c16));
+      }
+      return;
+    default:
+      if (nsyms >= 9 && nsyms <= 16) {
+        for (int c = 0; c < n; ++c) {
+          const uint16_t *const p = cdf + c * cdf_stride;
+          int *const o = costs + c * costs_stride;
+          const __m128i c16 = _mm_loadu_si128((const __m128i *)p);
+          _mm256_storeu_si256((__m256i *)o, cost_1_cdf8_from_vec(c16));
+          _mm256_storeu_si256((__m256i *)(o + nsyms - 8),
+                              cost_cdf_tail8_avx2(p, nsyms));
+        }
+        return;
+      }
+      av1_cost_tokens_from_cdf_batch_c(costs, costs_stride, cdf, cdf_stride,
+                                       nsyms, n);
+      return;
+  }
+}
+
+void av1_cost_tokens_from_cdf_inv_batch_avx2(int *costs, int costs_stride,
+                                             const uint16_t *cdf,
+                                             int cdf_stride, const int *inv_map,
+                                             int nsyms, int n) {
+  assert(nsyms >= 2);
+  assert(n >= 0);
+  if (n == 0) return;
+  assert(costs != NULL && cdf != NULL && inv_map != NULL);
+  assert(costs_stride >= nsyms);
+  assert(n <= 1 || cdf_stride >= nsyms);
+  if (nsyms < 5 || nsyms > 16) {
+    av1_cost_tokens_from_cdf_inv_batch_c(costs, costs_stride, cdf, cdf_stride,
+                                         inv_map, nsyms, n);
+    return;
+  }
+  int map[16];
+  for (int i = 0; i < nsyms; ++i) {
+    assert(inv_map[i] >= 0 && inv_map[i] < costs_stride);
+    map[i] = inv_map[i];
+  }
+  int tmp[16];
+  switch (nsyms) {
+    case 5:
+      for (int c = 0; c < n; ++c) {
+        const __m128i c16 = load_u16_5(cdf + c * cdf_stride);
+        _mm256_storeu_si256((__m256i *)tmp, cost_1_cdf8_from_vec(c16));
+        int *const o = costs + c * costs_stride;
+        for (int i = 0; i < 5; ++i) o[map[i]] = tmp[i];
+      }
+      return;
+    case 6:
+      for (int c = 0; c < n; ++c) {
+        const __m128i c16 = load_u16_6(cdf + c * cdf_stride);
+        _mm256_storeu_si256((__m256i *)tmp, cost_1_cdf8_from_vec(c16));
+        int *const o = costs + c * costs_stride;
+        for (int i = 0; i < 6; ++i) o[map[i]] = tmp[i];
+      }
+      return;
+    case 7:
+      for (int c = 0; c < n; ++c) {
+        const __m128i c16 = load_u16_7(cdf + c * cdf_stride);
+        _mm256_storeu_si256((__m256i *)tmp, cost_1_cdf8_from_vec(c16));
+        int *const o = costs + c * costs_stride;
+        for (int i = 0; i < 7; ++i) o[map[i]] = tmp[i];
+      }
+      return;
+    case 8:
+      for (int c = 0; c < n; ++c) {
+        const __m128i c16 =
+            _mm_loadu_si128((const __m128i *)(cdf + c * cdf_stride));
+        _mm256_storeu_si256((__m256i *)tmp, cost_1_cdf8_from_vec(c16));
+        int *const o = costs + c * costs_stride;
+        for (int i = 0; i < 8; ++i) o[map[i]] = tmp[i];
+      }
+      return;
+    default: {
+      assert(nsyms >= 9 && nsyms <= 16);
+      const int tail_off = 16 - nsyms;
+      for (int c = 0; c < n; ++c) {
+        const uint16_t *const p = cdf + c * cdf_stride;
+        const __m128i c16 = _mm_loadu_si128((const __m128i *)p);
+        _mm256_storeu_si256((__m256i *)tmp, cost_1_cdf8_from_vec(c16));
+        _mm256_storeu_si256((__m256i *)(tmp + 8),
+                            cost_cdf_tail8_avx2(p, nsyms));
+        int *const o = costs + c * costs_stride;
+        for (int i = 0; i < 8; ++i) o[map[i]] = tmp[i];
+        for (int i = 8; i < nsyms; ++i) o[map[i]] = tmp[tail_off + i];
+      }
+      return;
+    }
+  }
 }
diff --git a/test/cost_test.cc b/test/cost_test.cc
index e865fdfb12..a0b014db01 100644
--- a/test/cost_test.cc
+++ b/test/cost_test.cc
@@ -10,6 +10,10 @@
  */

 #include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <memory>
 #include <tuple>
 #include <vector>

@@ -18,8 +22,15 @@

 #include "aom_dsp/prob.h"
 #include "aom_ports/aom_timer.h"
+#include "av1/common/av1_common_int.h"
+#include "av1/common/blockd.h"
 #include "av1/common/entropy.h"
+#include "av1/common/entropymode.h"
+#include "av1/common/reconinter.h"
+#include "av1/common/reconintra.h"
+#include "av1/encoder/block.h"
 #include "av1/encoder/cost.h"
+#include "av1/encoder/rd.h"
 #include "test/acm_random.h"
 #include "test/register_state_check.h"
 #include "test/util.h"
@@ -31,7 +42,14 @@ using libaom_test::ACMRandom;

 using CdfBatchFn = void (*)(int *costs, int costs_stride, const uint16_t *cdf,
                             int cdf_stride, int n);
-using CdfBatchTestParams = std::tuple<CdfBatchFn, CdfBatchFn>;
+using CdfGenBatchFn = void (*)(int *costs, int costs_stride,
+                               const uint16_t *cdf, int cdf_stride, int nsyms,
+                               int n);
+using CdfInvBatchFn = void (*)(int *costs, int costs_stride,
+                               const uint16_t *cdf, int cdf_stride,
+                               const int *inv_map, int nsyms, int n);
+using CdfBatchTestParams =
+    std::tuple<CdfBatchFn, CdfBatchFn, CdfGenBatchFn, CdfInvBatchFn>;

 // Fixture that fills av1_cost_lut_low once before exercising the cost helpers.
 class CostTokensFromCdf4Test : public ::testing::Test {
@@ -66,6 +84,18 @@ void BuildCdf2(ACMRandom *rnd, aom_cdf_prob cdf[3]) {
   cdf[2] = 0;  // CDF adaptation counter slot; not read by the cost path.
 }

+// Builds a valid stored `nsyms`-symbol CDF into `cdf[0..nsyms-1]`, leaving
+// any stride padding `[nsyms, cdf_stride)` untouched for ASan/MSan checks.
+void BuildCdfN(ACMRandom *rnd, aom_cdf_prob *cdf, int nsyms) {
+  std::vector<uint16_t> v(nsyms - 1);
+  for (int k = 0; k < nsyms - 1; ++k) {
+    v[k] = 1 + (rnd->Rand16() % (CDF_PROB_TOP - 1));
+  }
+  std::sort(v.begin(), v.end());
+  for (int k = 0; k < nsyms - 1; ++k) cdf[k] = AOM_ICDF(v[k]);
+  cdf[nsyms - 1] = AOM_ICDF(CDF_PROB_TOP);
+}
+
 // The hybrid LUT+arithmetic path must equal the pure-arithmetic
 // av1_cost_symbol for every p15, including the COST_LUT_LOW boundary and the
 // fallback range.
@@ -114,24 +144,46 @@ TEST_F(CostTokensFromCdf4Test, MatchesGenericEdge) {
 void CheckBatchAgainstGeneric(CdfBatchFn fn) {
   ACMRandom rnd(ACMRandom::DeterministicSeed());
   const int kCdfStride = CDF_SIZE(4);  // 5
+  constexpr int kSentinel = -1234567;
+  constexpr int kCanary = 0x5A5A5A5A;
+  constexpr int kGuard = 8;
   for (const int costs_stride : { 4, 8 }) {
+    {
+      std::vector<int> out_buf(2 * kGuard + costs_stride, kCanary);
+      aom_cdf_prob dummy_cdf[1] = { 0 };
+      API_REGISTER_STATE_CHECK(
+          fn(out_buf.data() + kGuard, costs_stride, dummy_cdf, kCdfStride, 0));
+      for (const int val : out_buf) ASSERT_EQ(kCanary, val);
+    }
     for (int n = 1; n <= 45; ++n) {
       std::vector<aom_cdf_prob> cdf(n * kCdfStride);
       for (int k = 0; k < n; ++k) BuildCdf4(&rnd, &cdf[k * kCdfStride]);

-      std::vector<int> out(n * costs_stride, -1);
+      std::vector<int> out_buf(2 * kGuard + n * costs_stride, kCanary);
+      int *const out = out_buf.data() + kGuard;
+      std::fill(out, out + n * costs_stride, kSentinel);
       std::vector<int> ref(n * 4);
       for (int k = 0; k < n; ++k)
         av1_cost_tokens_from_cdf(&ref[k * 4], &cdf[k * kCdfStride], nullptr);

       API_REGISTER_STATE_CHECK(
-          fn(out.data(), costs_stride, cdf.data(), kCdfStride, n));
+          fn(out, costs_stride, cdf.data(), kCdfStride, n));

-      for (int k = 0; k < n; ++k)
+      for (int g = 0; g < kGuard; ++g) {
+        ASSERT_EQ(kCanary, out_buf[g]) << "underflow guard g=" << g;
+        ASSERT_EQ(kCanary, out_buf[kGuard + n * costs_stride + g])
+            << "overflow guard g=" << g;
+      }
+      for (int k = 0; k < n; ++k) {
         for (int i = 0; i < 4; ++i)
           ASSERT_EQ(ref[k * 4 + i], out[k * costs_stride + i])
               << "stride=" << costs_stride << " n=" << n << " k=" << k
               << " i=" << i;
+        for (int i = 4; i < costs_stride; ++i)
+          ASSERT_EQ(kSentinel, out[k * costs_stride + i])
+              << "stride=" << costs_stride << " n=" << n << " k=" << k
+              << " i=" << i;
+      }
     }
   }
 }
@@ -140,24 +192,46 @@ void CheckBatchAgainstGeneric(CdfBatchFn fn) {
 void CheckBatch2AgainstGeneric(CdfBatchFn fn) {
   ACMRandom rnd(ACMRandom::DeterministicSeed());
   const int kCdfStride = CDF_SIZE(2);  // 3
+  constexpr int kSentinel = -1234567;
+  constexpr int kCanary = 0x5A5A5A5A;
+  constexpr int kGuard = 8;
   for (const int costs_stride : { 2, 4 }) {
+    {
+      std::vector<int> out_buf(2 * kGuard + costs_stride, kCanary);
+      aom_cdf_prob dummy_cdf[1] = { 0 };
+      API_REGISTER_STATE_CHECK(
+          fn(out_buf.data() + kGuard, costs_stride, dummy_cdf, kCdfStride, 0));
+      for (const int val : out_buf) ASSERT_EQ(kCanary, val);
+    }
     for (int n = 1; n <= 45; ++n) {
       std::vector<aom_cdf_prob> cdf(n * kCdfStride);
       for (int k = 0; k < n; ++k) BuildCdf2(&rnd, &cdf[k * kCdfStride]);

-      std::vector<int> out(n * costs_stride, -1);
+      std::vector<int> out_buf(2 * kGuard + n * costs_stride, kCanary);
+      int *const out = out_buf.data() + kGuard;
+      std::fill(out, out + n * costs_stride, kSentinel);
       std::vector<int> ref(n * 2);
       for (int k = 0; k < n; ++k)
         av1_cost_tokens_from_cdf(&ref[k * 2], &cdf[k * kCdfStride], nullptr);

       API_REGISTER_STATE_CHECK(
-          fn(out.data(), costs_stride, cdf.data(), kCdfStride, n));
+          fn(out, costs_stride, cdf.data(), kCdfStride, n));

-      for (int k = 0; k < n; ++k)
+      for (int g = 0; g < kGuard; ++g) {
+        ASSERT_EQ(kCanary, out_buf[g]) << "underflow guard g=" << g;
+        ASSERT_EQ(kCanary, out_buf[kGuard + n * costs_stride + g])
+            << "overflow guard g=" << g;
+      }
+      for (int k = 0; k < n; ++k) {
         for (int i = 0; i < 2; ++i)
           ASSERT_EQ(ref[k * 2 + i], out[k * costs_stride + i])
               << "stride=" << costs_stride << " n=" << n << " k=" << k
               << " i=" << i;
+        for (int i = 2; i < costs_stride; ++i)
+          ASSERT_EQ(kSentinel, out[k * costs_stride + i])
+              << "stride=" << costs_stride << " n=" << n << " k=" << k
+              << " i=" << i;
+      }
     }
   }
 }
@@ -194,6 +268,243 @@ void RunBatchSpeed(const char *name, CdfBatchFn c_fn, CdfBatchFn simd_fn,
          label, n, costs_stride, ns[0], ns[1], ns[0] / ns[1]);
 }

+void CheckGeneralBatchAgainstGeneric(CdfGenBatchFn fn) {
+  ACMRandom rnd(ACMRandom::DeterministicSeed());
+  constexpr int kSentinel = -1234567;
+  constexpr int kCanary = 0x5A5A5A5A;
+  constexpr int kGuard = 8;
+  for (int nsyms = 2; nsyms <= 17; ++nsyms) {
+    for (const int cdf_stride : { nsyms, nsyms + 1, nsyms + 4 }) {
+      for (const int costs_stride : { nsyms, nsyms + 3 }) {
+        // Verify n == 0 leaves output and guards untouched.
+        {
+          std::vector<int> out_buf(2 * kGuard + costs_stride, kCanary);
+          aom_cdf_prob dummy_cdf[1] = { 0 };
+          API_REGISTER_STATE_CHECK(fn(out_buf.data() + kGuard, costs_stride,
+                                      dummy_cdf, cdf_stride, nsyms, 0));
+          for (const int val : out_buf) ASSERT_EQ(kCanary, val);
+        }
+        for (const int n : { 1, 2, 3, 4, 5, 7, 8, 9, 10, 13, 19 }) {
+          // Allocate exact tight tail so ASan catches any overread past
+          // cdf[(n - 1) * cdf_stride + nsyms - 1] and MSan catches reading
+          // uninitialized padding in [nsyms, cdf_stride).
+          const int cdf_elems = (n - 1) * cdf_stride + nsyms;
+          std::unique_ptr<aom_cdf_prob[]> cdf(new aom_cdf_prob[cdf_elems]);
+          for (int k = 0; k < n; ++k) {
+            aom_cdf_prob *const row = &cdf[k * cdf_stride];
+            if (k == 0) {
+              // Exercise p15 == CDF_PROB_TOP - 1 on symbol 0 (prob_idx 128)
+              // and minimum-prob duplicates.
+              for (int i = 0; i < nsyms - 1; ++i) row[i] = 1;
+              row[nsyms - 1] = 0;
+            } else if (k == 1) {
+              // Exercise p15 == CDF_PROB_TOP - 1 on the last symbol
+              // (cost_cdf_tail8_avx2 prob_idx 128 clamp).
+              for (int i = 0; i < nsyms - 1; ++i) row[i] = CDF_PROB_TOP - 1;
+              row[nsyms - 1] = 0;
+            } else {
+              BuildCdfN(&rnd, row, nsyms);
+            }
+          }
+
+          std::vector<int> out_buf(2 * kGuard + n * costs_stride, kCanary);
+          int *const out = out_buf.data() + kGuard;
+          std::fill(out, out + n * costs_stride, kSentinel);
+          std::vector<int> ref(n * nsyms);
+          for (int k = 0; k < n; ++k) {
+            av1_cost_tokens_from_cdf(&ref[k * nsyms], &cdf[k * cdf_stride],
+                                     nullptr);
+          }
+
+          API_REGISTER_STATE_CHECK(
+              fn(out, costs_stride, cdf.get(), cdf_stride, nsyms, n));
+
+          for (int g = 0; g < kGuard; ++g) {
+            ASSERT_EQ(kCanary, out_buf[g]) << "underflow guard g=" << g;
+            ASSERT_EQ(kCanary, out_buf[kGuard + n * costs_stride + g])
+                << "overflow guard g=" << g;
+          }
+          for (int k = 0; k < n; ++k) {
+            for (int i = 0; i < nsyms; ++i) {
+              ASSERT_EQ(ref[k * nsyms + i], out[k * costs_stride + i])
+                  << "nsyms=" << nsyms << " cdf_stride=" << cdf_stride
+                  << " costs_stride=" << costs_stride << " n=" << n
+                  << " k=" << k << " i=" << i;
+            }
+            for (int i = nsyms; i < costs_stride; ++i) {
+              ASSERT_EQ(kSentinel, out[k * costs_stride + i])
+                  << "overwrote padding: nsyms=" << nsyms << " k=" << k
+                  << " i=" << i;
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+void CheckInvBatchAgainstGeneric(CdfInvBatchFn fn) {
+  ACMRandom rnd(ACMRandom::DeterministicSeed());
+  constexpr int kSentinel = -7654321;
+  constexpr int kCanary = 0x5A5A5A5A;
+  constexpr int kGuard = 8;
+  // Test all real extended transform inverse maps plus synthetic permutations.
+  for (int set_type = 1; set_type < EXT_TX_SET_TYPES; ++set_type) {
+    const int nsyms = av1_num_ext_tx_set[set_type];
+    const int *const inv_map = av1_ext_tx_inv[set_type];
+    for (const int cdf_stride :
+         { nsyms, CDF_SIZE(nsyms), CDF_SIZE(TX_TYPES) }) {
+      {
+        std::vector<int> out_buf(2 * kGuard + TX_TYPES, kCanary);
+        aom_cdf_prob dummy_cdf[1] = { 0 };
+        API_REGISTER_STATE_CHECK(fn(out_buf.data() + kGuard, TX_TYPES,
+                                    dummy_cdf, cdf_stride, inv_map, nsyms, 0));
+        for (const int val : out_buf) ASSERT_EQ(kCanary, val);
+      }
+      for (const int n : { 1, 2, 5, 13 }) {
+        const int cdf_elems = (n - 1) * cdf_stride + nsyms;
+        std::unique_ptr<aom_cdf_prob[]> cdf(new aom_cdf_prob[cdf_elems]);
+        for (int k = 0; k < n; ++k) {
+          aom_cdf_prob *const row = &cdf[k * cdf_stride];
+          if (k == 0) {
+            for (int i = 0; i < nsyms - 1; ++i) row[i] = CDF_PROB_TOP - 1;
+            row[nsyms - 1] = 0;
+          } else {
+            BuildCdfN(&rnd, row, nsyms);
+          }
+        }
+        std::vector<int> out_buf(2 * kGuard + n * TX_TYPES, kCanary);
+        int *const out = out_buf.data() + kGuard;
+        std::fill(out, out + n * TX_TYPES, kSentinel);
+        std::vector<int> ref(n * TX_TYPES, kSentinel);
+        for (int k = 0; k < n; ++k) {
+          av1_cost_tokens_from_cdf(&ref[k * TX_TYPES], &cdf[k * cdf_stride],
+                                   inv_map);
+        }
+        API_REGISTER_STATE_CHECK(
+            fn(out, TX_TYPES, cdf.get(), cdf_stride, inv_map, nsyms, n));
+        for (int g = 0; g < kGuard; ++g) {
+          ASSERT_EQ(kCanary, out_buf[g]) << "underflow guard g=" << g;
+          ASSERT_EQ(kCanary, out_buf[kGuard + n * TX_TYPES + g])
+              << "overflow guard g=" << g;
+        }
+        for (int k = 0; k < n; ++k) {
+          for (int i = 0; i < TX_TYPES; ++i) {
+            ASSERT_EQ(ref[k * TX_TYPES + i], out[k * TX_TYPES + i])
+                << "set_type=" << set_type << " nsyms=" << nsyms
+                << " cdf_stride=" << cdf_stride << " n=" << n << " k=" << k
+                << " i=" << i;
+          }
+        }
+      }
+    }
+  }
+  // Exercise all nsyms in [2..17] with reversed mapping, tight/padded strides,
+  // and extreme CDFs.
+  for (int nsyms = 2; nsyms <= 17; ++nsyms) {
+    std::vector<int> inv_map(nsyms);
+    for (int i = 0; i < nsyms; ++i) inv_map[i] = nsyms - 1 - i;
+    for (const int cdf_stride : { nsyms, nsyms + 4 }) {
+      for (const int costs_stride : { nsyms, nsyms + 3 }) {
+        for (const int n : { 1, 7 }) {
+          const int cdf_elems = (n - 1) * cdf_stride + nsyms;
+          std::unique_ptr<aom_cdf_prob[]> cdf(new aom_cdf_prob[cdf_elems]);
+          for (int k = 0; k < n; ++k) {
+            aom_cdf_prob *const row = &cdf[k * cdf_stride];
+            if (k == 0) {
+              for (int i = 0; i < nsyms - 1; ++i) row[i] = 1;
+              row[nsyms - 1] = 0;
+            } else if (k == 1) {
+              for (int i = 0; i < nsyms - 1; ++i) row[i] = CDF_PROB_TOP - 1;
+              row[nsyms - 1] = 0;
+            } else {
+              BuildCdfN(&rnd, row, nsyms);
+            }
+          }
+          std::vector<int> out_buf(2 * kGuard + n * costs_stride, kCanary);
+          int *const out = out_buf.data() + kGuard;
+          std::fill(out, out + n * costs_stride, kSentinel);
+          std::vector<int> ref(n * costs_stride, kSentinel);
+          for (int k = 0; k < n; ++k) {
+            av1_cost_tokens_from_cdf(&ref[k * costs_stride],
+                                     &cdf[k * cdf_stride], inv_map.data());
+          }
+          API_REGISTER_STATE_CHECK(fn(out, costs_stride, cdf.get(), cdf_stride,
+                                      inv_map.data(), nsyms, n));
+          for (int g = 0; g < kGuard; ++g) {
+            ASSERT_EQ(kCanary, out_buf[g]) << "underflow guard g=" << g;
+            ASSERT_EQ(kCanary, out_buf[kGuard + n * costs_stride + g])
+                << "overflow guard g=" << g;
+          }
+          for (int i = 0; i < n * costs_stride; ++i) {
+            ASSERT_EQ(ref[i], out[i])
+                << "nsyms=" << nsyms << " cdf_stride=" << cdf_stride
+                << " costs_stride=" << costs_stride << " idx=" << i;
+          }
+        }
+      }
+    }
+  }
+}
+
+void RunGeneralBatchSpeed(CdfGenBatchFn c_fn, CdfGenBatchFn simd_fn,
+                          const char *label, int nsyms, int n, int cdf_stride,
+                          int costs_stride) {
+  ACMRandom rnd(ACMRandom::DeterministicSeed());
+  std::vector<aom_cdf_prob> cdf(n * cdf_stride, 0);
+  for (int k = 0; k < n; ++k) BuildCdfN(&rnd, &cdf[k * cdf_stride], nsyms);
+  std::vector<int> out(n * costs_stride);
+
+  const CdfGenBatchFn funcs[2] = { c_fn, simd_fn };
+  const int kLoops = 500000;
+  double ns[2];
+  volatile int sink = 0;
+  for (int i = 0; i < 2; ++i) {
+    aom_usec_timer timer;
+    aom_usec_timer_start(&timer);
+    for (int j = 0; j < kLoops; ++j)
+      funcs[i](out.data(), costs_stride, cdf.data(), cdf_stride, nsyms, n);
+    aom_usec_timer_mark(&timer);
+    sink += out[0];
+    ns[i] =
+        1000.0 * static_cast<double>(aom_usec_timer_elapsed(&timer)) / kLoops;
+  }
+  (void)sink;
+  printf(
+      "cdf_batch   %-11s nsyms=%2d n=%2d: c %7.1f ns  tst %7.1f ns (%4.2fx)\n",
+      label, nsyms, n, ns[0], ns[1], ns[0] / ns[1]);
+}
+
+void RunInvBatchSpeed(CdfInvBatchFn c_fn, CdfInvBatchFn simd_fn,
+                      const char *label, int set_type, int n) {
+  ACMRandom rnd(ACMRandom::DeterministicSeed());
+  const int nsyms = av1_num_ext_tx_set[set_type];
+  const int *const inv_map = av1_ext_tx_inv[set_type];
+  const int cdf_stride = CDF_SIZE(TX_TYPES);
+  std::vector<aom_cdf_prob> cdf(n * cdf_stride, 0);
+  for (int k = 0; k < n; ++k) BuildCdfN(&rnd, &cdf[k * cdf_stride], nsyms);
+  std::vector<int> out(n * TX_TYPES);
+
+  const CdfInvBatchFn funcs[2] = { c_fn, simd_fn };
+  const int kLoops = 500000;
+  double ns[2];
+  volatile int sink = 0;
+  for (int i = 0; i < 2; ++i) {
+    aom_usec_timer timer;
+    aom_usec_timer_start(&timer);
+    for (int j = 0; j < kLoops; ++j)
+      funcs[i](out.data(), TX_TYPES, cdf.data(), cdf_stride, inv_map, nsyms, n);
+    aom_usec_timer_mark(&timer);
+    sink += out[0];
+    ns[i] =
+        1000.0 * static_cast<double>(aom_usec_timer_elapsed(&timer)) / kLoops;
+  }
+  (void)sink;
+  printf(
+      "inv_batch   %-11s nsyms=%2d n=%2d: c %7.1f ns  tst %7.1f ns (%4.2fx)\n",
+      label, nsyms, n, ns[0], ns[1], ns[0] / ns[1]);
+}
+
 TEST_P(CostTokensFromCdfBatchTest, Batch4MatchesGeneric) {
   CheckBatchAgainstGeneric(GET_PARAM(0));
 }
@@ -202,6 +513,14 @@ TEST_P(CostTokensFromCdfBatchTest, Batch2MatchesGeneric) {
   CheckBatch2AgainstGeneric(GET_PARAM(1));
 }

+TEST_P(CostTokensFromCdfBatchTest, BatchGeneralMatchesGeneric) {
+  CheckGeneralBatchAgainstGeneric(GET_PARAM(2));
+}
+
+TEST_P(CostTokensFromCdfBatchTest, BatchInvMatchesGeneric) {
+  CheckInvBatchAgainstGeneric(GET_PARAM(3));
+}
+
 TEST_P(CostTokensFromCdfBatchTest, DISABLED_Batch4Speed) {
   RunBatchSpeed("cdf_4_batch", av1_cost_tokens_from_cdf_4_batch_c, GET_PARAM(0),
                 CDF_SIZE(4), 4, "base_cost", SIG_COEF_CONTEXTS, 8);
@@ -216,16 +535,734 @@ TEST_P(CostTokensFromCdfBatchTest, DISABLED_Batch2Speed) {
                 CDF_SIZE(2), 2, "eob_extra", EOB_COEF_CONTEXTS, 2);
 }

-INSTANTIATE_TEST_SUITE_P(
-    C, CostTokensFromCdfBatchTest,
-    ::testing::Values(CdfBatchTestParams(av1_cost_tokens_from_cdf_4_batch_c,
-                                         av1_cost_tokens_from_cdf_2_batch_c)));
+TEST_P(CostTokensFromCdfBatchTest, DISABLED_BatchGeneralSpeed) {
+  RunGeneralBatchSpeed(av1_cost_tokens_from_cdf_batch_c, GET_PARAM(2),
+                       "base_eob", 3, SIG_COEF_CONTEXTS_EOB, CDF_SIZE(3), 4);
+  RunGeneralBatchSpeed(av1_cost_tokens_from_cdf_batch_c, GET_PARAM(2),
+                       "angle_d", 7, DIRECTIONAL_MODES, CDF_SIZE(7), 7);
+  RunGeneralBatchSpeed(av1_cost_tokens_from_cdf_batch_c, GET_PARAM(2),
+                       "partition", EXT_PARTITION_TYPES, 12,
+                       CDF_SIZE(EXT_PARTITION_TYPES), EXT_PARTITION_TYPES);
+  RunGeneralBatchSpeed(av1_cost_tokens_from_cdf_batch_c, GET_PARAM(2),
+                       "intra_y", INTRA_MODES, KF_MODE_CONTEXTS,
+                       CDF_SIZE(INTRA_MODES), INTRA_MODES);
+  RunGeneralBatchSpeed(av1_cost_tokens_from_cdf_batch_c, GET_PARAM(2),
+                       "cfl_alpha", CFL_ALPHABET_SIZE, CFL_ALPHA_CONTEXTS,
+                       CDF_SIZE(CFL_ALPHABET_SIZE), CFL_ALPHABET_SIZE);
+  // Shuffled mixed-shape schedule to exercise dispatch branch prediction.
+  ACMRandom rnd(ACMRandom::DeterministicSeed());
+  constexpr int kSchedule = 4096;
+  const int kShapes[] = { 2, 3, 4, 5, 6, 7, 8, 10, 13, 16 };
+  constexpr int kNumShapes = static_cast<int>(sizeof(kShapes) / sizeof(int));
+  std::vector<int> shape_idx(kSchedule);
+  for (int i = 0; i < kSchedule; ++i) {
+    shape_idx[i] = rnd.PseudoUniform(kNumShapes);
+  }
+  std::vector<std::vector<aom_cdf_prob>> cdfs(kNumShapes);
+  for (int si = 0; si < kNumShapes; ++si) {
+    cdfs[si].assign(16 * CDF_SIZE(16), 0);
+    for (int k = 0; k < 16; ++k) {
+      BuildCdfN(&rnd, &cdfs[si][k * CDF_SIZE(16)], kShapes[si]);
+    }
+  }
+  std::vector<int> out(16 * 16);
+  const CdfGenBatchFn funcs[2] = { av1_cost_tokens_from_cdf_batch_c,
+                                   GET_PARAM(2) };
+  double ns[2];
+  volatile int sink = 0;
+  for (int f = 0; f < 2; ++f) {
+    aom_usec_timer timer;
+    aom_usec_timer_start(&timer);
+    for (int rep = 0; rep < 200; ++rep) {
+      for (int i = 0; i < kSchedule; ++i) {
+        const int si = shape_idx[i];
+        funcs[f](out.data(), 16, cdfs[si].data(), CDF_SIZE(16), kShapes[si], 8);
+      }
+    }
+    aom_usec_timer_mark(&timer);
+    sink += out[0];
+    ns[f] = 1000.0 * static_cast<double>(aom_usec_timer_elapsed(&timer)) /
+            (200.0 * kSchedule);
+  }
+  (void)sink;
+  printf(
+      "cdf_batch   mixed_4096           : c %7.1f ns  tst %7.1f ns (%4.2fx)\n",
+      ns[0], ns[1], ns[0] / ns[1]);
+}
+
+TEST_P(CostTokensFromCdfBatchTest, DISABLED_BatchInvSpeed) {
+  RunInvBatchSpeed(av1_cost_tokens_from_cdf_inv_batch_c, GET_PARAM(3),
+                   "dtt4_idtx", EXT_TX_SET_DTT4_IDTX, INTRA_MODES);
+  RunInvBatchSpeed(av1_cost_tokens_from_cdf_inv_batch_c, GET_PARAM(3),
+                   "intra_dtt7", EXT_TX_SET_DTT4_IDTX_1DDCT, INTRA_MODES);
+  RunInvBatchSpeed(av1_cost_tokens_from_cdf_inv_batch_c, GET_PARAM(3),
+                   "inter_dtt9", EXT_TX_SET_DTT9_IDTX_1DDCT, 1);
+  RunInvBatchSpeed(av1_cost_tokens_from_cdf_inv_batch_c, GET_PARAM(3),
+                   "inter_all16", EXT_TX_SET_ALL16, 1);
+}
+
+INSTANTIATE_TEST_SUITE_P(C, CostTokensFromCdfBatchTest,
+                         ::testing::Values(CdfBatchTestParams(
+                             av1_cost_tokens_from_cdf_4_batch_c,
+                             av1_cost_tokens_from_cdf_2_batch_c,
+                             av1_cost_tokens_from_cdf_batch_c,
+                             av1_cost_tokens_from_cdf_inv_batch_c)));

 #if HAVE_AVX2
 INSTANTIATE_TEST_SUITE_P(AVX2, CostTokensFromCdfBatchTest,
                          ::testing::Values(CdfBatchTestParams(
                              av1_cost_tokens_from_cdf_4_batch_avx2,
-                             av1_cost_tokens_from_cdf_2_batch_avx2)));
+                             av1_cost_tokens_from_cdf_2_batch_avx2,
+                             av1_cost_tokens_from_cdf_batch_avx2,
+                             av1_cost_tokens_from_cdf_inv_batch_avx2)));
 #endif  // HAVE_AVX2

+constexpr int kParityUseIntraExtTx[EXT_TX_SETS_INTRA][EXT_TX_SIZES] = {
+  { 1, 1, 1, 1 },
+  { 1, 1, 0, 0 },
+  { 0, 0, 1, 0 },
+};
+
+constexpr int kParityUseInterExtTx[EXT_TX_SETS_INTER][EXT_TX_SIZES] = {
+  { 1, 1, 1, 1 },
+  { 1, 1, 0, 0 },
+  { 0, 0, 1, 0 },
+  { 0, 1, 1, 1 },
+};
+
+constexpr int kParityExtTxSetIdxToType[2][AOMMAX(EXT_TX_SETS_INTRA,
+                                                 EXT_TX_SETS_INTER)] = {
+  { EXT_TX_SET_DCTONLY, EXT_TX_SET_DTT4_IDTX_1DDCT, EXT_TX_SET_DTT4_IDTX },
+  { EXT_TX_SET_DCTONLY, EXT_TX_SET_ALL16, EXT_TX_SET_DTT9_IDTX_1DDCT,
+    EXT_TX_SET_DCT_IDTX },
+};
+
+void PopulateRandomFrameContext(ACMRandom *rnd, FRAME_CONTEXT *fc) {
+  std::memset(fc, 0, sizeof(*fc));
+  for (int i = 0; i < PARTITION_CONTEXTS; ++i) {
+    const int nsyms = (i < PARTITION_PLOFFSET)       ? PARTITION_TYPES
+                      : (i < 4 * PARTITION_PLOFFSET) ? EXT_PARTITION_TYPES
+                                                     : EXT_PARTITION_TYPES - 2;
+    BuildCdfN(rnd, fc->partition_cdf[i], nsyms);
+  }
+  for (int i = 0; i < SKIP_MODE_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->skip_mode_cdfs[i], 2);
+  for (int i = 0; i < SKIP_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->skip_txfm_cdfs[i], 2);
+  for (int i = 0; i < KF_MODE_CONTEXTS; ++i)
+    for (int j = 0; j < KF_MODE_CONTEXTS; ++j)
+      BuildCdfN(rnd, fc->kf_y_cdf[i][j], INTRA_MODES);
+  for (int i = 0; i < BLOCK_SIZE_GROUPS; ++i)
+    BuildCdfN(rnd, fc->y_mode_cdf[i], INTRA_MODES);
+  for (int cfl = 0; cfl < CFL_ALLOWED_TYPES; ++cfl) {
+    const int nsyms =
+        (cfl == CFL_DISALLOWED) ? UV_INTRA_MODES - 1 : UV_INTRA_MODES;
+    for (int j = 0; j < INTRA_MODES; ++j)
+      BuildCdfN(rnd, fc->uv_mode_cdf[cfl][j], nsyms);
+  }
+  BuildCdfN(rnd, fc->filter_intra_mode_cdf, FILTER_INTRA_MODES);
+  for (int i = 0; i < BLOCK_SIZES_ALL; ++i)
+    BuildCdfN(rnd, fc->filter_intra_cdfs[i], 2);
+  for (int i = 0; i < PALATTE_BSIZE_CTXS; ++i) {
+    BuildCdfN(rnd, fc->palette_y_size_cdf[i], PALETTE_SIZES);
+    BuildCdfN(rnd, fc->palette_uv_size_cdf[i], PALETTE_SIZES);
+    for (int j = 0; j < PALETTE_Y_MODE_CONTEXTS; ++j)
+      BuildCdfN(rnd, fc->palette_y_mode_cdf[i][j], 2);
+  }
+  for (int i = 0; i < PALETTE_UV_MODE_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->palette_uv_mode_cdf[i], 2);
+  for (int i = 0; i < PALETTE_SIZES; ++i) {
+    const int nsyms = i + PALETTE_MIN_SIZE;
+    for (int j = 0; j < PALETTE_COLOR_INDEX_CONTEXTS; ++j) {
+      BuildCdfN(rnd, fc->palette_y_color_index_cdf[i][j], nsyms);
+      BuildCdfN(rnd, fc->palette_uv_color_index_cdf[i][j], nsyms);
+    }
+  }
+  BuildCdfN(rnd, fc->cfl_sign_cdf, CFL_JOINT_SIGNS);
+  for (int i = 0; i < CFL_ALPHA_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->cfl_alpha_cdf[i], CFL_ALPHABET_SIZE);
+  for (int i = 0; i < MAX_TX_CATS; ++i) {
+    const int nsyms = (i == 0) ? 2 : MAX_TX_DEPTH + 1;
+    for (int j = 0; j < TX_SIZE_CONTEXTS; ++j)
+      BuildCdfN(rnd, fc->tx_size_cdf[i][j], nsyms);
+  }
+  for (int i = 0; i < TXFM_PARTITION_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->txfm_partition_cdf[i], 2);
+  BuildCdfN(rnd, fc->intrabc_cdf, 2);
+  for (int i = TX_4X4; i < EXT_TX_SIZES; ++i) {
+    for (int s = 1; s < EXT_TX_SETS_INTRA; ++s) {
+      if (kParityUseIntraExtTx[s][i]) {
+        const int set_type = kParityExtTxSetIdxToType[0][s];
+        const int nsyms = av1_num_ext_tx_set[set_type];
+        for (int j = 0; j < INTRA_MODES; ++j)
+          BuildCdfN(rnd, fc->intra_ext_tx_cdf[s][i][j], nsyms);
+      }
+    }
+    for (int s = 1; s < EXT_TX_SETS_INTER; ++s) {
+      if (kParityUseInterExtTx[s][i]) {
+        const int set_type = kParityExtTxSetIdxToType[1][s];
+        const int nsyms = av1_num_ext_tx_set[set_type];
+        BuildCdfN(rnd, fc->inter_ext_tx_cdf[s][i], nsyms);
+      }
+    }
+  }
+  for (int i = 0; i < DIRECTIONAL_MODES; ++i)
+    BuildCdfN(rnd, fc->angle_delta_cdf[i], 2 * MAX_ANGLE_DELTA + 1);
+  for (int i = 0; i < SPATIAL_PREDICTION_PROBS; ++i)
+    BuildCdfN(rnd, fc->seg.spatial_pred_seg_cdf[i], MAX_SEGMENTS);
+  for (int i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->switchable_interp_cdf[i], SWITCHABLE_FILTERS);
+  for (int i = 0; i < SEG_TEMPORAL_PRED_CTXS; ++i)
+    BuildCdfN(rnd, fc->seg.pred_cdf[i], 2);
+  for (int i = 0; i < COMP_INTER_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->comp_inter_cdf[i], 2);
+  for (int i = 0; i < REF_CONTEXTS; ++i) {
+    for (int j = 0; j < SINGLE_REFS - 1; ++j)
+      BuildCdfN(rnd, fc->single_ref_cdf[i][j], 2);
+    for (int j = 0; j < FWD_REFS - 1; ++j)
+      BuildCdfN(rnd, fc->comp_ref_cdf[i][j], 2);
+    for (int j = 0; j < BWD_REFS - 1; ++j)
+      BuildCdfN(rnd, fc->comp_bwdref_cdf[i][j], 2);
+  }
+  for (int i = 0; i < COMP_REF_TYPE_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->comp_ref_type_cdf[i], COMP_REFERENCE_TYPES);
+  for (int i = 0; i < UNI_COMP_REF_CONTEXTS; ++i)
+    for (int j = 0; j < UNIDIR_COMP_REFS - 1; ++j)
+      BuildCdfN(rnd, fc->uni_comp_ref_cdf[i][j], 2);
+  for (int i = 0; i < INTRA_INTER_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->intra_inter_cdf[i], 2);
+  for (int i = 0; i < NEWMV_MODE_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->newmv_cdf[i], 2);
+  for (int i = 0; i < GLOBALMV_MODE_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->zeromv_cdf[i], 2);
+  for (int i = 0; i < REFMV_MODE_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->refmv_cdf[i], 2);
+  for (int i = 0; i < DRL_MODE_CONTEXTS; ++i) BuildCdfN(rnd, fc->drl_cdf[i], 2);
+  for (int i = 0; i < INTER_MODE_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->inter_compound_mode_cdf[i], INTER_COMPOUND_MODES);
+  for (int i = 0; i < BLOCK_SIZES_ALL; ++i) {
+    BuildCdfN(rnd, fc->compound_type_cdf[i], MASKED_COMPOUND_TYPES);
+    BuildCdfN(rnd, fc->wedge_idx_cdf[i], 16);
+    BuildCdfN(rnd, fc->wedge_interintra_cdf[i], 2);
+    BuildCdfN(rnd, fc->motion_mode_cdf[i], MOTION_MODES);
+    BuildCdfN(rnd, fc->obmc_cdf[i], 2);
+  }
+  for (int i = 0; i < BLOCK_SIZE_GROUPS; ++i) {
+    BuildCdfN(rnd, fc->interintra_cdf[i], 2);
+    BuildCdfN(rnd, fc->interintra_mode_cdf[i], INTERINTRA_MODES);
+  }
+  for (int i = 0; i < COMP_INDEX_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->compound_index_cdf[i], 2);
+  for (int i = 0; i < COMP_GROUP_IDX_CONTEXTS; ++i)
+    BuildCdfN(rnd, fc->comp_group_idx_cdf[i], 2);
+  for (int p = 0; p < PLANE_TYPES; ++p) {
+    for (int c = 0; c < 2; ++c) {
+      BuildCdfN(rnd, fc->eob_flag_cdf16[p][c], 5);
+      BuildCdfN(rnd, fc->eob_flag_cdf32[p][c], 6);
+      BuildCdfN(rnd, fc->eob_flag_cdf64[p][c], 7);
+      BuildCdfN(rnd, fc->eob_flag_cdf128[p][c], 8);
+      BuildCdfN(rnd, fc->eob_flag_cdf256[p][c], 9);
+      BuildCdfN(rnd, fc->eob_flag_cdf512[p][c], 10);
+      BuildCdfN(rnd, fc->eob_flag_cdf1024[p][c], 11);
+    }
+    for (int c = 0; c < DC_SIGN_CONTEXTS; ++c)
+      BuildCdfN(rnd, fc->dc_sign_cdf[p][c], 2);
+  }
+  for (int t = 0; t < TX_SIZES; ++t) {
+    for (int c = 0; c < TXB_SKIP_CONTEXTS; ++c)
+      BuildCdfN(rnd, fc->txb_skip_cdf[t][c], 2);
+    for (int p = 0; p < PLANE_TYPES; ++p) {
+      for (int c = 0; c < SIG_COEF_CONTEXTS_EOB; ++c)
+        BuildCdfN(rnd, fc->coeff_base_eob_cdf[t][p][c], 3);
+      for (int c = 0; c < SIG_COEF_CONTEXTS; ++c)
+        BuildCdfN(rnd, fc->coeff_base_cdf[t][p][c], 4);
+      for (int c = 0; c < EOB_COEF_CONTEXTS; ++c)
+        BuildCdfN(rnd, fc->eob_extra_cdf[t][p][c], 2);
+      for (int c = 0; c < LEVEL_CONTEXTS; ++c)
+        BuildCdfN(rnd, fc->coeff_br_cdf[t][p][c], BR_CDF_SIZE);
+    }
+  }
+}
+
+void FillInterTxTypeCostsScalar(ModeCosts *mode_costs,
+                                const FRAME_CONTEXT *fc) {
+  for (int i = TX_4X4; i < EXT_TX_SIZES; ++i) {
+    for (int s = 1; s < EXT_TX_SETS_INTER; ++s) {
+      if (kParityUseInterExtTx[s][i]) {
+        av1_cost_tokens_from_cdf(
+            mode_costs->inter_tx_type_costs[s][i], fc->inter_ext_tx_cdf[s][i],
+            av1_ext_tx_inv[kParityExtTxSetIdxToType[1][s]]);
+      }
+    }
+  }
+}
+
+void FillModeRatesScalar(const AV1_COMMON *cm, ModeCosts *mode_costs,
+                         const FRAME_CONTEXT *fc) {
+  const int is_intra_only = frame_is_intra_only(cm);
+  for (int i = 0; i < PARTITION_CONTEXTS; ++i)
+    av1_cost_tokens_from_cdf(mode_costs->partition_cost[i],
+                             fc->partition_cdf[i], nullptr);
+  if (cm->current_frame.skip_mode_info.skip_mode_flag) {
+    for (int i = 0; i < SKIP_MODE_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->skip_mode_cost[i],
+                               fc->skip_mode_cdfs[i], nullptr);
+  } else {
+    std::memset(mode_costs->skip_mode_cost, 0,
+                sizeof(mode_costs->skip_mode_cost));
+  }
+  for (int i = 0; i < SKIP_CONTEXTS; ++i)
+    av1_cost_tokens_from_cdf(mode_costs->skip_txfm_cost[i],
+                             fc->skip_txfm_cdfs[i], nullptr);
+  for (int i = 0; i < KF_MODE_CONTEXTS; ++i)
+    for (int j = 0; j < KF_MODE_CONTEXTS; ++j)
+      av1_cost_tokens_from_cdf(mode_costs->y_mode_costs[i][j],
+                               fc->kf_y_cdf[i][j], nullptr);
+  for (int i = 0; i < BLOCK_SIZE_GROUPS; ++i)
+    av1_cost_tokens_from_cdf(mode_costs->mbmode_cost[i], fc->y_mode_cdf[i],
+                             nullptr);
+  for (int i = 0; i < CFL_ALLOWED_TYPES; ++i)
+    for (int j = 0; j < INTRA_MODES; ++j)
+      av1_cost_tokens_from_cdf(mode_costs->intra_uv_mode_cost[i][j],
+                               fc->uv_mode_cdf[i][j], nullptr);
+  av1_cost_tokens_from_cdf(mode_costs->filter_intra_mode_cost,
+                           fc->filter_intra_mode_cdf, nullptr);
+  for (int i = 0; i < BLOCK_SIZES_ALL; ++i) {
+    if (av1_filter_intra_allowed_bsize(cm, static_cast<BLOCK_SIZE>(i)))
+      av1_cost_tokens_from_cdf(mode_costs->filter_intra_cost[i],
+                               fc->filter_intra_cdfs[i], nullptr);
+  }
+  for (int i = 0; i < PALATTE_BSIZE_CTXS; ++i) {
+    av1_cost_tokens_from_cdf(mode_costs->palette_y_size_cost[i],
+                             fc->palette_y_size_cdf[i], nullptr);
+    av1_cost_tokens_from_cdf(mode_costs->palette_uv_size_cost[i],
+                             fc->palette_uv_size_cdf[i], nullptr);
+    for (int j = 0; j < PALETTE_Y_MODE_CONTEXTS; ++j)
+      av1_cost_tokens_from_cdf(mode_costs->palette_y_mode_cost[i][j],
+                               fc->palette_y_mode_cdf[i][j], nullptr);
+  }
+  for (int i = 0; i < PALETTE_UV_MODE_CONTEXTS; ++i)
+    av1_cost_tokens_from_cdf(mode_costs->palette_uv_mode_cost[i],
+                             fc->palette_uv_mode_cdf[i], nullptr);
+  for (int i = 0; i < PALETTE_SIZES; ++i) {
+    for (int j = 0; j < PALETTE_COLOR_INDEX_CONTEXTS; ++j) {
+      av1_cost_tokens_from_cdf(mode_costs->palette_y_color_cost[i][j],
+                               fc->palette_y_color_index_cdf[i][j], nullptr);
+      av1_cost_tokens_from_cdf(mode_costs->palette_uv_color_cost[i][j],
+                               fc->palette_uv_color_index_cdf[i][j], nullptr);
+    }
+  }
+  int sign_cost[CFL_JOINT_SIGNS];
+  av1_cost_tokens_from_cdf(sign_cost, fc->cfl_sign_cdf, nullptr);
+  for (int joint_sign = 0; joint_sign < CFL_JOINT_SIGNS; ++joint_sign) {
+    int *cost_u = mode_costs->cfl_cost[joint_sign][CFL_PRED_U];
+    int *cost_v = mode_costs->cfl_cost[joint_sign][CFL_PRED_V];
+    if (CFL_SIGN_U(joint_sign) == CFL_SIGN_ZERO) {
+      std::memset(cost_u, 0, CFL_ALPHABET_SIZE * sizeof(*cost_u));
+    } else {
+      av1_cost_tokens_from_cdf(
+          cost_u, fc->cfl_alpha_cdf[CFL_CONTEXT_U(joint_sign)], nullptr);
+    }
+    if (CFL_SIGN_V(joint_sign) == CFL_SIGN_ZERO) {
+      std::memset(cost_v, 0, CFL_ALPHABET_SIZE * sizeof(*cost_v));
+    } else {
+      av1_cost_tokens_from_cdf(
+          cost_v, fc->cfl_alpha_cdf[CFL_CONTEXT_V(joint_sign)], nullptr);
+    }
+    for (int u = 0; u < CFL_ALPHABET_SIZE; ++u)
+      cost_u[u] += sign_cost[joint_sign];
+  }
+  for (int i = 0; i < MAX_TX_CATS; ++i)
+    for (int j = 0; j < TX_SIZE_CONTEXTS; ++j)
+      av1_cost_tokens_from_cdf(mode_costs->tx_size_cost[i][j],
+                               fc->tx_size_cdf[i][j], nullptr);
+  for (int i = 0; i < TXFM_PARTITION_CONTEXTS; ++i)
+    av1_cost_tokens_from_cdf(mode_costs->txfm_partition_cost[i],
+                             fc->txfm_partition_cdf[i], nullptr);
+  const int allow_intrabc = av1_allow_intrabc(cm);
+  if (allow_intrabc) {
+    FillInterTxTypeCostsScalar(mode_costs, fc);
+    av1_cost_tokens_from_cdf(mode_costs->intrabc_cost, fc->intrabc_cdf,
+                             nullptr);
+  }
+  for (int i = TX_4X4; i < EXT_TX_SIZES; ++i) {
+    for (int s = 1; s < EXT_TX_SETS_INTRA; ++s) {
+      if (kParityUseIntraExtTx[s][i]) {
+        for (int j = 0; j < INTRA_MODES; ++j) {
+          av1_cost_tokens_from_cdf(
+              mode_costs->intra_tx_type_costs[s][i][j],
+              fc->intra_ext_tx_cdf[s][i][j],
+              av1_ext_tx_inv[kParityExtTxSetIdxToType[0][s]]);
+        }
+      }
+    }
+  }
+  for (int i = 0; i < DIRECTIONAL_MODES; ++i)
+    av1_cost_tokens_from_cdf(mode_costs->angle_delta_cost[i],
+                             fc->angle_delta_cdf[i], nullptr);
+  for (int i = 0; i < SPATIAL_PREDICTION_PROBS; ++i)
+    av1_cost_tokens_from_cdf(mode_costs->spatial_pred_cost[i],
+                             fc->seg.spatial_pred_seg_cdf[i], nullptr);
+  if (is_intra_only) {
+    mode_costs->intra_only_skipped_inter_costs = 1;
+    mode_costs->intra_only_skipped_inter_tx_type =
+        static_cast<uint8_t>(!allow_intrabc);
+  } else {
+    mode_costs->intra_only_skipped_inter_costs = 0;
+    mode_costs->intra_only_skipped_inter_tx_type = 0;
+    for (int i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->switchable_interp_costs[i],
+                               fc->switchable_interp_cdf[i], nullptr);
+    FillInterTxTypeCostsScalar(mode_costs, fc);
+    for (int i = 0; i < SEG_TEMPORAL_PRED_CTXS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->tmp_pred_cost[i],
+                               fc->seg.pred_cdf[i], nullptr);
+    for (int i = 0; i < COMP_INTER_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->comp_inter_cost[i],
+                               fc->comp_inter_cdf[i], nullptr);
+    for (int i = 0; i < REF_CONTEXTS; ++i)
+      for (int j = 0; j < SINGLE_REFS - 1; ++j)
+        av1_cost_tokens_from_cdf(mode_costs->single_ref_cost[i][j],
+                                 fc->single_ref_cdf[i][j], nullptr);
+    for (int i = 0; i < COMP_REF_TYPE_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->comp_ref_type_cost[i],
+                               fc->comp_ref_type_cdf[i], nullptr);
+    for (int i = 0; i < UNI_COMP_REF_CONTEXTS; ++i)
+      for (int j = 0; j < UNIDIR_COMP_REFS - 1; ++j)
+        av1_cost_tokens_from_cdf(mode_costs->uni_comp_ref_cost[i][j],
+                                 fc->uni_comp_ref_cdf[i][j], nullptr);
+    for (int i = 0; i < REF_CONTEXTS; ++i)
+      for (int j = 0; j < FWD_REFS - 1; ++j)
+        av1_cost_tokens_from_cdf(mode_costs->comp_ref_cost[i][j],
+                                 fc->comp_ref_cdf[i][j], nullptr);
+    for (int i = 0; i < REF_CONTEXTS; ++i)
+      for (int j = 0; j < BWD_REFS - 1; ++j)
+        av1_cost_tokens_from_cdf(mode_costs->comp_bwdref_cost[i][j],
+                                 fc->comp_bwdref_cdf[i][j], nullptr);
+    for (int i = 0; i < INTRA_INTER_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->intra_inter_cost[i],
+                               fc->intra_inter_cdf[i], nullptr);
+    for (int i = 0; i < NEWMV_MODE_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->newmv_mode_cost[i], fc->newmv_cdf[i],
+                               nullptr);
+    for (int i = 0; i < GLOBALMV_MODE_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->zeromv_mode_cost[i],
+                               fc->zeromv_cdf[i], nullptr);
+    for (int i = 0; i < REFMV_MODE_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->refmv_mode_cost[i], fc->refmv_cdf[i],
+                               nullptr);
+    for (int i = 0; i < DRL_MODE_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->drl_mode_cost0[i], fc->drl_cdf[i],
+                               nullptr);
+    for (int i = 0; i < INTER_MODE_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->inter_compound_mode_cost[i],
+                               fc->inter_compound_mode_cdf[i], nullptr);
+    for (int i = 0; i < BLOCK_SIZES_ALL; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->compound_type_cost[i],
+                               fc->compound_type_cdf[i], nullptr);
+    for (int i = 0; i < BLOCK_SIZES_ALL; ++i) {
+      if (av1_is_wedge_used(static_cast<BLOCK_SIZE>(i)))
+        av1_cost_tokens_from_cdf(mode_costs->wedge_idx_cost[i],
+                                 fc->wedge_idx_cdf[i], nullptr);
+    }
+    for (int i = 0; i < BLOCK_SIZE_GROUPS; ++i) {
+      av1_cost_tokens_from_cdf(mode_costs->interintra_cost[i],
+                               fc->interintra_cdf[i], nullptr);
+      av1_cost_tokens_from_cdf(mode_costs->interintra_mode_cost[i],
+                               fc->interintra_mode_cdf[i], nullptr);
+    }
+    for (int i = 0; i < BLOCK_SIZES_ALL; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->wedge_interintra_cost[i],
+                               fc->wedge_interintra_cdf[i], nullptr);
+    for (int i = BLOCK_8X8; i < BLOCK_SIZES_ALL; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->motion_mode_cost[i],
+                               fc->motion_mode_cdf[i], nullptr);
+    for (int i = BLOCK_8X8; i < BLOCK_SIZES_ALL; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->motion_mode_cost1[i],
+                               fc->obmc_cdf[i], nullptr);
+    for (int i = 0; i < COMP_INDEX_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->comp_idx_cost[i],
+                               fc->compound_index_cdf[i], nullptr);
+    for (int i = 0; i < COMP_GROUP_IDX_CONTEXTS; ++i)
+      av1_cost_tokens_from_cdf(mode_costs->comp_group_idx_cost[i],
+                               fc->comp_group_idx_cdf[i], nullptr);
+  }
+}
+
+void FillCoeffCostsScalar(CoeffCosts *coeff_costs, const FRAME_CONTEXT *fc,
+                          int num_planes) {
+  const int nplanes = AOMMIN(num_planes, PLANE_TYPES);
+  for (int eob_multi_size = 0; eob_multi_size < 7; ++eob_multi_size) {
+    for (int plane = 0; plane < nplanes; ++plane) {
+      LV_MAP_EOB_COST *pcost = &coeff_costs->eob_costs[eob_multi_size][plane];
+      for (int ctx = 0; ctx < 2; ++ctx) {
+        const aom_cdf_prob *pcdf = nullptr;
+        switch (eob_multi_size) {
+          case 0: pcdf = fc->eob_flag_cdf16[plane][ctx]; break;
+          case 1: pcdf = fc->eob_flag_cdf32[plane][ctx]; break;
+          case 2: pcdf = fc->eob_flag_cdf64[plane][ctx]; break;
+          case 3: pcdf = fc->eob_flag_cdf128[plane][ctx]; break;
+          case 4: pcdf = fc->eob_flag_cdf256[plane][ctx]; break;
+          case 5: pcdf = fc->eob_flag_cdf512[plane][ctx]; break;
+          case 6:
+          default: pcdf = fc->eob_flag_cdf1024[plane][ctx]; break;
+        }
+        av1_cost_tokens_from_cdf(pcost->eob_cost[ctx], pcdf, nullptr);
+      }
+    }
+  }
+  for (int tx_size = 0; tx_size < TX_SIZES; ++tx_size) {
+    for (int plane = 0; plane < nplanes; ++plane) {
+      LV_MAP_COEFF_COST *pcost = &coeff_costs->coeff_costs[tx_size][plane];
+      for (int ctx = 0; ctx < TXB_SKIP_CONTEXTS; ++ctx)
+        av1_cost_tokens_from_cdf(pcost->txb_skip_cost[ctx],
+                                 fc->txb_skip_cdf[tx_size][ctx], nullptr);
+      for (int ctx = 0; ctx < SIG_COEF_CONTEXTS_EOB; ++ctx)
+        av1_cost_tokens_from_cdf(pcost->base_eob_cost[ctx],
+                                 fc->coeff_base_eob_cdf[tx_size][plane][ctx],
+                                 nullptr);
+      for (int ctx = 0; ctx < SIG_COEF_CONTEXTS; ++ctx) {
+        av1_cost_tokens_from_cdf(pcost->base_cost[ctx],
+                                 fc->coeff_base_cdf[tx_size][plane][ctx],
+                                 nullptr);
+        pcost->base_cost[ctx][4] = pcost->base_cost[ctx][0];
+        pcost->base_cost[ctx][5] =
+            pcost->base_cost[ctx][1] + av1_cost_literal(1);
+        pcost->base_cost[ctx][6] =
+            pcost->base_cost[ctx][2] + av1_cost_literal(1);
+        pcost->base_cost[ctx][7] =
+            pcost->base_cost[ctx][3] + av1_cost_literal(1);
+      }
+      for (int ctx = 0; ctx < EOB_COEF_CONTEXTS; ++ctx)
+        av1_cost_tokens_from_cdf(pcost->eob_extra_cost[ctx],
+                                 fc->eob_extra_cdf[tx_size][plane][ctx],
+                                 nullptr);
+      for (int ctx = 0; ctx < DC_SIGN_CONTEXTS; ++ctx)
+        av1_cost_tokens_from_cdf(pcost->dc_sign_cost[ctx],
+                                 fc->dc_sign_cdf[plane][ctx], nullptr);
+      if (tx_size <= TX_32X32) {
+        for (int ctx = 0; ctx < LEVEL_CONTEXTS; ++ctx) {
+          int br_rate[BR_CDF_SIZE];
+          int prev_cost = 0;
+          int i;
+          av1_cost_tokens_from_cdf(
+              br_rate, fc->coeff_br_cdf[tx_size][plane][ctx], nullptr);
+          for (i = 0; i < COEFF_BASE_RANGE; i += BR_CDF_SIZE - 1) {
+            for (int j = 0; j < BR_CDF_SIZE - 1; ++j)
+              pcost->lps_cost[ctx][i + j] = prev_cost + br_rate[j];
+            prev_cost += br_rate[BR_CDF_SIZE - 1];
+          }
+          pcost->lps_cost[ctx][i] = prev_cost;
+        }
+      } else {
+        std::memcpy(pcost->lps_cost,
+                    coeff_costs->coeff_costs[TX_32X32][plane].lps_cost,
+                    sizeof(pcost->lps_cost));
+      }
+    }
+  }
+}
+
+template <size_t N>
+void ExpectIntsEqual(const char *name, const int (&ref)[N],
+                     const int (&tst)[N]) {
+  for (size_t i = 0; i < N; ++i)
+    ASSERT_EQ(ref[i], tst[i]) << name << "[" << i << "]";
+}
+
+template <size_t M, size_t N>
+void ExpectIntsEqual(const char *name, const int (&ref)[M][N],
+                     const int (&tst)[M][N]) {
+  for (size_t i = 0; i < M; ++i)
+    for (size_t j = 0; j < N; ++j)
+      ASSERT_EQ(ref[i][j], tst[i][j]) << name << "[" << i << "][" << j << "]";
+}
+
+template <size_t L, size_t M, size_t N>
+void ExpectIntsEqual(const char *name, const int (&ref)[L][M][N],
+                     const int (&tst)[L][M][N]) {
+  for (size_t i = 0; i < L; ++i)
+    for (size_t j = 0; j < M; ++j)
+      for (size_t k = 0; k < N; ++k)
+        ASSERT_EQ(ref[i][j][k], tst[i][j][k])
+            << name << "[" << i << "][" << j << "][" << k << "]";
+}
+
+void ExpectModeCostsEqual(const ModeCosts &ref, const ModeCosts &tst) {
+  ExpectIntsEqual("partition_cost", ref.partition_cost, tst.partition_cost);
+  ExpectIntsEqual("mbmode_cost", ref.mbmode_cost, tst.mbmode_cost);
+  ExpectIntsEqual("y_mode_costs", ref.y_mode_costs, tst.y_mode_costs);
+  ExpectIntsEqual("intra_uv_mode_cost", ref.intra_uv_mode_cost,
+                  tst.intra_uv_mode_cost);
+  ExpectIntsEqual("filter_intra_cost", ref.filter_intra_cost,
+                  tst.filter_intra_cost);
+  ExpectIntsEqual("filter_intra_mode_cost", ref.filter_intra_mode_cost,
+                  tst.filter_intra_mode_cost);
+  ExpectIntsEqual("angle_delta_cost", ref.angle_delta_cost,
+                  tst.angle_delta_cost);
+  ExpectIntsEqual("cfl_cost", ref.cfl_cost, tst.cfl_cost);
+  ExpectIntsEqual("intrabc_cost", ref.intrabc_cost, tst.intrabc_cost);
+  ExpectIntsEqual("palette_y_size_cost", ref.palette_y_size_cost,
+                  tst.palette_y_size_cost);
+  ExpectIntsEqual("palette_uv_size_cost", ref.palette_uv_size_cost,
+                  tst.palette_uv_size_cost);
+  ExpectIntsEqual("palette_y_color_cost", ref.palette_y_color_cost,
+                  tst.palette_y_color_cost);
+  ExpectIntsEqual("palette_uv_color_cost", ref.palette_uv_color_cost,
+                  tst.palette_uv_color_cost);
+  ExpectIntsEqual("palette_y_mode_cost", ref.palette_y_mode_cost,
+                  tst.palette_y_mode_cost);
+  ExpectIntsEqual("palette_uv_mode_cost", ref.palette_uv_mode_cost,
+                  tst.palette_uv_mode_cost);
+  ExpectIntsEqual("skip_mode_cost", ref.skip_mode_cost, tst.skip_mode_cost);
+  ExpectIntsEqual("newmv_mode_cost", ref.newmv_mode_cost, tst.newmv_mode_cost);
+  ExpectIntsEqual("zeromv_mode_cost", ref.zeromv_mode_cost,
+                  tst.zeromv_mode_cost);
+  ExpectIntsEqual("refmv_mode_cost", ref.refmv_mode_cost, tst.refmv_mode_cost);
+  ExpectIntsEqual("drl_mode_cost0", ref.drl_mode_cost0, tst.drl_mode_cost0);
+  ExpectIntsEqual("single_ref_cost", ref.single_ref_cost, tst.single_ref_cost);
+  ExpectIntsEqual("comp_inter_cost", ref.comp_inter_cost, tst.comp_inter_cost);
+  ExpectIntsEqual("comp_ref_type_cost", ref.comp_ref_type_cost,
+                  tst.comp_ref_type_cost);
+  ExpectIntsEqual("uni_comp_ref_cost", ref.uni_comp_ref_cost,
+                  tst.uni_comp_ref_cost);
+  ExpectIntsEqual("comp_ref_cost", ref.comp_ref_cost, tst.comp_ref_cost);
+  ExpectIntsEqual("comp_bwdref_cost", ref.comp_bwdref_cost,
+                  tst.comp_bwdref_cost);
+  ExpectIntsEqual("intra_inter_cost", ref.intra_inter_cost,
+                  tst.intra_inter_cost);
+  ExpectIntsEqual("inter_compound_mode_cost", ref.inter_compound_mode_cost,
+                  tst.inter_compound_mode_cost);
+  ExpectIntsEqual("compound_type_cost", ref.compound_type_cost,
+                  tst.compound_type_cost);
+  ExpectIntsEqual("wedge_idx_cost", ref.wedge_idx_cost, tst.wedge_idx_cost);
+  ExpectIntsEqual("interintra_cost", ref.interintra_cost, tst.interintra_cost);
+  ExpectIntsEqual("wedge_interintra_cost", ref.wedge_interintra_cost,
+                  tst.wedge_interintra_cost);
+  ExpectIntsEqual("interintra_mode_cost", ref.interintra_mode_cost,
+                  tst.interintra_mode_cost);
+  ExpectIntsEqual("comp_idx_cost", ref.comp_idx_cost, tst.comp_idx_cost);
+  ExpectIntsEqual("comp_group_idx_cost", ref.comp_group_idx_cost,
+                  tst.comp_group_idx_cost);
+  ExpectIntsEqual("motion_mode_cost", ref.motion_mode_cost,
+                  tst.motion_mode_cost);
+  ExpectIntsEqual("motion_mode_cost1", ref.motion_mode_cost1,
+                  tst.motion_mode_cost1);
+  ExpectIntsEqual("switchable_interp_costs", ref.switchable_interp_costs,
+                  tst.switchable_interp_costs);
+  ExpectIntsEqual("skip_txfm_cost", ref.skip_txfm_cost, tst.skip_txfm_cost);
+  ExpectIntsEqual("tx_size_cost", ref.tx_size_cost, tst.tx_size_cost);
+  ExpectIntsEqual("txfm_partition_cost", ref.txfm_partition_cost,
+                  tst.txfm_partition_cost);
+  ExpectIntsEqual("inter_tx_type_costs", ref.inter_tx_type_costs,
+                  tst.inter_tx_type_costs);
+  for (int s = 0; s < EXT_TX_SETS_INTRA; ++s) {
+    ExpectIntsEqual("intra_tx_type_costs", ref.intra_tx_type_costs[s],
+                    tst.intra_tx_type_costs[s]);
+  }
+  ExpectIntsEqual("switchable_restore_cost", ref.switchable_restore_cost,
+                  tst.switchable_restore_cost);
+  ExpectIntsEqual("wiener_restore_cost", ref.wiener_restore_cost,
+                  tst.wiener_restore_cost);
+  ExpectIntsEqual("sgrproj_restore_cost", ref.sgrproj_restore_cost,
+                  tst.sgrproj_restore_cost);
+  ExpectIntsEqual("tmp_pred_cost", ref.tmp_pred_cost, tst.tmp_pred_cost);
+  ExpectIntsEqual("spatial_pred_cost", ref.spatial_pred_cost,
+                  tst.spatial_pred_cost);
+  ASSERT_EQ(ref.intra_only_skipped_inter_costs,
+            tst.intra_only_skipped_inter_costs);
+  ASSERT_EQ(ref.intra_only_skipped_inter_tx_type,
+            tst.intra_only_skipped_inter_tx_type);
+}
+
+void ExpectCoeffCostsEqual(const CoeffCosts &ref, const CoeffCosts &tst) {
+  for (int i = 0; i < 7; ++i)
+    for (int p = 0; p < PLANE_TYPES; ++p)
+      ExpectIntsEqual("eob_cost", ref.eob_costs[i][p].eob_cost,
+                      tst.eob_costs[i][p].eob_cost);
+  for (int t = 0; t < TX_SIZES; ++t) {
+    for (int p = 0; p < PLANE_TYPES; ++p) {
+      const LV_MAP_COEFF_COST &r = ref.coeff_costs[t][p];
+      const LV_MAP_COEFF_COST &c = tst.coeff_costs[t][p];
+      ExpectIntsEqual("txb_skip_cost", r.txb_skip_cost, c.txb_skip_cost);
+      ExpectIntsEqual("base_eob_cost", r.base_eob_cost, c.base_eob_cost);
+      ExpectIntsEqual("base_cost", r.base_cost, c.base_cost);
+      ExpectIntsEqual("eob_extra_cost", r.eob_extra_cost, c.eob_extra_cost);
+      ExpectIntsEqual("dc_sign_cost", r.dc_sign_cost, c.dc_sign_cost);
+      ExpectIntsEqual("lps_cost", r.lps_cost, c.lps_cost);
+    }
+  }
+}
+
+TEST_F(CostTokensFromCdf4Test, FillModeAndCoeffCostsParity) {
+  ACMRandom rnd(ACMRandom::DeterministicSeed());
+  auto cm = std::make_unique<AV1_COMMON>();
+  auto seq_params = std::make_unique<SequenceHeader>();
+  auto fc = std::make_unique<FRAME_CONTEXT>();
+  auto ref_mode_costs = std::make_unique<ModeCosts>();
+  auto tst_mode_costs = std::make_unique<ModeCosts>();
+  auto ref_coeff_costs = std::make_unique<CoeffCosts>();
+  auto tst_coeff_costs = std::make_unique<CoeffCosts>();
+
+  for (int use_default : { 1, 0 }) {
+    std::memset(cm.get(), 0, sizeof(*cm));
+    std::memset(seq_params.get(), 0, sizeof(*seq_params));
+    cm->seq_params = seq_params.get();
+    cm->fc = fc.get();
+    if (use_default) {
+      std::memset(fc.get(), 0, sizeof(*fc));
+      cm->quant_params.base_qindex = 100;
+      av1_default_coef_probs(cm.get());
+      av1_init_mode_probs(fc.get());
+    } else {
+      PopulateRandomFrameContext(&rnd, fc.get());
+    }
+
+    // Inter frame with skip_mode and filter_intra enabled.
+    cm->current_frame.frame_type = INTER_FRAME;
+    cm->current_frame.skip_mode_info.skip_mode_flag = 1;
+    seq_params->enable_filter_intra = 1;
+    cm->features.allow_screen_content_tools = 0;
+    cm->features.allow_intrabc = 0;
+    std::memset(ref_mode_costs.get(), 0x5A, sizeof(*ref_mode_costs));
+    std::memset(tst_mode_costs.get(), 0x5A, sizeof(*tst_mode_costs));
+    FillModeRatesScalar(cm.get(), ref_mode_costs.get(), fc.get());
+    API_REGISTER_STATE_CHECK(
+        av1_fill_mode_rates(cm.get(), tst_mode_costs.get(), fc.get()));
+    ExpectModeCostsEqual(*ref_mode_costs, *tst_mode_costs);
+
+    // Keyframe with intrabc enabled and filter_intra/skip_mode disabled.
+    cm->current_frame.frame_type = KEY_FRAME;
+    cm->current_frame.skip_mode_info.skip_mode_flag = 0;
+    seq_params->enable_filter_intra = 0;
+    cm->features.allow_screen_content_tools = 1;
+    cm->features.allow_intrabc = 1;
+    std::memset(ref_mode_costs.get(), 0x5A, sizeof(*ref_mode_costs));
+    std::memset(tst_mode_costs.get(), 0x5A, sizeof(*tst_mode_costs));
+    FillModeRatesScalar(cm.get(), ref_mode_costs.get(), fc.get());
+    API_REGISTER_STATE_CHECK(
+        av1_fill_mode_rates(cm.get(), tst_mode_costs.get(), fc.get()));
+    ExpectModeCostsEqual(*ref_mode_costs, *tst_mode_costs);
+
+    // Keyframe with intrabc disabled (verifies inter_tx_type_costs and
+    // intrabc_cost stay untouched).
+    cm->features.allow_intrabc = 0;
+    std::memset(ref_mode_costs.get(), 0x5A, sizeof(*ref_mode_costs));
+    std::memset(tst_mode_costs.get(), 0x5A, sizeof(*tst_mode_costs));
+    FillModeRatesScalar(cm.get(), ref_mode_costs.get(), fc.get());
+    API_REGISTER_STATE_CHECK(
+        av1_fill_mode_rates(cm.get(), tst_mode_costs.get(), fc.get()));
+    ExpectModeCostsEqual(*ref_mode_costs, *tst_mode_costs);
+
+    for (const int num_planes : { 1, MAX_MB_PLANE }) {
+      std::memset(ref_coeff_costs.get(), 0x5A, sizeof(*ref_coeff_costs));
+      std::memset(tst_coeff_costs.get(), 0x5A, sizeof(*tst_coeff_costs));
+      FillCoeffCostsScalar(ref_coeff_costs.get(), fc.get(), num_planes);
+      API_REGISTER_STATE_CHECK(
+          av1_fill_coeff_costs(tst_coeff_costs.get(), fc.get(), num_planes));
+      ExpectCoeffCostsEqual(*ref_coeff_costs, *tst_coeff_costs);
+    }
+  }
+}
+
 }  // namespace