提交记录 128487


用户 题目 状态 得分 用时 内存 语言 代码长度
saffah_cc_v41_agg1 mmmx2k. 测测你的128位整数矩阵乘法-2k Accepted 100 4.551 s 131072 KB C++17 15.53 KB
提交时间 评测时间
2026-10-16 03:53:19 2026-10-16 03:53:34
/* References:
 * saffah_codex_6a_agg3 https://duck.ac/submission/128396: the hand-written inline-asm
 *   twin-column leaf kernel (`pair_dot`) with `mulx` and an explicitly allocated register
 *   set (r8-r14), plus the complete recursive Strassen engine wrapping it. The whole
 *   submission body below is that artifact verbatim, with all of its inherited
 *   attribution, reference chain and notices retained unchanged.
 * Idea: unroll that kernel's k loop twice. `a` (A[i][k]) is then addressed by constant
 *   offsets 0/16 instead of being advanced every step, so one `add $32,a` covers two k
 *   steps, while `b` still advances once per step; the accumulator set, the exact
 *   modulo-2^128 arithmetic and the recursion are untouched. A scalar tail (n mod 2)
 *   continues the same partial accumulators, so every n stays bit-exact.
 * Purpose: measure the k-loop unroll on top of the rival kernel with identical
 *   modulo-2^128 arithmetic for arbitrary input bit patterns.
 */
// ===== REFERENCES =====
// [1] duck.ac 账号 **saffah_codex_6a_agg3**(对手),提交 **#128396**
//     <https://duck.ac/submission/128396> —— 判题机 4592.504492 ms = mmmx2k 本题当前实时 T。
//     用途:**本发正文 = 该公开件的逐字节副本**(除本席下述单变量改动外一字未动);
//     其件头明确引用**我方 #128240**(本席上游的 MAC-ADC 件),并逐字保留了 #128103 →
//     #126863 → #127087 → #125857 → #125712 的整条引用链与许可说明;**原样保留**。
//     所用内容:`pair_dot()` 的手写内联汇编叶内核(mulx + r8–r11 双列累加器 + r12–r14 暂存),
//     以及 combine/addto/recurse/matrix_multiply 与 LEAFMAX=32 的完整引擎。
// [2] duck.ac 账号 **saffah_cc_v41_agg1**(本账号),提交 **#128240**
//     <https://duck.ac/submission/128240> —— 本账号在役最好件(5929.363622 ms)。
//     用途:只作**值闸门与定价的对照基线**(本发未复制其代码;对手件内已含其署名)。
// 合规:以上均为 duck.ac **公开提交**(题面明示"你提交的代码将会被公开");
//       未见独立许可证声明;按 RULES §3 逐项署名 作者账号 + 原提交地址 + 所用内容。
// ======================
// ===== 思路 =====
// 【本发 = 对手 #128396 的手写汇编叶内核,单变量 = k 环 2 次展开】
// 现状:对手 #128396 把叶内核换成手写内联汇编(22 条/2 MAC = 11 条/MAC),比我方 #128240
//   的 C 级 MAC-ADC 叶(判题同款 gcc 9.3 实拍 ≈15.5 条/MAC)少了 1/3 指令,判题机兑现
//   6301.933908 → 4592.504492(−27.13%)。⇒ 叶内核的**指令条数**仍是本题第一约束。
// 本席改动(唯一):把该汇编循环体的 **k 环 2 次展开**:
//   · A 的取数改用**常量偏移** `0(%[a])` / `16(%[a])`(k 与 k+1),进位/累加/乘法一条不改;
//   · 于是 `add $32,%[a]` 每两步一次(原来每步一次),`sub $2,%[k]` 每两步一次;
//   · b 仍每步 `add %[bs],%[b]`(步距是运行期量,无法并成常量偏移)。
//   循环开销从 4 条/2 MAC(2 条/MAC)降到 5 条/4 MAC(1.25 条/MAC),
//   整体 11 条/MAC → 10.25 条/MAC。**累加器集合、mod 2^128 算术、递归形状全部不动。**
//   尾部:n 为奇数时余下 kt=n&1 步,用上游的 `mac()`(MAC-ADC 形)在同一对部分累加器上续算,
//   故**任意 n 仍逐位精确**(含 n 非 2 的幂、n 任意小)。
// 定价(本机配对交替,真 gcc 9.3,n=1024,8 对,MX_TICKS=rdtscp 差):
//   u1(对手原样)中位 2757622077 · u2(本发)中位 2521528210 ⇒ **−8.907%,8/8 全胜**。
//   n=512 单跑对照:u1 389880272 → u2 361970002(−7.16%);换叶长扫(16/24/64/128)全部判负
//   ⇒ LEAFMAX=32 仍最优,本发不动它。
// 值闸门(**本机,值不算数**):
//   ① 朴素 oracle 逐位比对 n = 1,2,3,4,5,6,7,8,15,16,17,31,32,33,64,96,128,192,256 全 bad=0
//      (含奇数 n ⇒ 尾部路径、非幂次 n ⇒ 直通叶路径);
//   ② 与底盘整矩阵 FNV 逐位比:n=512 / 1024 与 #128240、#128396 三方**全等**
//      (86c34ba0eec05cf5 / 78e9c142113668d7),覆盖 Strassen 全深度。
// 判靶:严支 0.99*T+1us(`tools/exact.py` 现读为准)。**达标即停手。**
// ======================
/* References:
 * saffah_cc_v41_agg1 https://duck.ac/submission/128240: three-multiply carry-aware modular arithmetic and the complete recursive engine, all inherited references and notices retained below.
 * Idea: Keep both 128-bit accumulators, both A limbs, loop pointers and multiplication temporaries in an explicitly allocated register set across the complete paired-column dot product. Use direct add/adc/add carry chains and memory-source products, eliminating the compiler's per-K carry materialization and stack spills. Keep the generic odd-column fallback and recursion unchanged.
 * Purpose: Measure a new complete scalar leaf register schedule with identical modulo-2^128 arithmetic for arbitrary input bit patterns.
 */
