跳到主要内容

L3 Mapping -- Math 路径:Tiling 与调度

功能概述

L3 Math 路径接收 L3 公共层输出的 DistributedModel,完成:

  1. TilingPlanner: 片内 Tile 映射 + Kernel 选择
  2. Scheduler: 时序调度 + 依赖排序

输出: ExecPlan (timeline + binding + kernel_config)

前置: 必须先经过 04-l3-common.md 的 ParallelismPlanner。

模块清单

模块职责
math/tiling/planner.pyTilingPlanner
math/tiling/evaluators.pyTile 候选评估器
math/scheduling/scheduler.pyScheduler
math/plan/exec_plan.pyExecPlan

TilingPlanner

输入/输出

  • 输入: DistributedModel + ChipSpecImpl + L4TileEvaluator (可选)
  • 输出: TilePlan

计算流程

  1. 候选生成: 按 op_type 生成 tile 候选 (MKN blocking)
  2. 约束剪枝: SRAM 上限、对齐约束、Cube 整除
  3. 快速预筛: 简化 roofline 预估 + 帕累托剪枝
  4. 精评估: 调用 L4 PreciseTileEvaluator (traffic/urate/loop-order)
  5. 选优: 选择最短执行时间的 tile
  6. 缓存: 对同构 op 做内存缓存 + 可选 SQLite 持久缓存
  7. Zigzag 优化: 若 enable_zigzag=True,调整 PP 阶段 tile 顺序以减少 bubble

TilePlan

@dataclass
class TilePlan:
tile_configs: dict[str, TileConfig] # op_id -> tile
kernel_configs: dict[str, dict] # op_id -> kernel 元数据
intra_chip_comms: list[DistributedOp] # 片内通信 (tiling 引起)

Tile 候选规则 (对齐 CHIPMathica)

  • 分区合法: P_* 必须整除 core_count
  • Tile 对齐: tile_m/n/k 满足 cube_m/k/n 整除
  • SRAM 上限: 单 tile 占用 <= lmem_capacity_kb * lmem_utilization
  • 帕累托剪枝: 各维度均不小于候选时丢弃
  • 流量优先: 选择最小 DRAM traffic 的 tile + loop-order
  • FA2 细化: Q/K tile 满足 Q+K+V+2P+4O buffer 预算

Scheduler

输入/输出

  • 输入: DistributedModel + TilePlan
  • 输出: ExecPlan

计算流程

  1. 拓扑排序: Kahn 算法,确保依赖约束
  2. 优先级: fanout (默认) 或 critical_path 模式
  3. 实例展开: Op/CommOp -> timeline event
  4. 资源统计: 记录 core_slots 与 path_slots
  5. Buffer 估算: 追踪 buffer 峰值

ExecPlan

@dataclass
class ExecPlan:
timeline: list[dict] # [{op_id, duration, wait_time, stage}, ...]
binding: dict[str, Any] # op_id -> chip_id/core_ids
precedence: list[tuple] # 依赖边
kernel_config: dict[str, dict] # op_id -> kernel 参数
trace_meta: dict # 调度元数据

Timeline Event

{
"op_id": "layers.0.mla.q_proj",
"start_step": 0,
"duration": 1,
"wait_time": 0.0,
"stage": 0,
}