SC 侧 Twist
本页所有地址均适用于
libtpu-0.0.40-cp314wheel 中的libtpu.so(build-id89edbbe81c5b328a958fe628a9f2207d,buildlibtpu_lts_20260413_b_RC00)。其他版本会不同。.textVMA 等于文件偏移(基址0xe63c000);所有地址都是 VMA。下面的每个符号都在二进制中带有完整 C++ 名称,并已与 IDA 反编译交叉核对。
摘要
本页记录扭转环面的 SparseCore 侧——重新实现者需要、且 TensorCore twist 页面有意不负责的三个部分:
sparse_core::collective::TwistedTorusTopologyInfo——TensorCoreTwistedTorusND的 embedding-shard 类比物。它接受相同的K/2K几何,使用相同的R = (num-2K-axes ≥ 2) ? 2K : K旋钮和相同的+K-mod-2K接缝,但把 twist 表达为两个可组合的TwistedView对象;这些对象的按轴坐标变换是std::function<long(long,long)>闭包,由共享的ForEachPhasefold engine 应用——而不是两个GetPhaseNReplicaGroups循环嵌套。TwistedTorusND::GetPhase0Cores/GetPhase1Cores——按阶段的 core-count virtual(TensorCoreGetPhaseNReplicaGroups设备列表的仅计数孪生)。GetPhase0Cores = 2K · LogicalDevicesPerChip;GetPhase1Cores = R。Collective-fusion validator 读取它们,以检查 offloaded fusion 的 shard 几何是否匹配 strategy。EstimatePhysicalLinksUsed——物理 ICI 链路估算器。它遍历每个 replica group 的成员芯片坐标,检测该 group 跨越哪些 torus 轴,并返回 collective 穿过的不同方向性IciResource的有序集合(1..6= 3 dims × 2 directions)。其result.size()是 all-to-all / cross-module-all-reduce cost model 用来除带宽的 “links” 除数。
TensorCore 侧 TwistedTorusND 类族(ctor、BuildStrategy、接缝构建器、megacore split)见 BuildStrategy,设备列表阶段见 2-Phase Replica-Group Construction;+K-mod-2K 坐标折叠本身见 GetReplicaPair3DOnTwistedTorus。消费 TwistedTorusTopologyInfo 的 SparseCore offload config emission——ConstructConfigForCollectiveUniDirNDGroups<*> builder 和 *OffloadConfig proto 家族——见 SC-Offload Config Builder。本页负责 SC topology struct、分阶段 view 枚举和物理链路估算器。
二进制中观察到的三个部分的契约:
- 形状 gate。
TryCreateTwistedTorusTopologyInfo只有在max_dim_size % min_dim_size == 0且min_dims.size()与max_dims.size()呈2:1比例时才接受 twisted topology。比例方向是形状判别量:2·|min| == |max|→k_2k_2k,|min| == 2·|max|→k_k_2k。正好两种形状——没有字面nK。 - 两个 view。 每种形状都会从 7 个坐标折叠闭包池中构建两个
TwistedView对象(reduce-scatter view 和 all-gather view),每个闭包都捕获K。 - Fold。
TwistedView::ForEachPhase是固定的 3 轴 fold(CHECK size == 3):对每个轴,它读取一个置换索引,并在(coord_a, coord_b)对上调用匹配的std::function闭包,生成物理TpuDimensions。接缝原语是(⌊j/K⌋·K + i) mod 2K;短轴原语是i mod K。 - 链路计数。
EstimatePhysicalLinksUsed是 topology set walk,不是标量 span 乘积:跨越更多轴 / 同一轴两个方向的 group 会触及更多不同的IciResource,且links = |set|。
一览
| Aspect | Value (byte-anchored) |
|---|---|
| SC topology class | xla::tpu::sparse_core::collective::TwistedTorusTopologyInfo (operator new(0x100)) |
| SC factory | TryCreateTwistedTorusTopologyInfo @0x133e1980 → StatusOr<unique_ptr<…>> |
| SC view builder | ConstructTwistedViews @0x133e1ea0(两个 unique_ptr<TwistedView> push_backs) |
| SC fold engine | TwistedView::ForEachPhase @0x133e17c0(3 轴;CHECK size == 3) |
| SC fold closures | 7 × std::function<long(long,long)>,lambdas 0x133e4ae0..0x133e4dc0 |
| Source TU (SC) | platforms/xla/sparse_core/offload_collective_config_builder.cc |
| Core counts | TwistedTorusND::GetPhase0Cores @0x137d6de0,GetPhase1Cores @0x137d6ec0 |
| Phase0 count | [this+0x5f0] (2K) · LogicalDevicesPerChip(0) |
| Phase1 count | [this + (num2K<2)·8 + 0x5f0] = (num2K ≥ 2 ? 2K : K) = R |
| Source TU (cores) | all_reduce_strategies.h(VLOG lines 792 / 800) |
| Link estimator | xla::jellyfish::EstimatePhysicalLinksUsed @0x1c8939c0 → vector<IciResource> |
| Source TU (links) | group_utils.cc(cross-slice RetCheck line 1652) |
| Link encoding | 6 个 IciResource 1..6 = {X,Y,Z} × {dir0,dir1};GetResourceFromIciResource @0x1c894c00(e-1+0xd → slots 0xd..0x12) |
| Cost consumer | ComputeAllToAllCyclesHelper @0x130d02a0(IciResource → torus-dim extent) |
| Confidence | HIGH(反编译验证了 TryCreate RetCheck 字符串、ForEachPhase CHECK==3 + *0x10 dispatch、GetPhaseNCores 字段算术、6 个 IciResource 插入 + 有序集合返回),除非某行/标注另有说明 |
1. TwistedTorusTopologyInfo——SparseCore twist
SparseCore embedding collective 不拥有 TwistedTorusND。它拥有一个兄弟类型 xla::tpu::sparse_core::collective::TwistedTorusTopologyInfo,该类型描述相同的物理 twist,但接入的是 SparseCore offload-config builder,而不是 dense HLO ReplicaGroup scheduler。它是 Twisted Torus — Section Map §2 中列出的 “twisted torus” 名称碰撞里的第三个成员,也是 SC-Offload Config Builder §6 通过其 cmp $3 K/2K mesh-dim gate 触达的那个类型。
1.1 TryCreateTwistedTorusTopologyInfo——验证 + 形状 gate
// xla::tpu::sparse_core::collective::TwistedTorusTopologyInfo::
absl::StatusOr<std::unique_ptr<TwistedTorusTopologyInfo>>
TryCreateTwistedTorusTopologyInfo(
const std::vector<IciDim>& min_dims, // K-side axes
const std::vector<IciDim>& max_dims, // 2K-side axes
long min_dim_size, // = K
long max_dim_size); // = 2K
```text
Factory body(`@0x133e1980`)在构造任何东西之前应用两个 gate:
```text
TryCreateTwistedTorusTopologyInfo(min_dims, max_dims, K, 2K):
// gate 1 — divisibility (RetCheck line 96):
if (max_dim_size % min_dim_size != 0) // = 2K % K
return RetCheckFail("max_dim_size % min_dim_size == 0")
<< "Found unexpected twisted torus topology where
max_dim_size is not divisible by min_dim_size."
// gate 2 — the 2:1 size ratio (RetCheck line 102):
if (2·min_dims.size() != max_dims.size()
&& min_dims.size() != 2·max_dims.size())
return RetCheckFail("min_dims.size() == 2 * max_dims.size()")
<< "Twisted torus is only for k_2k_2k and k_k_2k topology."
obj = operator new(0x100); TwistedTorusTopologyInfo::ctor(obj) // §1.2
return obj反编译把整除测试拆成 32 位 fast path((2K | K) >> 32 == 0 → 32 位 idiv)和 64 位 idiv fallback;两者都计算 2K % K。Size gate 从 [vector+8] 读取 min_dims.size() 和 max_dims.size()(end 指针减去 begin 后折叠为元素计数),并接受任一比例方向。
两个 RetCheck 字符串在反编译中都是字节精确的:
"max_dim_size % min_dim_size == 0"位于offload_collective_config_builder.cc:96,"min_dims.size() == 2 * max_dims.size()"位于 line 102,两个面向用户的错误消息("Found unexpected … not divisible …"、"Twisted torus is only for k_2k_2k and k_k_2k topology.")各自经由StatusBuilder::operator<<跟随。operator new(0x100u)分配存在。
形状判别量就是比例方向本身:2·|min_dims| == |max_dims| 是 k_2k_2k 形状(两个加倍轴,一个短轴),|min_dims| == 2·|max_dims| 是 k_k_2k 形状(一个加倍轴,两个短轴)。这是它与 routing 侧 TwistedTorusTopology 的唯一区别,后者还处理字面 k_2k_nK(n > 2);SparseCore factory 会拒绝两个 2:1 形状之外的任何内容(这也是 TensorCore TwistedTorusND 通过其 max_dim == 2·min_dim CHECK 强制的同一限制——见 overview §3)。
[LOW] 反编译的
TryCreate只用 object pointer 调用 ctor;shape byte 和(2K, R, K)三元组是在 ctor 内部(@0x133e1b40)填充的,在TryCreate调用点不可见。Ctor 字段布局(§1.2)是根据 ctor body 的工作笔记反汇编重建的,并未在此逐指令重新遍历。比例方向 → 形状映射和R旋钮为 HIGH;三元组精确[this+…]偏移为 MEDIUM。
1.2 对象布局与 (2K, R, K) 三元组
Ctor(@0x133e1b40)构建一个 0x100 字节对象,其活跃区域为:
| Offset | Field | Meaning |
|---|---|---|
+0x00 | vector<IciDim> min_dims | K 侧轴(arg 的 memcpy) |
+0x18 | vector<IciDim> max_dims | 2K 侧轴(arg 的 memcpy) |
+0x30 | long min_dim_size | K |
+0x38 | long max_dim_size | 2K |
+0x40 | ptr → {2K, R, K} | 参数三元组,R = (shape ? 2K : K) |
+0x58 | vector<bool> (3) | “is-doubled-axis” mask |
+0x70 | char shape | 0 = k_k_2k,1 = k_2k_2k |
+0x78..0xe0 | 7 × std::function<long(long,long)> | fold closures(每个捕获 K) |
这里的 R 旋钮与 TensorCore 侧完全相同:R = (num-2K-axes ≥ 2) ? 2K : K。在 TensorCore 侧,它由 [obj+0x5f0]=2K/[obj+0x5f8]=K 并通过 [obj+0x600]=num2K 选择(见 §2 和 overview §3);在 SparseCore 侧,它是由 shape byte 选择 2K 或 K 放入三元组的中间槽。同一几何,只是重新表达。
1.3 ConstructTwistedViews——两个 phase view
ConstructTwistedViews @0x133e1ea0 根据 shape byte 分派,并且对任一形状都会构建两个 TwistedView 对象,push-back 到一个 vector<unique_ptr<TwistedView>> 中——reduce-scatter view 和 all-gather view(SparseCore 对 TensorCore Phase0/Phase1 拆分的类比物)。每个 TwistedView 携带一个 vector<vector<shared_ptr<function<long(long,long)>>>>,内容来自 7 个 ctor 闭包,并携带 is-doubled-axis mask,用于标记该 view 中 3 个轴里哪个轴是加倍(2K)轴。
ConstructTwistedViews(this):
if (shape != 0) build k_2k_2k arm // 2 doubled axes
else build k_k_2k arm // 1 doubled axis
// each arm:
push_back( TwistedView{ reduce-scatter coordinate folds } ) // view 0
push_back( TwistedView{ all-gather coordinate folds } ) // view 1
```text
> 反编译显示两个 `vector<unique_ptr<TwistedView>>::push_back` 位置(`@0x133e1ea0` body,约 lines 1300 和 1542)。两个 view 携带 `std::function<TpuDimensions(TpuDimensions)>` 闭包存储:第一个 view 安装 `ConstructTwistedViews()::$_0`(`@0x133e6160`)和 `ConstructTwistedViews()::$_1`(`@0x133e6180`);第二个安装 forward/inverse 对 `TwistedView::SetToTwistedCoordinates::$_0`(`@0x133e4140`)和 `TwistedView::SetToOriginalCoordinates::$_0`(`@0x133e4580`)。两 view 结构和 shape dispatch 已字节确认。存在与 `SetToTwistedCoordinates` 配对的 `SetToOriginalCoordinates`,这与 `$_4` 是 `$_1` 接缝的*逆*(§1.5)相符。
>
> **[LOW]** 对每种形状,7 个 fold closure 中**哪个**填入两个 view 的三个 axis-group 中的**哪个**,已追踪到夹杂 `shared_ptr` refcounting 的构造顺序,但尚未归约为按 `(shape, view, group)` 的 composition table。两个 view 的 `{2,3,3}` group 结构和 7 个原语的闭式形式(§1.5)是字节精确的,但类似 TensorCore “Phase0 uses fold $_1/$_3/$_2; Phase1 uses $_5/$_4/$_6” 的 assignment table 仍未完成。解码它就能以闭式形式重建任意 `(logical group, member)` 的 SparseCore 物理坐标,即 SparseCore 版 [GetReplicaPair3DOnTwistedTorus](get-replica-pair-3d.md) 坐标表。
### 1.4 `TwistedView::ForEachPhase`——3 轴 fold engine
```cpp
// xla::tpu::sparse_core::collective::TwistedView::
TpuDimensions ForEachPhase(
TpuDimensions dims,
std::vector<std::shared_ptr<std::function<long(long,long)>>> transform,
int phase);ForEachPhase @0x133e17c0 是 TensorCore 坐标折叠的 SparseCore 等价物——它通过应用三个按轴 fold closure,把逻辑 TpuDimensions 映射到物理 TpuDimensions:
ForEachPhase(dims, transform, phase):
out = TpuDimensions{} // new(0xC) = 3 × int32
CHECK dim_per_phase_.size() == transform.size() // fatal, line 77
CHECK dim_per_phase_.size() == 3 // fatal, line 78
for axis i in [0, 3):
a = dim_per_phase_[i] // permutation index, < 3
b = dim_per_phase_[phase] // the phase column index, < 3
out[a] = (*transform[i])(dims[a], dims[b]) // call *(fn+0x10): std::function invoker
return out
```text
闭包通过 `*(transform[i] + 0x10)`——`std::function` call-operator slot——调用,两个源坐标为 `dims[a]` 和 `dims[b]`。固定的 `== 3` rank 是 TensorCore `num_max_dims == 2` / 3-D twist 不变量的 SparseCore 对应物([get-replica-pair-3d.md](get-replica-pair-3d.md) §2)。`TwistedView::SetToTwistedCoordinates::$_0`(`@0x133e4140`)克隆 fold list,并为每个 phase 驱动一次 `ForEachPhase`;`SetToOriginalCoordinates::$_0`(`@0x133e4580`)是其逆向配对。
> 反编译显示输入 clone 和输出都使用 `new(0xCu)`(12 字节 `TpuDimensions`),两个 fatal `CHECK`(`"dim_per_phase_.size() == transform.size()"` line 77,`"dim_per_phase_.size() == 3"` line 78,均为 `offload_collective_config_builder.cc` 中的 `LogMessageFatal`),带 `< 3` 边界检查的 3 次迭代循环,以及 `*(transform[i] + 16)(obj, dims[a], dims[b])` 间接调用。原始工作笔记的十六进制行标记 `0x4d`/`0x4e` 是十进制 `77`/`78`——一致。
### 1.5 7 个 fold 原语
每个闭包都是捕获 `K` 的 `operator()(long i, long j)`,其中 `i` 是**第一个**参数,`j` 是**第二个**参数(分别对应 `ForEachPhase` 中的 `dims[a]` 和 `dims[b]`)。下面的闭式形式遵循这一约定,并已逐个 `$_N` body 字节验证:
| Closure | Address | Closed form | Role |
|---------|---------|-------------|------|
| `$_1` | `0x133e4ae0` | `(⌊j/K⌋·K + i) mod 2K` | `+K`-mod-`2K` twist 接缝(forward) |
| `$_2` | `0x133e4b80` | `i mod K` | 短 `K` 轴坐标(只使用 `i`) |
| `$_3` | `0x133e4bc0` | `⌊j/K⌋·K + i` | 长轴 base `+ i` |
| `$_4` | `0x133e4c40` | `(i − ⌊j/K⌋·K) mod 2K` | 逆接缝(`$_1` 的 `−⌊j/K⌋·K` 对应物) |
| `$_5` | `0x133e4d00` | `⌊j/K⌋·K + i` | `= $_3` |
| `$_6` | `0x133e4d80` | `i mod K` | `= $_2`(只使用 `i`) |
| `$_7` | `0x133e4dc0` | `i` | identity(返回第一个参数) |
接缝原语 `$_1` 是 TensorCore `+K`-mod-`2K` fold 的精确 SparseCore 重述([overview](overview.md) §1,[get-replica-pair-3d.md](get-replica-pair-3d.md) §3):沿短 `K` 轴行走,沿长轴跳 `+K`,第二次沿 `K` 轴行走——也就是切断加倍环上循环依赖的日期线。`$_4` 是它的逆:相同的 `⌊j/K⌋·K` 步长被减去而不是加上,并带有 `(… mod 2K + 2K) mod 2K` 非负余数修正。`⌊j/K⌋` floor division 是标准的符号正确截断商惯用法(`idiv K` 后接 `(rem != 0 && signs differ) ? -1` 进位修正)。
---
## 2. 按阶段 core count——`GetPhase0Cores` / `GetPhase1Cores`
`TwistedTorusND::GetPhase0Cores` 和 `GetPhase1Cores` 是 **TensorCore** strategy class(`TwistedTorusND` vtable `0x219242a0`,slots `+0x50`/`+0x58`)上的 vtable virtual,但它们回答一个与 SparseCore 相关的问题:**一个阶段的环/平面触及多少个 core?** 它们是 `GetPhaseNReplicaGroups` 设备列表的仅计数孪生([2-Phase Replica-Group Construction](replica-group-2phase.md)),offload-collective fusion validator 读取它们,以检查 offloaded fusion 的 shard 几何是否匹配 strategy。
两者都先调用 `UpdateMinMaxDims`(`K`/`2K` 分类器;[overview](overview.md) §3)以填充 `[obj+0x5f0]=2K`、`[obj+0x5f8]=K`、`[obj+0x600]=num2K`,随后索引这三个字段。
### 2.1 `GetPhase0Cores = 2K · LogicalDevicesPerChip`
```text
GetPhase0Cores(target, device_assign):
UpdateMinMaxDims(target)
v10 = *((long*)this + 190) // [this+0x5f0] = 2K
result = v10 * Target::LogicalDevicesPerChip(target, 0)
VLOG(1) "GetPhase0Cores: " << result // all_reduce_strategies.h:792
return resultLogicalDevicesPerChip(0) 在 megacore 模式下为 1,否则为物理 core count(见 SC-Offload Config Builder §2.1)。因此 Phase0(reduce-scatter)core count 在 megacore 下是 2K,在 non-megacore 2-core 芯片下是 4K——即加倍轴环长乘以每芯片 core 数。
2.2 GetPhase1Cores = R = (num2K ≥ 2 ? 2K : K)
GetPhase1Cores(target, device_assign):
UpdateMinMaxDims(target)
result = *((long*)this + (*((long*)this + 192) < 2) + 190)
// index 192 = [this+0x600] = num2K
// (num2K < 2) → +1 → index 191 = [this+0x5f8] = K
// (num2K >= 2) → +0 → index 190 = [this+0x5f0] = 2K
VLOG(1) "GetPhase1Cores: " << result // all_reduce_strategies.h:800
return result
```text
布尔值 `(num2K < 2)` 被加到基 QWORD 索引 `190`(`0x5f0`):单个加倍轴(`num2K == 1`)选择 `K`,两个加倍轴(`num2K ≥ 2`)选择 `2K`。这正是 `R`,也就是 all-gather segment count,并且是 SparseCore `TwistedTorusTopologyInfo` 三元组携带的**同一个 `R`**(§1.2),也是 TensorCore replica-group Phase1 平面所跨越的 `R`。
> 两个函数体在反编译中都是字节精确的。Phase0:`*((long*)this + 190) * LogicalDevicesPerChip(a2, 0)`,并在 `all_reduce_strategies.h:792` 有 VLOG `"GetPhase0Cores: "`。Phase1:`*((long*)this + (*((long*)this + 192) < 2LL) + 190)`,并在 line 800 有 VLOG `"GetPhase1Cores: "`。QWORD 索引 `190`/`191`/`192` 是偏移 `0x5f0`/`0x5f8`/`0x600`(`190·8 = 0x5f0`)。基类 `StrategyND::GetPhase0Cores @0x137d6980` 则通过 `BaseStrategyND::ComputeColorDimensions`(按颜色的芯片维度)路由——确认 `TwistedTorusND` override 是独立的 `2K·LDPC` / `R` 公式。
### 2.3 读取它们的 validator
| Function | Address | Reads | Purpose |
|----------|---------|-------|---------|
| `cross_replica_sharding_util::TryParseColorwiseAllReduceFusion` | `0x137e34c0` | `GetPhase0Cores`(slot `+0x50`) | 验证 AR fusion shard 几何 |
| `cross_replica_sharding_util::TryParseAllGatherFusion` | `0x137e4ec0` | `GetPhase1Cores`(slot `+0x58`) | 验证 AG fusion replica 几何 |
每个 parser 都通过 vtable 调用 virtual(`call *0x50(%rax)` / `*0x58`),并把返回的按阶段 core count 与 HLO fusion 的 operand shapes 比较——拒绝 shard/replica 几何不匹配 strategy 按阶段环/平面的 fusion。
### 2.4 Core count 与 replica group 的区别
这些函数返回的是**计数**,不是设备列表。配套的 [2-Phase Replica-Group Construction](replica-group-2phase.md) 会构建完整的 `ReplicaGroup` 成员 device-ID;`GetPhaseNCores` 只返回环长 / segment cardinality。
| Phase | Function | Count | vs replica group member count |
|-------|----------|-------|-------------------------------|
| 0 — reduce-scatter | `GetPhase0Cores @0x137d6de0` | `2K · LDPC` | RS 环长 × cores/chip(group 有 `2K`,megacore 时 ×2) |
| 1 — all-gather | `GetPhase1Cores @0x137d6ec0` | `R = (num2K ≥ 2 ? 2K : K)` | AG 平面 segment count(group 有 `R·K` 个成员) |
---
## 3. `EstimatePhysicalLinksUsed`——物理 ICI 链路估算器
```cpp
// xla::jellyfish::
std::vector<IciResource> EstimatePhysicalLinksUsed(
const Target& target,
const DeviceAssignment& device_assign,
absl::Span<const std::vector<GlobalDeviceId>> replica_groups);EstimatePhysicalLinksUsed @0x1c8939c0 回答“这一组 replica groups 的 collective 穿过多少条不同的物理 ICI 链路?”——也就是 all-to-all / ragged / cross-module-all-reduce cost model 用来除带宽的 “links” 除数。关键是,它不是按轴 span 的标量乘积:它返回一个 vector<IciResource>,link count 是 result.size()。
3.1 算法——对成员芯片坐标做 torus-set walk
EstimatePhysicalLinksUsed(target, device_assign, replica_groups):
result = {} // FlatHashSet<IciResource> (CRC32 swiss-set)
multi_slice = (Target::GetMultiSliceTopology(target) != nullptr)
for each replica group g in replica_groups: // outer loop, group stride 0x18
// resolve member[0] → chip coordinates:
id0 = LogicalDeviceForId(0, g.member[0]) // multi-slice: ToSliceAndLogicalDeviceId
ref = chip_coordinates(id0) // (ref.X, ref.Y, ref.Z)
sameX = sameY = sameZ = true // "all members share this axis?"
for m in g.members[1 .. N-1]:
id = LogicalDeviceForId(0, m) // multi-slice gated
c = chip_coordinates(id)
sameY &= (c.Y == ref.Y) // HIDWORD compare
sameX &= (c.X == ref.X) // LODWORD compare
sameZ &= (c.Z == ref.Z)
// per-axis directional resource insert (the 6 IciResources 1..6):
insert( sameY ? <Y dir> : <Y dir'> ) // value in {1, 2}
insert( sameX ? <X dir> : <X dir'> ) // value in {3, 4}
insert( sameZ ? <Z dir> : <Z dir'> ) // value in {5, 6}
v = sort(vector(result)) // __introsort over IciResource*
return v // links = v.size()
```text
只有当 group 的每个成员都与 `member[0]` 共享该坐标时,flag 才会保持 `true`——也就是说该 group **不**跨越该轴。随后按轴 flag 会选择该轴两个方向性 `IciResource` 值之一插入。因为 `result` 是集合,被多个 group 触及的方向性 resource 只计一次;跨越更多轴(或某轴两个方向)的 group 会贡献更多不同 resource。
> 反编译显示:`GetMultiSliceTopology` gate;按成员执行的 `LogicalDeviceForId(…, 0, …)` → `TpuCoreLocation::chip_coordinates` 解析;三个 “all-same-on-axis” AND reductions(`v34 &= HIDWORD(coords) == ref`,`v185 &= (DWORD)coords == ref`,第三轴 `&&`);六个 `IciResource` 常量存储 `LODWORD(res) = N`,其中 `N ∈ {1,2,3,4,5,6}`;通过 `PrepareInsertLarge` / `GrowSooTableToNextCapacityAndPrepareInsert` 并使用 `_mm_crc32_u64` hashing 的 `FlatHashSet<IciResource>` 插入;带 cross-slice RetCheck `"Unsupported cross-slice replica groups"`(`group_utils.cc:1652`)的 multi-slice `ToSliceAndLogicalDeviceId` 路径;以及收尾——`operator new(4 * count)`(每个 `IciResource` 4 字节),复制集合的 live slots(跳过 `≤ -2` empty/deleted sentinels),并在 `sret` 返回前用 `std::__introsort<… IciResource* …>` 排序。全部字节确认。
### 3.2 `IciResource` 编码
6 个方向性 resource 是 `{axis × direction}` 笛卡尔积:
| `IciResource` | Torus dim | Direction | `ResourceVector` slot (`GetResourceFromIciResource`) |
|---------------|-----------|-----------|------------------------------------------------------|
| `1` | X | dir 0 | `0xd` |
| `2` | X | dir 1 | `0xe` |
| `3` | Y | dir 0 | `0xf` |
| `4` | Y | dir 1 | `0x10` |
| `5` | Z | dir 0 | `0x11` |
| `6` | Z | dir 1 | `0x12` |
`GetResourceFromIciResource @0x1c894c00` 把每个值 `e ∈ [1,6]` 映射到 slot `e - 1 + 0xd`(slots `0xd..0x12`)。Dim↔resource 配对与 cost consumer 的按维度读取匹配(§3.3)。
> **[LOW]** 一个轴的两个方向性 resource 中**哪个**(每对的 even vs odd)由跨越该轴选择——即 `+/-` SerDes 方向奇偶——已追踪到 same-flag conjunction(`sameX`/`sameY`/`sameZ` booleans 驱动 `{1,2}`/`{3,4}`/`{5,6}` 选择),但尚未绑定到物理 SerDes 方向符号。反编译显示 resource 值 `2`、`4` 和 `6`(每个轴的 “dir 1”)各自在**两个**位置插入(由 member-walk parity 做 even/odd 选择),确认了 dispatch 但未确认几何方向符号。与 degraded axis 的交互(它可以从集合中删除一个 resource——partial-torus reliability path)通过 consumer 的 degraded-mask AND(§3.3)观察到,但未字段解码。
### 3.3 Cost-model consumer
`ComputeAllToAllCyclesHelper @0x130d02a0` 调用 `EstimatePhysicalLinksUsed` 并遍历返回的 `vector<IciResource>`(每个 4 字节)。对每个值,它映射 `{1/3/5 → X/Y/Z}` 并用 `cmovle` 读取对应的芯片 torus-dim extent(`[cfg+0x58]` 等)(取这些 resource 上的**最小值**),同时 AND degraded-axis bool `[cfg+0xa0]`。因此 all-to-all / cross-module-all-reduce 带宽除数是**最小跨越轴范围**和 degraded mask 的函数——而 `÷ links` 项具体就是“`÷` replica groups 触及的不同方向性 ICI resource 数量”,不是 span 的闭式乘积。
这解决了 cost model 之前的开放问题(link divisor “traced to the chip-coordinate walk, not reduced to a single equation”):除数是 `|EstimatePhysicalLinksUsed(...)|`,即有序方向性 resource 集合的基数。
---
## 4. SparseCore twist vs TensorCore twist——结构并行
SparseCore `TwistedTorusTopologyInfo` 和 TensorCore `TwistedTorusND` 描述**相同的物理 twist**,并共享 `R` 旋钮和接缝,但表示方式和输出不同:
| Aspect | TensorCore (`group_utils.cc` / `all_reduce_strategies.h`) | SparseCore (`offload_collective_config_builder.cc`) |
|--------|----------------------------------------------------------|-----------------------------------------------------|
| Class | `xla::jellyfish::TwistedTorusND` (StrategyND) | `sparse_core::collective::TwistedTorusTopologyInfo` |
| Shapes | `k_k_2k`, `k_2k_2k`(+ routing-only `k_2k_nK`) | 仅 `k_k_2k`, `k_2k_2k`(无字面 `nK`) |
| `R` knob | `num2K ≥ 2 ? 2K : K`(`[obj+0x600]` select) | `shape ? 2K : K`(triple `[this+0x40]`)— **相同** |
| Seam | `+K`-mod-`2K`(`GetReplicaPair3DOnTwistedTorus`) | `+K`-mod-`2K`(fold primitive `$_1`)— **相同** |
| Phase representation | 2 × `GetPhaseNReplicaGroups` 循环嵌套 | 2 × `TwistedView` (`vector<vector<shared_ptr<fn>>>`) |
| Coordinate fold | `GetReplicaPair3DOnTwistedTorus @0x1c893400` | `ForEachPhase @0x133e17c0` + 7 fold closures |
| Rank invariant | `num_max_dims == 2` CHECK | `CHECK dim_per_phase_.size() == 3` — **同样 3-D** |
| Output | HLO `ReplicaGroup` 设备列表 | `CollectiveIciStrategyConfig` 按颜色 rings |
| Consumer | XLA collective scheduler | `ConstructConfigForCollectiveUniDirNDGroups<*>` (offload) |
| Per-phase counts | `GetPhase0/1Cores`(§2)— `2K·LDPC` / `R` | (counts 通过相同的 `TwistedTorusND` virtual 共享) |
---
## 5. Function Map
| Function | Address | Role |
|----------|---------|------|
| `TwistedTorusTopologyInfo::TryCreateTwistedTorusTopologyInfo` | `0x133e1980` | SC twist factory + shape/divisibility gate |
| `TwistedTorusTopologyInfo::TwistedTorusTopologyInfo` (ctor) | `0x133e1b40` | 对象布局 + `(2K,R,K)` 三元组 + 7 个 closure |
| `TwistedTorusTopologyInfo::ConstructTwistedViews` | `0x133e1ea0` | 两个 `TwistedView` 构建(RS + AG) |
| `TwistedView::ForEachPhase` | `0x133e17c0` | 3 轴 fold;`CHECK==3` + `*0x10` dispatch |
| `TwistedView::SetToTwistedCoordinates::$_0` | `0x133e4140` | 按 phase 驱动 `ForEachPhase`(forward twist) |
| `TwistedView::SetToOriginalCoordinates::$_0` | `0x133e4580` | `SetToTwistedCoordinates` 的 inverse twist 配对 |
| `ConstructTwistedViews()::$_0` / `$_1` | `0x133e6160` / `0x133e6180` | 第一个 view 的两个 `TpuDimensions(TpuDimensions)` closure |
| fold closures `$_1..$_7` | `0x133e4ae0..0x133e4dc0` | 7 个坐标折叠原语 |
| `TwistedTorusND::GetPhase0Cores` | `0x137d6de0` | `2K · LogicalDevicesPerChip` |
| `TwistedTorusND::GetPhase1Cores` | `0x137d6ec0` | `R = (num2K ≥ 2 ? 2K : K)` |
| `StrategyND::GetPhase0Cores`(base,对照) | `0x137d6980` | 经由 `ComputeColorDimensions` 的按颜色芯片维度 |
| `TryParseColorwiseAllReduceFusion` | `0x137e34c0` | AR-fusion validator(读取 slot `+0x50`) |
| `TryParseAllGatherFusion` | `0x137e4ec0` | AG-fusion validator(读取 slot `+0x58`) |
| `EstimatePhysicalLinksUsed` | `0x1c8939c0` | 有序集合方向性 `IciResource` 链路估算器 |
| `EstimatePhysicalLinksUsed::$_0` (multi-slice) | `0x1c894ac0` | global → local logical-id resolver |
| `GetResourceFromIciResource` | `0x1c894c00` | `e-1+0xd`(slots `0xd..0x12`) |
| `ComputeAllToAllCyclesHelper` | `0x130d02a0` | 映射 `IciResource` → torus-dim extent(除数) |
---
## 6. 未解决内容
- **`ConstructTwistedViews` 中按 `(shape, view, group)` 的 fold-closure assignment。** 两 view `{2,3,3}` group 结构和 7 个原语的闭式形式是字节精确的,但每种形状下哪个 closure index 填入两个 view 的三个 axis-group 中的哪个,是从构造顺序追踪到的,尚未归约为 composition table。**[LOW]** — 见 §1.3。
- **`EstimatePhysicalLinksUsed` 中的 `+/-` SerDes 方向奇偶。** 按轴 same-flag → resource dispatch 和 6 个值已确认,但跨越轴映射到每对中的哪个方向性 resource(由 member-walk parity 做 even/odd 选择),以及 degraded axis 如何从集合中删除 resource,尚未字段解码。**[LOW]** — 见 §3.2。
- **`TwistedTorusTopologyInfo` ctor 偏移。** `(2K,R,K)` 三元组、`is-doubled-axis` mask 和 7-closure 存储偏移(`[this+0x40]`/`[+0x58]`/`[+0x78..0xe0]`)是从 ctor 反汇编重建的,未逐指令重新遍历。`R` 旋钮和形状判别量为 HIGH;精确字段偏移为 **MEDIUM**。
- **`IciDim` 类型布局。** `TryCreate` 接收 `vector<IciDim>`,cost path 使用 `vector<IciResource>`;`IciDim` 是否携带 `(dim_index, extent, wrap-mode)` 元组,以及它如何与 dense mesh descriptor 统一,尚未字段解码。**[LOW]**
---
## 交叉引用
### Twist 算法(本节)
- [Twisted Torus — Section Map](overview.md) — 三类名称碰撞(`TwistedTorusND` / `TwistedTorusTopology` / `TwistedTorusTopologyInfo`)和形状 gate
- [TwistedTorusND::BuildStrategy](buildstrategy.md) — TensorCore twist class family、ND ring + 按颜色接缝 phases
- [2-Phase Replica-Group Construction](replica-group-2phase.md) — 这些 `*Cores` count 对应的 TensorCore `GetPhaseNReplicaGroups` 设备列表
- [GetReplicaPair3DOnTwistedTorus](get-replica-pair-3d.md) — SC `$_1` 接缝所镜像的 TensorCore `+K`-mod-`2K` 坐标折叠
### 相邻章节
- [SC-Offload Config Builder](../collectives/sc-offload-config-builder.md) — `ConstructConfigForCollectiveUniDirNDGroups<*>`,通过其 `cmp $3` K/2K gate 触达 `TryCreateTwistedTorusTopologyInfo` 的 consumer
- [SC Core-Selection (Offload)](../collectives/sc-core-selection-offload.md) — offload config 上游的 SparseCore op-type classification 和 core selection
- [返回索引](../index.md)