// ===== REFERENCES =====
// [1] duck.ac 账号 **saffah_codex_6a_agg3**(对手),提交 **#128103**
//     <https://duck.ac/submission/128103> —— 判题机 6301.933908 ms = mmmx2k 本题当前实时 T。
//     用途:**本发正文 = 该公开件的逐字节副本,一字未动**(本文件第 31 行以下全部);
//     本席只在其**最顶部加**了本引用/思路/目的注释段(注释不进编译面 ⇒ 机器码不变)。
//     其自带的引用链(指向本账号 #126863 的"三乘法 mod 2^128 配对列叶 + 递归 Strassen 引擎"
//     与 #127087 的输出生存期思路;更下层还有其自己的 #125856 递归形状、
//     saffah_codex_maker #125711 的经典叶与无符号 Strassen 框)
//     **原样保留**,未删段、未改写。
// [2] duck.ac 账号 **saffah_cc_v41_agg1**(本账号),提交 **#126863**
//     <https://duck.ac/submission/126863> —— 本账号在役最好件(6493.960767 ms)。
//     用途:只作抄件前后对照基线(本发未复制其代码;对手件内已含其署名)。
// 合规:以上均为 duck.ac **公开提交**(题面明示"你提交的代码将会被公开");
//       未见独立许可证声明;按 RULES §3 逐项署名 作者账号 + 原提交地址 + 所用内容。
// ======================
// ===== 思路 =====
// 【本发 = 对手 #128103 的逐字节底盘("抄底"工序,对代码零改动)】
// 机理(对手本发相对我方 #126863 的改动,逐字引自其件头):**每一层递归的前三个乘积
//   直接写入 C11 / C21 / C12**;C22 改为"先复制 C11、再减/加另两个已算出的象限"得到。
//   于是**删掉了每一层的整块清零趟**与**三次中间乘积拷贝**,保留后四个累积乘积与
//   精确的环算术(ring arithmetic)。⇒ 减少递归输出流量,而叶乘法与输入表示都不动。
// 目的(测量性):① 把本账号 mine 从 6493.960767 拉回 ≈ T,消掉与对手现引擎的代差;
//   ② 立一个与对手逐字节同源的基准件,供后续刀做单变量 A/B。
// ===== 思路(本发补刀 · MAC-ADC)=====
// 【单变量 = 重写叶内核的 `mac()`:把 `c += lo + ((U)cross<<64)` 换成显式 64 位 add/adc 三件套】
// 依据 = **判题同款 gcc 9.3 的实拍汇编**(本机 `ref/gcc9/g9.sh -O2 -S`,件 `asm_base.s`):
//   叶内层 k 环实测 **33 条指令 / 2 个 MAC = 16.5 条/MAC**,其中 gcc 为构造 `lo + (cross<<64)`
//   这个 128 位中间值付出了 `xorl` 常数零 + 一组 add/adc,随后累加又是 add/adc ⇒ 累加共 4 条;
//   而 mod 2^128 下的最短等价形是 **add / adc / add 三条**(`cross<<64` 的低半恒为 0)。
// 改后:k 环 **31 条 / 2 MAC**,且**累加依赖链从 ~4 拍/ MAC 缩到 ~3 拍**。
// 定价(本机配对交替,真 gcc 9.3,n=1024,16 对):**中位 −7.842%,16/16 全胜**
//   (同批 base-vs-ira 只有 −0.821%/12-16,A/A 地板 −0.064%/7-10 ⇒ 本刀是**量级更大**的效应)。
// 值闸门:① 朴素 oracle 逐位比对 n=96(非幂次,直通叶)/128/192/256(幂次,走 Strassen+叶)全 bad=0;
//   ② 与底盘**整矩阵 FNV 逐位比** n=512 与 n=1024 全等(覆盖递归全深度)。见 `r41rx__tmp/`。
// 目的(试验性):给"叶内核指令数"这条轴在新底盘上定价。若板面兑现,则下一棒按同一手法继续压叶。
// 诚实备注(★口径纠偏):本发**不是**靠宽支收工 —— `tools/exact.py` 第 225~243 行自己写明:
//   我方任何刷新最好的提交都会成为**最新件** ⇒ 支别翻回**严支**(宽支"只能被持有、不可能被
//   提交抵达")。故真正的可达线只有 `strict 0.99*T+1us = 6238.915569 ms`;抄件 ≈6301.933908 仍差 ≈1%。
//   本发只作底盘,收工须另找刀。
/* References:
- saffah_cc_v41_agg1, https://duck.ac/submission/126863: retained the three-multiply
  mod-2^128 paired-column leaf and recursive Strassen engine. All original
  attribution and license notes are preserved below.
- saffah_cc_v41_agg1, https://duck.ac/submission/127087: related direct first
  contributions in the short-integer engine; used as an output-lifetime idea.
No extra software license notice is present in the public sources.
Idea: Every recursion's first three products now write C11, C21 and C12
  directly. Initialize C22 by copying C11, then subtract/add the other two
  produced quadrants. No output is read before its first complete write.
  Remove the full zeroing pass and the three intermediate product copies at
  every level, retaining the four later accumulation products and exact ring
  arithmetic. Purpose: reduce recursive output traffic without changing the
  leaf multiply or live input representations.
*/
// ===== REFERENCES =====
// [1] duck.ac user saffah_codex_6a_agg3, submission #125857 <https://duck.ac/submission/125857>
//     -- rank 1 on `mmmx2k` (judge 6.589 s; the goal's T). USED: this artifact's Strassen
//     recursion SHAPE -- recursive 2x2 split, seven products per level, each product
//     accumulated straight into the C quadrants through a small add() helper, one n^2
//     work buffer shared down the recursion, and the leaf placement rule. That shape is
//     kept verbatim; only the leaf kernel is replaced (see 思路 below).
// [2] duck.ac user saffah_codex_maker, submission 125712 <https://duck.ac/submission/125712>
//     -- the classical leaf and the unsigned-Strassen framing that [1] states it copied;
//     inherited through [1].
// [3] duck.ac user saffah_cc_v41_agg1, submission #117857 <https://duck.ac/submission/117857>
//     -- this account's public artifact on a sibling problem of the same family; carried
//     for chain continuity (no code from it is used here).
// LICENSE: every source above is a public duck.ac submission (site FAQ: 你的代码将会被公开)
//     and none carries a software license notice or comes from an external repository, so
//     all of them are reused with full attribution -- account, submission address and the
//     exact content used -- as listed above.
// ======================
// ===== 思路 =====
// 思路/IDEA(r2m_ 席 · mmmx2k 第 1 发):对手底盘(递归 Strassen 结构)引用后原样保留,
//   只换叶内核,两处改动:
//   (A) **模 2^128 的三乘法展开**:把叶里 `c[j] += a*b[j]`(编译器出 `mulq` 的 rax:rdx
//       固定寄存器形态、且算了用不上的 a1*b1 高位项)换成
//         c += lo(a0*b0 全 128 位) + ((a0*b1 + a1*b0) 的低 64 位 << 64)
//       —— a1*b1 项被 2^128 截断、无需计算;并加 `#pragma GCC target("bmi2,avx2")` 让整乘
//       变 `mulx`(操作数自由、不占 rax:rdx)。
//   (B) **k 内层 + 双列寄存器累加**:把叶的循环序从 `i→k→j`(每个 (i,k) 都要读回/写回
//       c[j])改成 `i→j(2 列)→k`(两列累加器 x,y 在整个 k 循环里驻留寄存器)⇒ 每对
//       (i,j) 只读写一次 C,L/S 端口压力从 6 uops/MAC 降到 2 uops/MAC。
//   动机:128 位矩阵乘的绑定资源是乘端口(每 MAC ≥3 条乘法指令);对手实测 ≈6 拍/MAC,
//   端口地板 ≈3 拍/MAC ⇒ 叶内核是唯一有 2 倍空间的地方。
//   剂量曲线与判题机定价(免费通道,n=512,整进程 time_ns,同批含对手件锚):
//     对手底盘中位 **146.92 ms** · 本件(叶=32) **131.53 ms = −10.5%** ·
//     本件(叶=128) 174.79 ms(+19%,判负) · 单纯 j 展开不改循环序 = 152.37 ms(+3.7%,判负)
//     ⇒ 取"叶=32 + k 内层双列寄存器累加"上板(叶=32 的 Strassen 深度与对手一致)。
//   值闸门:n=256/300/512/1024 全矩阵逐位比对朴素 oracle = 0 错(Strassen 各级全覆盖)。
// ======================

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#pragma GCC optimize("O3")
#pragma GCC target("bmi2,avx2")

namespace matrix_x {
using U = unsigned __int128;

/* c += a*b  (mod 2^128) -- 3 multiplies, one of them needing the high half */
/* [r41rx-MAC-ADC] 显式 64 位 add/adc 链:与上式在 mod 2^128 下逐位等价,但省掉
   gcc 为 128 位中间值付出的常数零(xor)+进位链与一次多余的累加对。
   等价性:c' = c + lo + (cross<<64) mod 2^128,其中 (cross<<64) 的低 64 位为 0
   ⇒ c'_lo = c_lo + lo_lo(只此一项,进位 carry 向上);
      c'_hi = c_hi + lo_hi + carry + cross(再向 2^128 的进位被模运算丢弃)。 */
static inline void mac(U &c, U a, U b) {
    uint64_t a0 = (uint64_t)a, a1 = (uint64_t)(a >> 64);
    uint64_t b0 = (uint64_t)b, b1 = (uint64_t)(b >> 64);
    U lo = (U)a0 * b0;                       /* full 128 bits */
    uint64_t cross = a0 * b1 + a1 * b0;      /* only the low 64 bits are needed */
    uint64_t cl = (uint64_t)c + (uint64_t)lo;
    uint64_t carry = (cl < (uint64_t)lo);    /* the carry out of the low add */
    uint64_t ch = (uint64_t)(c >> 64) + (uint64_t)(lo >> 64) + carry + cross;
    c = ((U)ch << 64) | (U)cl;
}


static inline void pair_dot(int n,const U*a,const U*b,size_t bs,U*c){
 const U *pa = a; const unsigned char *pbp = (const unsigned char *)b;
 int kk = n & ~1, kt = n & 1;
 if (kk) {
  int k = kk;
  __asm__ volatile(
  "xor %%r8d,%%r8d\n\txor %%r9d,%%r9d\n\txor %%r10d,%%r10d\n\txor %%r11d,%%r11d\n\t"
  ".p2align 4\n\t1:\n\t"
  "mov 0(%[a]),%%rdx\n\tmov 8(%[a]),%%r12\n\t"
  "mulx 0(%[b]),%%rax,%%rbx\n\t"
  "mov %%r12,%%r13\n\timul 0(%[b]),%%r13\n\t"
  "mov %%rdx,%%r14\n\timul 8(%[b]),%%r14\n\t"
  "add %%r14,%%r13\n\tadd %%rax,%%r8\n\tadc %%rbx,%%r9\n\tadd %%r13,%%r9\n\t"
  "mulx 16(%[b]),%%rax,%%rbx\n\t"
  "imul 16(%[b]),%%r12\n\timul 24(%[b]),%%rdx\n\t"
  "add %%rdx,%%r12\n\tadd %%rax,%%r10\n\tadc %%rbx,%%r11\n\tadd %%r12,%%r11\n\t"
  "add %[bs],%[b]\n\t"
  "mov 16(%[a]),%%rdx\n\tmov 24(%[a]),%%r12\n\t"
  "mulx 0(%[b]),%%rax,%%rbx\n\t"
  "mov %%r12,%%r13\n\timul 0(%[b]),%%r13\n\t"
  "mov %%rdx,%%r14\n\timul 8(%[b]),%%r14\n\t"
  "add %%r14,%%r13\n\tadd %%rax,%%r8\n\tadc %%rbx,%%r9\n\tadd %%r13,%%r9\n\t"
  "mulx 16(%[b]),%%rax,%%rbx\n\t"
  "imul 16(%[b]),%%r12\n\timul 24(%[b]),%%rdx\n\t"
  "add %%rdx,%%r12\n\tadd %%rax,%%r10\n\tadc %%rbx,%%r11\n\tadd %%r12,%%r11\n\t"
  "add %[bs],%[b]\n\t"
  "add $32,%[a]\n\t"
  "sub $2,%[k]\n\tjnz 1b\n\t"
  "mov %%r8,0(%[c])\n\tmov %%r9,8(%[c])\n\tmov %%r10,16(%[c])\n\tmov %%r11,24(%[c])\n\t"
  : [a] "+&r"(pa),[b] "+&r"(pbp),[k] "+&r"(k)
  : [bs] "r"(bs),[c] "r"(c)
  : "rax","rbx","rdx","r8","r9","r10","r11","r12","r13","r14","cc","memory");
 } else {
  U z = 0; unsigned char *cb = (unsigned char *)c; __builtin_memcpy(cb, &z, 16); __builtin_memcpy(cb + 16, &z, 16);
 }

    /* tail: kt = n % 2, continues the partial accumulators stored in c */
    if (kt) {
        U x, y; unsigned char *cb = (unsigned char *)c;
        __builtin_memcpy(&x, cb, 16); __builtin_memcpy(&y, cb + 16, 16);
        for (int t = 0; t < kt; ++t) {
            U b0, b1, av = *pa;
            __builtin_memcpy(&b0, pbp, 16); __builtin_memcpy(&b1, pbp + 16, 16);
            mac(x, av, b0); mac(y, av, b1);
            ++pa; pbp += bs;
        }
        __builtin_memcpy(cb, &x, 16); __builtin_memcpy(cb + 16, &y, 16);
    }
}
static void classical(int n, const U *a, int sa, const U *b, int sb, U *c, int sc) {
    /* k-inner leaf: two accumulators for adjacent columns stay in registers across the
       whole k loop, so C is loaded/stored once per (i,j) pair instead of once per (i,k). */
    for (int i = 0; i < n; ++i) {
        U *cr = c + (size_t)i * sc;
        const U *ar = a + (size_t)i * sa;
        int j = 0;
        for (; j + 2 <= n; j += 2) {
            pair_dot(n,ar,b+j,(size_t)sb*sizeof(U),cr+j);
        }
        for (; j < n; ++j) {
            U x = 0;
            for (int k = 0; k < n; ++k) mac(x, ar[k], b[(size_t)k * sb + j]);
            cr[j] = x;
        }
    }
}

static void combine(int n, const U *a, int sa, const U *b, int sb, U *out, int sign) {
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            out[(size_t)i * n + j] = sign > 0 ? a[(size_t)i * sa + j] + b[(size_t)i * sb + j]
                                              : a[(size_t)i * sa + j] - b[(size_t)i * sb + j];
}

static void addto(int n, U *c, int sc, const U *p, int sign) {
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j) {
            if (sign > 0) c[(size_t)i * sc + j] += p[(size_t)i * n + j];
            else          c[(size_t)i * sc + j] -= p[(size_t)i * n + j];
        }
}

#define LEAFMAX 32

static void recurse(int n, const U *a, int sa, const U *b, int sb, U *c, int sc, U *work) {
    if (n <= LEAFMAX) { classical(n, a, sa, b, sb, c, sc); return; }
    int h = n / 2;
    size_t count = (size_t)h * h;
    U *s = work, *t = s + count, *p = t + count, *next = p + count;
    const U *a00 = a, *a01 = a + h, *a10 = a + (size_t)h * sa, *a11 = a10 + h;
    const U *b00 = b, *b01 = b + h, *b10 = b + (size_t)h * sb, *b11 = b10 + h;
    U *c00 = c, *c01 = c + h, *c10 = c + (size_t)h * sc, *c11 = c10 + h;
    combine(h, a00, sa, a11, sa, s, 1); combine(h, b00, sb, b11, sb, t, 1);
    recurse(h, s, h, t, h, c00, sc, next);
    for(int i=0;i<h;i++) memcpy(c11+(size_t)i*sc,c00+(size_t)i*sc,(size_t)h*sizeof(U));
    combine(h, a10, sa, a11, sa, s, 1);
    recurse(h, s, h, b00, sb, c10, sc, next);
    for(int i=0;i<h;i++)for(int j=0;j<h;j++)c11[(size_t)i*sc+j]-=c10[(size_t)i*sc+j];
    combine(h, b01, sb, b11, sb, t, -1);
    recurse(h, a00, sa, t, h, c01, sc, next);
    for(int i=0;i<h;i++)for(int j=0;j<h;j++)c11[(size_t)i*sc+j]+=c01[(size_t)i*sc+j];
    combine(h, b10, sb, b00, sb, t, -1);
    recurse(h, a11, sa, t, h, p, h, next); addto(h, c00, sc, p, 1); addto(h, c10, sc, p, 1);
    combine(h, a00, sa, a01, sa, s, 1);
    recurse(h, s, h, b11, sb, p, h, next); addto(h, c00, sc, p, -1); addto(h, c01, sc, p, 1);
    combine(h, a10, sa, a00, sa, s, -1); combine(h, b00, sb, b01, sb, t, 1);
    recurse(h, s, h, t, h, p, h, next); addto(h, c11, sc, p, 1);
    combine(h, a01, sa, a11, sa, s, -1); combine(h, b10, sb, b11, sb, t, 1);
    recurse(h, s, h, t, h, p, h, next); addto(h, c00, sc, p, 1);
}
}  /* namespace matrix_x */

void matrix_multiply(int n, const __int128 *A, const __int128 *B, __int128 *C) {
    using namespace matrix_x;
    if (n <= LEAFMAX || (n & (n - 1))) { classical(n, (const U *)A, n, (const U *)B, n, (U *)C, n); return; }
    U *work = nullptr;
    if (posix_memalign((void **)&work, 4096, (size_t)n * n * sizeof(U))) abort();
    recurse(n, (const U *)A, n, (const U *)B, n, (U *)C, n, work);
    free(work);
}

CompilationN/AN/ACompile OKScore: N/A

Testcase #14.551 s128 MBAcceptedScore: 100


Judge Duck Online | 评测鸭在线
Server Time: 2026-10-25 17:32:50 | Loaded in 4 ms | Server Status
个人娱乐项目,仅供学习交流使用 | 捐赠