diff --git a/VX_config.toml b/VX_config.toml index a79426767e..80a2eb36de 100644 --- a/VX_config.toml +++ b/VX_config.toml @@ -421,13 +421,28 @@ VX_CFG_TCU_SPARSE_ENABLE = false VX_CFG_TCU_DSM_ENABLE = false VX_CFG_TCU_WGMMA_ENABLE = false VX_CFG_TCU_FEDP2K = false +# Tensor memory: a per-core accumulator of (TCU blocks x WGMMA M) lanes by +# TMEM_COLS 32-bit columns, written by the TCU's single-thread MMA engine. +VX_CFG_TCU_TMEM_ENABLE = false +VX_CFG_TCU_TMEM_COLS = 128 +# Per-warp MMAs (tcu.wmma, and tcu.ld for their sparse and MX metadata). A +# tensor-memory build can drop them, as its MMAs are tc.mma: the TCU then keeps +# no register-operand path, result landing queue or metadata store. +VX_CFG_TCU_WMMA_ENABLE = true [dxa] # Cluster-level DXA engine count, decoupled from cores/socket size. VX_CFG_NUM_DXA_CORES = "expr: max(1, up($VX_CFG_NUM_CORES / 8))" VX_CFG_DXA_MEM_PORTS = "expr: min($VX_CFG_NUM_DXA_CORES, up($VX_CFG_NUM_CORES / $VX_CFG_SOCKET_SIZE) * $VX_CFG_L1_MEM_PORTS)" VX_CFG_DXA_QUEUE_SIZE = 16 -VX_CFG_DXA_MAX_INFLIGHT = 8 +# Line reads a DXA worker keeps in flight (Little's law, as the cache MSHRs): +# its share of the bytes in flight above the L2, in lines, but no more than +# the memory latency, since a worker issues at most one line per cycle. +VX_CFG_DXA_MAX_INFLIGHT = "expr: clamp(pow(2, clog2(min(($l1_mem_bytes_in_flight + $dxa_inflight_bytes - 1) // $dxa_inflight_bytes, $VX_CFG_PLATFORM_MEMORY_LATENCY + 2 * $VX_CFG_L2_LINK_LATENCY))), 8, 512)" +dxa_inflight_bytes = "expr: $VX_CFG_NUM_CLUSTERS * up($VX_CFG_NUM_CORES // $VX_CFG_SOCKET_SIZE) * $VX_CFG_NUM_DXA_CORES * $VX_CFG_L1_LINE_SIZE" +# Transfers a worker keeps in flight: the next one issues while earlier ones +# drain. Sized so tile-sized transfers (16+ lines) can fill the read pool. +VX_CFG_DXA_MAX_XFERS = "expr: clamp($VX_CFG_DXA_MAX_INFLIGHT // 16, 2, 16)" [rtu] # RTU (Ray-Tracing Unit) diff --git a/VX_types.toml b/VX_types.toml index 4babbab5f2..318263718b 100644 --- a/VX_types.toml +++ b/VX_types.toml @@ -136,7 +136,9 @@ VX_DCR_KMU_WARP_STEP_Z = 0x020 VX_DCR_KMU_CLUSTER_DIM_X= 0x021 VX_DCR_KMU_CLUSTER_DIM_Y= 0x022 VX_DCR_KMU_CLUSTER_DIM_Z= 0x023 -VX_DCR_KMU_STATE_END = 0x024 +# TMEM columns a CTA may allocate (tensor-memory builds; 0 = none) +VX_DCR_KMU_TMEM_COLS = 0x024 +VX_DCR_KMU_STATE_END = 0x025 # DXA descriptor DCR mapping # access pattern: @@ -809,6 +811,18 @@ VX_CSR_MPM_TCU_TBUF_CACHE_HITS= 0xB04 # B tile reuse hits from tile buffer cach VX_CSR_MPM_TCU_TBUF_CACHE_HITS_H = 0xB84 VX_CSR_MPM_TCU_LMEM_READS = 0xB05 # tile buffer local memory reads VX_CSR_MPM_TCU_LMEM_READS_H = 0xB85 +# Each cycle falls in one bucket: MMA busy (block-cycles), else operand wait, +# other op activity, or idle. +VX_CSR_MPM_TCU_MMA_BUSY = 0xB06 # block-cycles an MMA step fired +VX_CSR_MPM_TCU_MMA_BUSY_H = 0xB86 +VX_CSR_MPM_TCU_OPND_WAITS = 0xB07 # cycles: MMA waits on A/B operands (tile buffers, TMEM A) +VX_CSR_MPM_TCU_OPND_WAITS_H = 0xB87 +VX_CSR_MPM_TCU_JOB_OTHER = 0xB08 # cycles: op start, drain or tc.cp +VX_CSR_MPM_TCU_JOB_OTHER_H = 0xB88 +VX_CSR_MPM_TCU_IDLE = 0xB09 # cycles: no MMA work +VX_CSR_MPM_TCU_IDLE_H = 0xB89 +VX_CSR_MPM_TCU_TMEM_XFERS = 0xB0A # tmem.ld/st transfers +VX_CSR_MPM_TCU_TMEM_XFERS_H = 0xB8A [csr_mpm_tex] # PERF: texture unit (per-core; summed across blocks) diff --git a/ci/baselines/perf/core.json b/ci/baselines/perf/core.json index 9e35eab6ba..380cbf5c27 100644 --- a/ci/baselines/perf/core.json +++ b/ci/baselines/perf/core.json @@ -6,7 +6,7 @@ }, "app": "raycast", "args": "", - "config_hash": "55cc313a7e04e175", + "config_hash": "81f9ffd9b38350c9", "configs": "-DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -17,7 +17,7 @@ }, "app": "raycast", "args": "", - "config_hash": "dd27d4e019b1ce48", + "config_hash": "e9f4bd5c7677bdec", "configs": "-DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -28,7 +28,7 @@ }, "app": "sgemm", "args": "-n128", - "config_hash": "bb3179476f050efd", + "config_hash": "2ce74004c3f9c5f3", "configs": "-DVX_CFG_NUM_WARPS=8 -DVX_CFG_NUM_CORES=2 -DVX_CFG_NUM_THREADS=16 -DVX_CFG_L2_ENABLE", "driver": "rtlsim" }, @@ -39,7 +39,7 @@ }, "app": "sgemm", "args": "-n128", - "config_hash": "d7960926dfeeeb1a", + "config_hash": "9781f45e6f5b3ce5", "configs": "-DVX_CFG_NUM_WARPS=8 -DVX_CFG_NUM_CORES=2 -DVX_CFG_NUM_THREADS=4 -DVX_CFG_L2_ENABLE", "driver": "rtlsim" }, @@ -50,7 +50,7 @@ }, "app": "sgemm", "args": "-n128", - "config_hash": "fa3eb81110539fb3", + "config_hash": "3003591c5c576215", "configs": "-DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -61,7 +61,7 @@ }, "app": "sgemm", "args": "-n128", - "config_hash": "faa73f4f1a81a3d0", + "config_hash": "9d95d404d11e3da2", "configs": "-DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -72,7 +72,7 @@ }, "app": "sgemmx", "args": "-n128", - "config_hash": "5e051358cb6705f1", + "config_hash": "e427b4368b068a8a", "configs": "-DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -83,7 +83,7 @@ }, "app": "sgemmx", "args": "-n128", - "config_hash": "0286292d319c5b4e", + "config_hash": "d740a44b584575de", "configs": "-DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -94,7 +94,7 @@ }, "app": "sgemv", "args": "-m512 -n512", - "config_hash": "2a1bbb428f8d6870", + "config_hash": "3c250ffd26121340", "configs": "-DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -105,7 +105,7 @@ }, "app": "sgemv", "args": "-m512 -n512", - "config_hash": "575d72e47c1c0daa", + "config_hash": "756832d874123c1b", "configs": "-DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -116,7 +116,7 @@ }, "app": "softmax", "args": "-n64", - "config_hash": "d656cb5ba22d494f", + "config_hash": "b54eb832f0599f67", "configs": "-DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -127,7 +127,7 @@ }, "app": "softmax", "args": "-n64", - "config_hash": "f5c775b6c4dbc1cf", + "config_hash": "66455c71442d2f59", "configs": "-DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -138,7 +138,7 @@ }, "app": "stencil3d", "args": "-n32", - "config_hash": "5082708220a3aab3", + "config_hash": "2db925342c6470c1", "configs": "-DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -149,7 +149,7 @@ }, "app": "stencil3d", "args": "-n32", - "config_hash": "7c57f7380ccb6a94", + "config_hash": "d39c4473299b462f", "configs": "-DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -160,7 +160,7 @@ }, "app": "vecadd", "args": "-n16384", - "config_hash": "37045d524c1e46ce", + "config_hash": "c28e19ec12d82b31", "configs": "-DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -171,7 +171,7 @@ }, "app": "vecadd", "args": "-n16384", - "config_hash": "d353d7d15f65b5fd", + "config_hash": "d0e3864ab7f714cf", "configs": "-DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" } diff --git a/ci/baselines/perf/dxa.json b/ci/baselines/perf/dxa.json index 926c0cef32..75281e77bb 100644 --- a/ci/baselines/perf/dxa.json +++ b/ci/baselines/perf/dxa.json @@ -1,23 +1,23 @@ { "dxa:perf_gate-copy-mcast:rtlsim": { "32": { - "cycles": 3437, + "cycles": 3439, "instrs": 955 }, "app": "dxa_copy_mcast", "args": "", - "config_hash": "902d06551db54908", + "config_hash": "7aa75505bb072dd0", "configs": "-DVX_CFG_EXT_DXA_ENABLE", "driver": "rtlsim" }, "dxa:perf_gate-copy-nt16:rtlsim": { "32": { - "cycles": 1829, + "cycles": 1795, "instrs": 552 }, "app": "dxa_copy", "args": "-d1", - "config_hash": "07394e6aa480a2d8", + "config_hash": "75539d5445c0a927", "configs": "-DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -28,95 +28,95 @@ }, "app": "dxa_copy", "args": "-d1", - "config_hash": "2bb76314b3aac79b", + "config_hash": "05ce9835d1998c51", "configs": "-DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, "dxa:perf_gate-sgemm2-dxa-mcast-nt16:rtlsim": { "32": { - "cycles": 9937880, + "cycles": 9923748, "instrs": 3829776 }, "app": "sgemm2_dxa_mcast", "args": "-n128", - "config_hash": "cbfcd136a9cbf5f3", + "config_hash": "cefa29dd449550d2", "configs": "-DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, "dxa:perf_gate-sgemm2-dxa-mcast-nt4:rtlsim": { "32": { - "cycles": 9969042, + "cycles": 9923859, "instrs": 3829776 }, "app": "sgemm2_dxa_mcast", "args": "-n128", - "config_hash": "4c813805db4d6ceb", + "config_hash": "1694cdd60a825ae1", "configs": "-DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, "dxa:perf_gate-sgemm2-dxa-nt16:rtlsim": { "32": { - "cycles": 2265324, + "cycles": 2262127, "instrs": 835600 }, "app": "sgemm2_dxa", "args": "-n128 -t4 -m1", - "config_hash": "dc6a4fb24203f236", + "config_hash": "90a09f7a724bf084", "configs": "-DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, "dxa:perf_gate-sgemm2-dxa-nt4:rtlsim": { "32": { - "cycles": 8921139, + "cycles": 8901090, "instrs": 3302416 }, "app": "sgemm2_dxa", "args": "-n128 -t4 -m1", - "config_hash": "c0117149996966a4", + "config_hash": "93e7a25846523eff", "configs": "-DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, "dxa:perf_gate-wgmma-dxa-mcast-nt16:rtlsim": { "32": { - "cycles": 79428, + "cycles": 77303, "instrs": 26560 }, "app": "sgemm_tcu_wg_dxa_mcast", "args": "-m 128 -n 128 -k 64", - "config_hash": "4578525b3dad120a", + "config_hash": "4ada4b764cc7fd29", "configs": "-DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, "dxa:perf_gate-wgmma-dxa-mcast-nt4:rtlsim": { "32": { - "cycles": 355108, + "cycles": 353734, "instrs": 170560 }, "app": "sgemm_tcu_wg_dxa_mcast", "args": "-m 128 -n 128 -k 64", - "config_hash": "cf9987cc4e0ec4b6", + "config_hash": "5c5f6cf458fa9da6", "configs": "-DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, "dxa:perf_gate-wgmma-dxa:rtlsim": { "32": { - "cycles": 28003, + "cycles": 26903, "instrs": 8872 }, "app": "sgemm_tcu_wg_dxa", "args": "-m 128 -n 128 -k 64", - "config_hash": "2dfa43c0ffd2af2a", + "config_hash": "bb1fe6a4a9327177", "configs": "-DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DWGMMA_NRC=16 -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_NUM_THREADS=32", "driver": "rtlsim" }, "dxa:perf_gate-wgmma-sp-dxa:rtlsim": { "32": { - "cycles": 47359, + "cycles": 44695, "instrs": 9344 }, "app": "sgemm_tcu_wg_sp_dxa", "args": "-m 128 -n 128 -k 128", - "config_hash": "5cb40c33773fc66c", + "config_hash": "249a9327a1403e3b", "configs": "-DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DWGMMA_NRC=32 -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_NUM_THREADS=32", "driver": "rtlsim" } diff --git a/ci/baselines/perf/graphics.json b/ci/baselines/perf/graphics.json index 73bb427b9d..9b3c75ebb6 100644 --- a/ci/baselines/perf/graphics.json +++ b/ci/baselines/perf/graphics.json @@ -6,7 +6,7 @@ }, "app": "gfx_draw3d", "args": "-w 128 -h 128 -t box.cgltrace -r box_ref_128.png", - "config_hash": "89c0128e9ca4f6fd", + "config_hash": "10eed2fee7217ff7", "configs": "-DVX_CFG_EXT_TEX_ENABLE -DVX_CFG_EXT_RASTER_ENABLE -DVX_CFG_EXT_OM_ENABLE -DVX_CFG_NUM_CORES=2 -DVX_CFG_NUM_THREADS=4 -DVX_CFG_L2_ENABLE", "driver": "rtlsim" }, @@ -17,7 +17,7 @@ }, "app": "gfx_draw3d", "args": "-w 128 -h 128 -t box.cgltrace -r box_ref_128.png", - "config_hash": "e624b9b51f6baef3", + "config_hash": "8f614b0ae52a28f7", "configs": "-DVX_CFG_EXT_TEX_ENABLE -DVX_CFG_EXT_RASTER_ENABLE -DVX_CFG_EXT_OM_ENABLE -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -28,7 +28,7 @@ }, "app": "gfx_draw3d", "args": "-w 128 -h 128 -t box.cgltrace -r box_ref_128.png", - "config_hash": "270685a4f2b573e4", + "config_hash": "1f14dd14eaf53e56", "configs": "-DVX_CFG_EXT_TEX_ENABLE -DVX_CFG_EXT_RASTER_ENABLE -DVX_CFG_EXT_OM_ENABLE -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -39,7 +39,7 @@ }, "app": "gfx_om", "args": "-w 128 -h 128 -r whitebox_128.png", - "config_hash": "8f81b9cbea824821", + "config_hash": "1b5cfb0613e651bf", "configs": "-DVX_CFG_EXT_OM_ENABLE -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -50,7 +50,7 @@ }, "app": "gfx_om", "args": "-w 128 -h 128 -r whitebox_128.png", - "config_hash": "96b6e6d47c8f0e6f", + "config_hash": "48ce27ba42416f40", "configs": "-DVX_CFG_EXT_OM_ENABLE -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -61,7 +61,7 @@ }, "app": "gfx_raster", "args": "-w 128 -h 128 -t triangle.cgltrace -r triangle_ref_128.png", - "config_hash": "465f2e520f475df5", + "config_hash": "3847ae8ffbeeaa2d", "configs": "-DVX_CFG_EXT_RASTER_ENABLE -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -72,7 +72,7 @@ }, "app": "gfx_raster", "args": "-w 128 -h 128 -t triangle.cgltrace -r triangle_ref_128.png", - "config_hash": "f672749b1816d04d", + "config_hash": "089399d90e7bd401", "configs": "-DVX_CFG_EXT_RASTER_ENABLE -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" }, @@ -83,7 +83,7 @@ }, "app": "gfx_tex", "args": "-i toad.png -r toad_ref_f0.png -f 0 -g 0", - "config_hash": "54f35f4d8236a2f5", + "config_hash": "1ac3bb07e8dd4a4f", "configs": "-DVX_CFG_EXT_TEX_ENABLE -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -94,7 +94,7 @@ }, "app": "gfx_tex", "args": "-i toad.png -r toad_ref_f0.png -f 0 -g 0", - "config_hash": "dba2310b8ed2bc68", + "config_hash": "d50709a30cebf144", "configs": "-DVX_CFG_EXT_TEX_ENABLE -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" } diff --git a/ci/baselines/perf/raytracing.json b/ci/baselines/perf/raytracing.json index 75021c4780..098b534a1b 100644 --- a/ci/baselines/perf/raytracing.json +++ b/ci/baselines/perf/raytracing.json @@ -6,7 +6,7 @@ }, "app": "rt_raycast", "args": "", - "config_hash": "926004202e1230cc", + "config_hash": "e14e9471553a9563", "configs": "-DVX_CFG_EXT_RTU_ENABLE -DVX_CFG_NUM_CORES=2 -DVX_CFG_NUM_THREADS=4 -DVX_CFG_L2_ENABLE", "driver": "rtlsim" }, @@ -17,7 +17,7 @@ }, "app": "rt_raycast", "args": "", - "config_hash": "cde0e92d03a53a87", + "config_hash": "1a32b5473c0eaf9b", "configs": "-DVX_CFG_EXT_RTU_ENABLE -DVX_CFG_NUM_THREADS=16", "driver": "rtlsim" }, @@ -28,7 +28,7 @@ }, "app": "rt_raycast", "args": "", - "config_hash": "fffab4e1c8cfe28a", + "config_hash": "b6059bc8b51f7b9f", "configs": "-DVX_CFG_EXT_RTU_ENABLE -DVX_CFG_NUM_THREADS=4", "driver": "rtlsim" } diff --git a/ci/baselines/perf/tensor.json b/ci/baselines/perf/tensor.json index 3c907caa8b..d7589868fc 100644 --- a/ci/baselines/perf/tensor.json +++ b/ci/baselines/perf/tensor.json @@ -6,7 +6,7 @@ }, "app": "sgemm_tcu", "args": "-m 128 -n 128 -k 128", - "config_hash": "4fbb4f6c32f0fac9", + "config_hash": "cff22f431ec078f6", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DITYPE=fp16 -DOTYPE=fp32 -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1", "driver": "rtlsim" }, @@ -17,7 +17,7 @@ }, "app": "sgemm_tcu", "args": "-m 128 -n 128 -k 128", - "config_hash": "2dcf0a1b4eea6c29", + "config_hash": "c3856f4e69b1e70d", "configs": "-DVX_CFG_NUM_WARPS=8 -DVX_CFG_EXT_TCU_ENABLE -DITYPE=fp16 -DOTYPE=fp32 -DVX_CFG_NUM_CORES=2 -DVX_CFG_NUM_THREADS=16 -DVX_CFG_L2_ENABLE", "driver": "rtlsim" }, @@ -28,7 +28,7 @@ }, "app": "sgemm_tcu", "args": "-m 128 -n 128 -k 128", - "config_hash": "234a9a6ed54055b5", + "config_hash": "965f7ef9c4b3a422", "configs": "-DVX_CFG_NUM_WARPS=8 -DVX_CFG_EXT_TCU_ENABLE -DITYPE=fp16 -DOTYPE=fp32 -DVX_CFG_NUM_CORES=2 -DVX_CFG_NUM_THREADS=4 -DVX_CFG_L2_ENABLE", "driver": "rtlsim" }, @@ -39,7 +39,7 @@ }, "app": "sgemm_tcu", "args": "-m 128 -n 128 -k 128", - "config_hash": "1a511d0897922770", + "config_hash": "e9bdc9f60bbded1a", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_EXT_TCU_ENABLE -DITYPE=fp16 -DOTYPE=fp32", "driver": "rtlsim" }, @@ -50,7 +50,7 @@ }, "app": "sgemm2_tcu", "args": "-m 128 -n 128 -k 64", - "config_hash": "2a6b68d4c73246ad", + "config_hash": "d6f77b49458ec88c", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DITYPE=fp16 -DOTYPE=fp32 -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1", "driver": "rtlsim" } diff --git a/ci/baselines/perf/tensor_mx.json b/ci/baselines/perf/tensor_mx.json index a22d3341af..1559ebbce6 100644 --- a/ci/baselines/perf/tensor_mx.json +++ b/ci/baselines/perf/tensor_mx.json @@ -6,7 +6,7 @@ }, "app": "sgemm_tcu_mx", "args": "-m 128 -n 128 -k32", - "config_hash": "2d2b1b822bd13001", + "config_hash": "12b106502456c85b", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_TCU_MX_ENABLE -DVX_CFG_TCU_FP8_ENABLE -DITYPE=mxfp8 -DOTYPE=fp32 -DVX_CFG_TCU_TYPE_DPI", "driver": "rtlsim" } diff --git a/ci/baselines/perf/tensor_sp.json b/ci/baselines/perf/tensor_sp.json index 715eea6d87..a86c659e25 100644 --- a/ci/baselines/perf/tensor_sp.json +++ b/ci/baselines/perf/tensor_sp.json @@ -6,7 +6,7 @@ }, "app": "sgemm_tcu_sp", "args": "-m 128 -n 128 -k 128", - "config_hash": "3f34e8ee3f7f7e13", + "config_hash": "87ac0943e426d381", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_TCU_SPARSE_ENABLE", "driver": "rtlsim" } diff --git a/ci/baselines/perf/tensor_wg.json b/ci/baselines/perf/tensor_wg.json index 561ab5adac..7edbb79260 100644 --- a/ci/baselines/perf/tensor_wg.json +++ b/ci/baselines/perf/tensor_wg.json @@ -1,4 +1,15 @@ { + "tensor_wg:perf_gate-tmem:rtlsim": { + "32": { + "cycles": 38228, + "instrs": 7660 + }, + "app": "sgemm_tcu_tmem", + "args": "-m64 -n64 -k256", + "config_hash": "cce7a8227a7c2cd9", + "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2", + "driver": "rtlsim" + }, "tensor_wg:perf_gate-wgmma-fedp2k-rs:rtlsim": { "32": { "cycles": 134813, @@ -6,7 +17,7 @@ }, "app": "sgemm_tcu_wg", "args": "-m64 -n64 -k64", - "config_hash": "242cd0e42b1e6d8d", + "config_hash": "ead5ee40e17dbbf6", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 -DVX_CFG_TCU_FEDP2K -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=8 -DWGMMA_RS", "driver": "rtlsim" }, @@ -17,7 +28,7 @@ }, "app": "sgemm_tcu_wg", "args": "-m 128 -n 128 -k 128", - "config_hash": "731fefa477a89198", + "config_hash": "8fc1fe2072e6c449", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DWGMMA_SS -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1", "driver": "rtlsim" }, @@ -28,7 +39,7 @@ }, "app": "sgemm_tcu_wg_sp", "args": "-m 128 -n 128 -k 128", - "config_hash": "b5b5adc71557d418", + "config_hash": "e6001b0344d75995", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE -DVX_CFG_TCU_SPARSE_ENABLE -DWGMMA_NRC=32 -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1", "driver": "rtlsim" } diff --git a/ci/baselines/synthesis/beacon/core.json b/ci/baselines/synthesis/beacon/core.json index 56753cad39..f17654b3f7 100644 --- a/ci/baselines/synthesis/beacon/core.json +++ b/ci/baselines/synthesis/beacon/core.json @@ -21,7 +21,7 @@ "16 cache/g_cache.cache/g_banks_1.bank/cache_tags/g_way_decode_3.__buffer_ex187/g_pipe.g_full_reset.pipe[3] -> cache/g_cache.cache/g_banks_1.bank/mshr_pending_size/g_size_gt1.g_select_step.size_r.d[2]" ], "dsp": 0, - "endpoints": 32634, + "endpoints": 32633, "env": { "circt": "CIRCT 892a65a01", "device": "xcu55c-fsvh2892-2L-e", @@ -31,7 +31,7 @@ "ff": 33558, "fix_levels": 12, "interfaces": {}, - "lut": 37104, + "lut": 37092, "lutram": 3333, "max_levels": 16, "pred_fmax_mhz": 291.3, @@ -82,8 +82,8 @@ "dut": "core", "result": { "bram": 129.0, - "build_time_s": 75, - "deep_endpoints": 1536, + "build_time_s": 70, + "deep_endpoints": 1520, "deepest_paths": [ "15 core/g_compute_slices.g_slices_0.compute_slice/frontend_slice/fetch/inflight[2] -> core/g_compute_slices.g_slices_0.compute_slice/frontend_slice/fetch/req_buf/g_eb2.stream_buffer/g_buffer.data_out_r.d[28]", "15 core/g_compute_slices.g_slices_0.compute_slice/frontend_slice/fetch/inflight[2] -> core/g_compute_slices.g_slices_0.compute_slice/frontend_slice/fetch/req_buf/g_eb2.stream_buffer/g_buffer.data_out_r.d[29]", @@ -97,14 +97,14 @@ "15 core/g_compute_slices.g_slices_0.compute_slice/backend_slice/execute_slice/lsu_dispatch/g_blocks_0.buf_out/g_eb2.stream_buffer/g_buffer.data_out_r[1551] -> core/g_compute_slices.g_slices_0.compute_slice/backend_slice/execute_slice/lsu_block/mem_path/lsu_scheduler/mem_scheduler/g_req_queue_rw.req_queue/g_ebN.fifo_queue/g_depth_n.g_out_reg.data_out_r.d[824]" ], "dsp": 97, - "endpoints": 122340, + "endpoints": 120078, "env": { "circt": "CIRCT 892a65a01", "device": "xcu55c-fsvh2892-2L-e", "foldsim": "foldsim d8350bc0f", "xlen": 32 }, - "ff": 163874, + "ff": 160592, "fix_levels": 12, "interfaces": { "core.dcache_bus_if_0_rsp_ready": 1, @@ -114,11 +114,11 @@ "core.icache_bus_if_0_rsp_ready": 1, "core.kmu_bus_if_ready": 1 }, - "lut": 143741, + "lut": 140444, "lutram": 6838, "max_levels": 15, - "pred_fmax_mhz": 285.6, - "risk_endpoints": 11, + "pred_fmax_mhz": 283.6, + "risk_endpoints": 12, "tied_bits": 2, "tied_ports": [ { @@ -169,7 +169,7 @@ "core/scheduler/warp_shared_unit/bar_unit": 9 }, "uram": 0, - "watch_endpoints": 8283, + "watch_endpoints": 8379, "watch_levels": 8 } }, @@ -180,7 +180,7 @@ "dut": "lmem", "result": { "bram": 16.0, - "build_time_s": 25, + "build_time_s": 20, "deep_endpoints": 0, "deepest_paths": [ "9 lmem_unit/g_data_store_0.g_amo.amo_old_r[0] -> lmem_unit/g_data_store_0.g_dual_port.lmem_store/g_bram.g_wren.ram.wd[0]", @@ -233,7 +233,7 @@ "dut": "vortex", "result": { "bram": 81.0, - "build_time_s": 50, + "build_time_s": 35, "deep_endpoints": 3229, "deepest_paths": [ "23 dev_ptw/rsp_arb/g_input_select.g_arbiter.g_out_buf_0.out_buf/g_eb2.stream_buffer/g_buffer.buffer_r[30] -> g_clusters_0.cluster/l2tlb/set_mru_r.d[2]", @@ -271,7 +271,7 @@ "g_clusters_*_cluster/g_sockets_*_socket/g_cores_*_core.icache_bus_if_0_rsp_ready": 1, "g_clusters_*_cluster/g_sockets_*_socket/g_cores_*_core.kmu_bus_if_ready": 1 }, - "lut": 129759, + "lut": 129868, "lutram": 10082, "max_levels": 23, "pred_fmax_mhz": 265.9, diff --git a/ci/baselines/synthesis/beacon/dxa.json b/ci/baselines/synthesis/beacon/dxa.json index 2e22b25e36..cf0fd60f00 100644 --- a/ci/baselines/synthesis/beacon/dxa.json +++ b/ci/baselines/synthesis/beacon/dxa.json @@ -1,5 +1,22 @@ { "dxa": { + "accepted": { + "against": "1061088aa91bd6f295d91945832acdc8408223c4", + "regressions": [ + { + "after": 13, + "before": 11, + "kind": "deeper", + "name": "dxa_core/g_workers_0.worker/addr_gen/lines_left_r.d" + }, + { + "after": 753.0, + "before": 568.0, + "kind": "area", + "name": "lutram" + } + ] + }, "clock_mhz": 300, "config_hash": "0eaf10f31ff7d9ff", "configs": "-DVX_CFG_NUM_THREADS=16 -DVX_CFG_NUM_WARPS=16", @@ -7,7 +24,7 @@ "result": { "bram": 0.0, "build_time_s": 20, - "deep_endpoints": 2081, + "deep_endpoints": 61, "deepest_paths": [ "15 dxa_core/g_workers_0.worker/addr_gen/gmem_cursor_r[0] -> dxa_core/g_workers_0.worker/addr_gen/smem_byte_addr_r.d[8]", "15 dxa_core/g_workers_0.worker/addr_gen/gmem_cursor_r[0] -> dxa_core/g_workers_0.worker/addr_gen/smem_byte_addr_r.d[9]", @@ -16,25 +33,25 @@ "15 dxa_core/g_workers_0.worker/addr_gen/gmem_cursor_r[0] -> dxa_core/g_workers_0.worker/addr_gen/smem_byte_addr_r.d[12]", "15 dxa_core/g_workers_0.worker/addr_gen/gmem_cursor_r[0] -> dxa_core/g_workers_0.worker/addr_gen/smem_byte_addr_r.d[13]", "15 dxa_core/g_workers_0.worker/addr_gen/gmem_cursor_r[0] -> dxa_core/g_workers_0.worker/addr_gen/smem_byte_addr_r.d[14]", - "15 dxa_core/g_workers_0.worker/gmem_req/oob_pending_r[0] -> dxa_core/g_workers_0.worker/smem_wr/pend_data_r.d[64]", - "15 dxa_core/g_workers_0.worker/gmem_req/oob_pending_r[0] -> dxa_core/g_workers_0.worker/smem_wr/pend_data_r.d[65]", - "15 dxa_core/g_workers_0.worker/gmem_req/oob_pending_r[0] -> dxa_core/g_workers_0.worker/smem_wr/pend_data_r.d[66]" + "14 dxa_core/g_workers_0.worker/addr_gen/gmem_cursor_r[0] -> dxa_core/g_workers_0.worker/addr_gen/smem_byte_addr_r.d[3]", + "14 dxa_core/g_workers_0.worker/addr_gen/gmem_cursor_r[0] -> dxa_core/g_workers_0.worker/addr_gen/smem_byte_addr_r.d[4]", + "14 dxa_core/g_workers_0.worker/addr_gen/gmem_cursor_r[0] -> dxa_core/g_workers_0.worker/addr_gen/smem_byte_addr_r.d[5]" ], "dsp": 9, - "endpoints": 11408, + "endpoints": 10547, "env": { "circt": "CIRCT 892a65a01", "device": "xcu55c-fsvh2892-2L-e", "foldsim": "foldsim d8350bc0f", "xlen": 32 }, - "ff": 9328, + "ff": 8213, "fix_levels": 12, "interfaces": {}, - "lut": 10675, - "lutram": 568, + "lut": 9942, + "lutram": 753, "max_levels": 15, - "pred_fmax_mhz": 298.6, + "pred_fmax_mhz": 307.5, "risk_endpoints": 0, "tied_bits": 1, "tied_ports": [ @@ -47,12 +64,17 @@ "units": { "dxa_core/desc_table/desc_store": 8, "dxa_core/g_workers_*_worker/addr_gen": 15, - "dxa_core/g_workers_*_worker/gmem_req": 9, + "dxa_core/g_workers_*_worker/gmem_req": 8, + "dxa_core/g_workers_*_worker/gmem_req/free_fifo": 9, + "dxa_core/g_workers_*_worker/gmem_req/free_fifo/pending_size": 10, + "dxa_core/g_workers_*_worker/gmem_req/oob_fifo": 9, + "dxa_core/g_workers_*_worker/gmem_req/oob_fifo/pending_size": 9, "dxa_core/g_workers_*_worker/setup": 12, - "dxa_core/g_workers_*_worker/smem_wr": 15 + "dxa_core/g_workers_*_worker/smem_wr": 13, + "dxa_core/g_workers_*_worker/xfer_table": 9 }, "uram": 0, - "watch_endpoints": 4353, + "watch_endpoints": 2383, "watch_levels": 8 } } diff --git a/ci/baselines/synthesis/beacon/graphics.json b/ci/baselines/synthesis/beacon/graphics.json index 4fd2f3a012..96c21f0486 100644 --- a/ci/baselines/synthesis/beacon/graphics.json +++ b/ci/baselines/synthesis/beacon/graphics.json @@ -1,29 +1,12 @@ { "gfx": { - "accepted": { - "against": "26d2bc4b5409a35a111e8316ac3a87d07b15fc80", - "regressions": [ - { - "after": 14, - "before": null, - "kind": "new", - "name": "graphics/g_raster_core_0.raster_core/raster_slices_0.raster_earlyz/quad_zprod.d" - }, - { - "after": 1071, - "before": 1073, - "kind": "ties", - "name": "tied_bits" - } - ] - }, "clock_mhz": 250, "config_hash": "d39e5baadbeea03c", "configs": "-DVX_CFG_NUM_THREADS=16 -DVX_CFG_NUM_WARPS=16", "dut": "gfx", "result": { "bram": 183.5, - "build_time_s": 155, + "build_time_s": 180, "deep_endpoints": 1738, "deepest_paths": [ "19 g_rtu_core_0.rtu_core/scheduler/g_recip_pe.recip_tags/g_shift.g_partial_reset.pipe_free[219] -> g_rtu_core_0.rtu_core/scheduler/g1_idx.d[4]", @@ -189,30 +172,13 @@ } }, "gfxvm": { - "accepted": { - "against": "26d2bc4b5409a35a111e8316ac3a87d07b15fc80", - "regressions": [ - { - "after": 14, - "before": null, - "kind": "new", - "name": "graphics/g_raster_core_0.raster_core/raster_slices_0.raster_earlyz/quad_zprod.d" - }, - { - "after": 1073, - "before": 1075, - "kind": "ties", - "name": "tied_bits" - } - ] - }, "clock_mhz": 250, "config_hash": "dda6e15b71ddde55", "configs": "-DVX_CFG_NUM_THREADS=16 -DVX_CFG_NUM_WARPS=16", "dut": "gfxvm", "result": { "bram": 183.5, - "build_time_s": 160, + "build_time_s": 175, "deep_endpoints": 1889, "deepest_paths": [ "19 g_rtu_core_0.rtu_core/scheduler/g_recip_pe.recip_tags/g_shift.g_partial_reset.pipe_free[219] -> g_rtu_core_0.rtu_core/scheduler/g1_idx.d[4]", @@ -227,20 +193,20 @@ "18 g_rtu_core_0.rtu_core/scheduler/g_recip_pe.recip_tags/g_shift.g_partial_reset.pipe_free[219] -> g_rtu_core_0.rtu_core/scheduler/ctx_arbiter/g_model1.reqs_mask.d[29]" ], "dsp": 1140, - "endpoints": 328937, + "endpoints": 328940, "env": { "circt": "CIRCT 892a65a01", "device": "xcu55c-fsvh2892-2L-e", "foldsim": "foldsim d8350bc0f", "xlen": 32 }, - "ff": 415294, + "ff": 415297, "fix_levels": 12, "interfaces": {}, "lut": 331144, "lutram": 14557, "max_levels": 19, - "pred_fmax_mhz": 256.3, + "pred_fmax_mhz": 255.6, "risk_endpoints": 475, "tied_bits": 1073, "tied_ports": [ @@ -398,7 +364,7 @@ "ummu/tlb/mshr/reqpool": 10 }, "uram": 0, - "watch_endpoints": 18305, + "watch_endpoints": 18364, "watch_levels": 8 } }, @@ -595,7 +561,7 @@ "dut": "tex", "result": { "bram": 0.0, - "build_time_s": 70, + "build_time_s": 60, "deep_endpoints": 0, "deepest_paths": [ "11 tex_core/tex_addr/pipe_reg0/g_pipe.g_partial_reset.pipe_free[4197] -> tex_core/tex_addr/pipe_reg1/g_pipe.g_partial_reset.pipe_free.d[831]", diff --git a/ci/baselines/synthesis/beacon/tensor.json b/ci/baselines/synthesis/beacon/tensor.json index 7fe0d2e34c..4c7916845f 100644 --- a/ci/baselines/synthesis/beacon/tensor.json +++ b/ci/baselines/synthesis/beacon/tensor.json @@ -6,7 +6,7 @@ "dut": "tcu", "result": { "bram": 0.0, - "build_time_s": 40, + "build_time_s": 25, "deep_endpoints": 2294, "deepest_paths": [ "25 tcu_unit/g_blocks_0.tcu_block/tcu_core/g_i_0.g_j_0.fedp/pipe_acc/g_pipe.g_no_reset.pipe[39] -> tcu_unit/g_blocks_0.tcu_block/tcu_core/g_i_0.g_j_0.fedp/pipe_norm_round/g_pipe.g_no_reset.pipe.d[6]", @@ -31,10 +31,10 @@ "ff": 44475, "fix_levels": 12, "interfaces": {}, - "lut": 117205, + "lut": 96340, "lutram": 2083, "max_levels": 25, - "pred_fmax_mhz": 277.7, + "pred_fmax_mhz": 274.0, "risk_endpoints": 17, "tied_bits": 0, "tied_ports": [], @@ -63,13 +63,19 @@ }, "tensor": { "accepted": { - "against": "26d2bc4b5409a35a111e8316ac3a87d07b15fc80", + "against": "1061088aa91bd6f295d91945832acdc8408223c4", "regressions": [ { - "after": 4, - "before": 6, - "kind": "ties", - "name": "tied_bits" + "after": 13, + "before": 11, + "kind": "deeper", + "name": "dxa_core/g_workers_0.worker/addr_gen/lines_left_r.d" + }, + { + "after": 12, + "before": 11, + "kind": "deeper", + "name": "dxa_core/g_workers_0.worker/smem_wr/replay_onehot_r.d" } ] }, @@ -79,8 +85,8 @@ "dut": "tensor", "result": { "bram": 114.5, - "build_time_s": 85, - "deep_endpoints": 4761, + "build_time_s": 130, + "deep_endpoints": 2751, "deepest_paths": [ "25 g_cores_0.tcu_unit/g_blocks_0.tcu_block/tcu_core/g_i_0.g_j_0.fedp/pipe_acc/g_pipe.g_no_reset.pipe[39] -> g_cores_0.tcu_unit/g_blocks_0.tcu_block/tcu_core/g_i_0.g_j_0.fedp/pipe_norm_round/g_pipe.g_no_reset.pipe.d[14]", "25 g_cores_0.tcu_unit/g_blocks_0.tcu_block/tcu_core/g_i_0.g_j_0.fedp/pipe_acc/g_pipe.g_no_reset.pipe[39] -> g_cores_0.tcu_unit/g_blocks_0.tcu_block/tcu_core/g_i_0.g_j_0.fedp/pipe_norm_round/g_pipe.g_no_reset.pipe.d[17]", @@ -94,21 +100,21 @@ "25 g_cores_0.tcu_unit/g_blocks_0.tcu_block/tcu_core/g_i_0.g_j_1.fedp/pipe_acc/g_pipe.g_no_reset.pipe[39] -> g_cores_0.tcu_unit/g_blocks_0.tcu_block/tcu_core/g_i_0.g_j_1.fedp/pipe_norm_round/g_pipe.g_no_reset.pipe.d[18]" ], "dsp": 267, - "endpoints": 170647, + "endpoints": 169785, "env": { "circt": "CIRCT 892a65a01", "device": "xcu55c-fsvh2892-2L-e", "foldsim": "foldsim d8350bc0f", "xlen": 32 }, - "ff": 161531, + "ff": 160416, "fix_levels": 12, "interfaces": {}, - "lut": 259747, - "lutram": 12672, + "lut": 216975, + "lutram": 12857, "max_levels": 25, "pred_fmax_mhz": 253.4, - "risk_endpoints": 411, + "risk_endpoints": 358, "tied_bits": 4, "tied_ports": [ { @@ -144,9 +150,14 @@ "dcache/g_core_arb_*_core_arb/req_arb/g_input_select_g_arbiter_g_out_buf_*_out_buf/g_eb2_stream_buffer": 8, "dxa_core/desc_table/desc_store": 8, "dxa_core/g_workers_*_worker/addr_gen": 15, - "dxa_core/g_workers_*_worker/gmem_req": 9, + "dxa_core/g_workers_*_worker/gmem_req": 8, + "dxa_core/g_workers_*_worker/gmem_req/free_fifo": 9, + "dxa_core/g_workers_*_worker/gmem_req/free_fifo/pending_size": 10, + "dxa_core/g_workers_*_worker/gmem_req/oob_fifo": 9, + "dxa_core/g_workers_*_worker/gmem_req/oob_fifo/pending_size": 9, "dxa_core/g_workers_*_worker/setup": 12, - "dxa_core/g_workers_*_worker/smem_wr": 16, + "dxa_core/g_workers_*_worker/smem_wr": 15, + "dxa_core/g_workers_*_worker/xfer_table": 9, "g_cores_*_g_lsu_mem_path_*_mem_path/g_coalescing_mem_coalescer/req_ibuf/allocator": 12, "g_cores_*_g_lsu_mem_path_*_mem_path/lsu_scheduler/mem_scheduler/g_req_queue_rw_req_queue/g_ebN_fifo_queue": 9, "g_cores_*_g_lsu_mem_path_*_mem_path/lsu_scheduler/mem_scheduler/req_ibuf/allocator": 11, @@ -156,7 +167,6 @@ "g_cores_*_mem_unit/lmem_unit/g_data_store_*_g_single_port_lmem_store": 9, "g_cores_*_tcu_shared/wgmma": 12, "g_cores_*_tcu_shared/wgmma/tbuf/bbuf": 16, - "g_cores_*_tcu_shared/wgmma/tbuf/bbuf/storage_a_ram": 10, "g_cores_*_tcu_shared/wgmma/tbuf/g_abufs_*_abuf": 15, "g_cores_*_tcu_unit/g_blocks_*_tcu_block/tcu_core": 11, "g_cores_*_tcu_unit/g_blocks_*_tcu_block/tcu_core/g_i_*_g_j_*_fedp/pipe_acc": 15, @@ -198,7 +208,7 @@ "l2cache/g_cache_cache/g_core_req_skid_*_req_skid": 9 }, "uram": 0, - "watch_endpoints": 26346, + "watch_endpoints": 23318, "watch_levels": 8 } } diff --git a/ci/baselines/synthesis/beacon/vm.json b/ci/baselines/synthesis/beacon/vm.json index b483ee3bc2..45274a3594 100644 --- a/ci/baselines/synthesis/beacon/vm.json +++ b/ci/baselines/synthesis/beacon/vm.json @@ -6,7 +6,7 @@ "dut": "vm", "result": { "bram": 159.0, - "build_time_s": 70, + "build_time_s": 50, "deep_endpoints": 3153, "deepest_paths": [ "23 ptw/rsp_arb/g_input_select.g_arbiter.g_out_buf_0.out_buf/g_eb2.stream_buffer/g_buffer.buffer_r[30] -> l2tlb/set_mru_r.d[2]", diff --git a/ci/baselines/synthesis/beacon_asic/core.json b/ci/baselines/synthesis/beacon_asic/core.json index c26d1de552..03938e0cd3 100644 --- a/ci/baselines/synthesis/beacon_asic/core.json +++ b/ci/baselines/synthesis/beacon_asic/core.json @@ -6,8 +6,8 @@ "dut": "cache", "result": { "build_time_s": 25, - "cells": 282062, - "endpoints": 32478, + "cells": 282013, + "endpoints": 32477, "env": { "circt": "CIRCT 892a65a01", "foldsim": "foldsim d8350bc0f", @@ -31,16 +31,16 @@ "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8", "dut": "core", "result": { - "build_time_s": 60, - "cells": 769936, - "endpoints": 73708, + "build_time_s": 40, + "cells": 759542, + "endpoints": 72495, "env": { "circt": "CIRCT 892a65a01", "foldsim": "foldsim d8350bc0f", "pdk": "asap7", "xlen": 32 }, - "ff": 102791, + "ff": 101061, "fmax_mhz": 1051.5, "macros": 16, "max_stages": 30, @@ -100,16 +100,16 @@ "configs": "-DVX_CFG_NUM_THREADS=4 -DVX_CFG_NUM_WARPS=4", "dut": "top", "result": { - "build_time_s": 80, - "cells": 1438152, - "endpoints": 169931, + "build_time_s": 60, + "cells": 1427771, + "endpoints": 168590, "env": { "circt": "CIRCT 892a65a01", "foldsim": "foldsim d8350bc0f", "pdk": "asap7", "xlen": 32 }, - "ff": 305204, + "ff": 303334, "fmax_mhz": 749.1, "macros": 82, "max_stages": 46, diff --git a/ci/baselines/synthesis/beacon_asic/dxa.json b/ci/baselines/synthesis/beacon_asic/dxa.json index 76e9bb3a9f..dc1df46970 100644 --- a/ci/baselines/synthesis/beacon_asic/dxa.json +++ b/ci/baselines/synthesis/beacon_asic/dxa.json @@ -6,7 +6,7 @@ "dut": "dxa", "result": { "build_time_s": 20, - "cells": 84969, + "cells": 85181, "endpoints": 11408, "env": { "circt": "CIRCT 892a65a01", diff --git a/ci/baselines/synthesis/beacon_asic/graphics.json b/ci/baselines/synthesis/beacon_asic/graphics.json index 559a510439..d35325328a 100644 --- a/ci/baselines/synthesis/beacon_asic/graphics.json +++ b/ci/baselines/synthesis/beacon_asic/graphics.json @@ -1,22 +1,11 @@ { "gfx": { - "accepted": { - "against": "26d2bc4b5409a35a111e8316ac3a87d07b15fc80", - "regressions": [ - { - "after": 1063, - "before": 1065, - "kind": "ties", - "name": "tied_bits" - } - ] - }, "clock_mhz": 1000, "config_hash": "f49712b842f2f234", "configs": "-DVX_CFG_NUM_THREADS=4 -DVX_CFG_NUM_WARPS=4", "dut": "gfx", "result": { - "build_time_s": 100, + "build_time_s": 110, "cells": 1875217, "endpoints": 239287, "env": { @@ -115,7 +104,7 @@ "configs": "", "dut": "raster", "result": { - "build_time_s": 15, + "build_time_s": 20, "cells": 76084, "endpoints": 12792, "env": { @@ -152,7 +141,7 @@ "configs": "", "dut": "rtu", "result": { - "build_time_s": 130, + "build_time_s": 55, "cells": 1060729, "endpoints": 105631, "env": { @@ -178,7 +167,7 @@ "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8", "dut": "tex", "result": { - "build_time_s": 45, + "build_time_s": 40, "cells": 376164, "endpoints": 49445, "env": { diff --git a/ci/baselines/synthesis/beacon_asic/tensor.json b/ci/baselines/synthesis/beacon_asic/tensor.json index 4fabf553fa..59d8b93031 100644 --- a/ci/baselines/synthesis/beacon_asic/tensor.json +++ b/ci/baselines/synthesis/beacon_asic/tensor.json @@ -1,31 +1,20 @@ { "tcu": { - "accepted": { - "against": "28fc2c581262d2d7d4e1dc432d50cc303e3dea2e", - "regressions": [ - { - "after": 66855.0, - "before": 47446.0, - "kind": "area", - "name": "ff" - } - ] - }, "clock_mhz": 1000, "config_hash": "1d6c72424d1a993d", "configs": "", "dut": "tcu", "result": { - "build_time_s": 120, - "cells": 1320372, - "endpoints": 44630, + "build_time_s": 30, + "cells": 1136744, + "endpoints": 44318, "env": { "circt": "CIRCT 892a65a01", "foldsim": "foldsim d8350bc0f", "pdk": "asap7", "xlen": 32 }, - "ff": 66855, + "ff": 66539, "fmax_mhz": 893.7, "macros": 0, "max_stages": 37, @@ -37,25 +26,14 @@ } }, "tensor": { - "accepted": { - "against": "26d2bc4b5409a35a111e8316ac3a87d07b15fc80", - "regressions": [ - { - "after": 4, - "before": 6, - "kind": "ties", - "name": "tied_bits" - } - ] - }, "clock_mhz": 1000, "config_hash": "2992cc36d736afff", "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8", "dut": "tensor", "result": { - "build_time_s": 65, - "cells": 860583, - "endpoints": 89468, + "build_time_s": 70, + "cells": 769545, + "endpoints": 89466, "env": { "circt": "CIRCT 892a65a01", "foldsim": "foldsim d8350bc0f", diff --git a/ci/baselines/synthesis/beacon_asic/vm.json b/ci/baselines/synthesis/beacon_asic/vm.json index f007f60c6a..3b8dd9f75f 100644 --- a/ci/baselines/synthesis/beacon_asic/vm.json +++ b/ci/baselines/synthesis/beacon_asic/vm.json @@ -5,9 +5,9 @@ "configs": "-DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8", "dut": "vm", "result": { - "build_time_s": 65, - "cells": 1156412, - "endpoints": 115494, + "build_time_s": 55, + "cells": 1156102, + "endpoints": 115499, "env": { "circt": "CIRCT 892a65a01", "foldsim": "foldsim d8350bc0f", diff --git a/ci/testcases/dxa.yaml b/ci/testcases/dxa.yaml index 636c4b0a03..cd18af390c 100644 --- a/ci/testcases/dxa.yaml +++ b/ci/testcases/dxa.yaml @@ -661,6 +661,19 @@ tests: shape: threads: [4, 16] +# Overlapped transfers: two resident TMEM GEMM CTAs stream their stages behind +# a 300-cycle memory, so the reads of several transfers share a worker's +# latency-sized in-flight pool while earlier transfers still drain. +- id: model_parity-tmem-lat300 + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TMEM_COLS=512 -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DB_KMAJOR -DVX_CFG_PLATFORM_MEMORY_LATENCY=300 + # The DXA-staged WGMMA accumulator stored with vx_stm # (VX_CFG_EXT_LDST_MATRIX_ENABLE). - id: sgemm_tcu_wg_dxa-ldm diff --git a/ci/testcases/tensor_wg.yaml b/ci/testcases/tensor_wg.yaml index b427a2c0e4..f43406f653 100644 --- a/ci/testcases/tensor_wg.yaml +++ b/ci/testcases/tensor_wg.yaml @@ -397,3 +397,273 @@ tests: configs: -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 args: -N 32 -D 16 -c 8 -t 8 touches: [hw/rtl/tcu, hw/rtl/VX_gpu_pkg.sv, sim/simx/tcu, sim/simx/fragment_layout.h, sw/kernel/include/vx_tensor.h, tests/regression/flash_attn] + +# Tensor memory: the accumulator in TMEM. A producer warp stages the K loop +# for an MMA warp's tc.mma ops. +- id: sgemm_tcu_tmem + via: blackbox + drivers: + - simx + - rtlsim + app: sgemm_tcu_tmem + xlen: [32, 64] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 +- id: model_parity-tmem + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 +# Sparse MMAs: 2:4 compressed A, K-tile metadata read from TMEM. +- id: sgemm_tcu_tmem-sparse + via: blackbox + drivers: + - simx + - rtlsim + app: sgemm_tcu_tmem + xlen: [32, 64] + args: -m64 -n64 -k64 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_SPARSE +- id: model_parity-tmem-sparse + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_SPARSE +# tc.cp (tcgen05.cp): the TCU moves the staged sparse metadata into TMEM. +- id: sgemm_tcu_tmem-sparse-cp + via: blackbox + drivers: + - simx + - rtlsim + app: sgemm_tcu_tmem + xlen: [32, 64] + args: -m64 -n64 -k64 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_SPARSE -DTMEM_CP +- id: model_parity-tmem-sparse-cp + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_SPARSE -DTMEM_CP +# A from TMEM: the MMA reads A over the TMEM port instead of loading a stage. +- id: model_parity-tmem-a + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TMEM_COLS=512 -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_A +# Sparse A from TMEM: compressed A and its tc.cp-copied metadata both in TMEM. +- id: model_parity-tmem-sparse-a + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TMEM_COLS=512 -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_SPARSE -DTMEM_CP -DTMEM_A +# Block-major B (ldb = 0): row-major B staged by the DXA BlockMajor layout. +# Tensor memory without FEDP2K: a tile spans two FEDP-width K-tiles, and a +# sparse K-tile carries one metadata row. NT=16 is where FEDP2K cannot build. +- id: model_parity-tmem-nofedp2k + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 +# 512 columns keep every resident CTA's allocation from waiting on another's, +# so the retired-instruction count does not depend on timing. +- id: model_parity-tmem-sparse-nofedp2k + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TMEM_COLS=512 -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_SPARSE +- id: model_parity-tmem-nofedp2k-nt16 + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=16 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TMEM_COLS=512 -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_SPARSE +# FlashAttention-4 schedule: two Q tiles ping-pong between softmax warp groups and +# the TCU, so TMEM transfers run alongside the CTA's MMAs on other columns. +- id: flashattention4 + via: blackbox + drivers: + - simx + - rtlsim + app: flashattention4 + xlen: [32, 64] + args: -l64 -n32 -d64 -b2 -c1 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=16 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TMEM_COLS=512 -DVX_CFG_EXT_TFU_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 +- id: model_parity-flashattention4 + check: model_parity + via: blackbox + app: flashattention4 + xlen: [32] + args: -l64 -n32 -d64 -b4 -c1 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=16 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TMEM_COLS=512 -DVX_CFG_EXT_TFU_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 +# MX MMAs on TMEM: the step's A and B scales from the side column (A latched +# by the prologue, B rows read on the free RAM port), copied in by tc.cp. +- id: sgemm_tcu_tmem_mx-mxfp8 + via: blackbox + drivers: + - simx + - rtlsim + app: sgemm_tcu_tmem_mx + xlen: [32, 64] + args: -m32 -n64 -k128 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_MX_ENABLE -DVX_CFG_TCU_FP8_ENABLE -DVX_CFG_TCU_FP4_ENABLE -DVX_CFG_TCU_MXFP4_ENABLE -DVX_CFG_TCU_NVFP4_ENABLE + -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=mxfp8 -DOTYPE=fp32 -DWGMMA_NRC=32 +- id: sgemm_tcu_tmem_mx-mxfp4 + via: blackbox + drivers: + - simx + - rtlsim + app: sgemm_tcu_tmem_mx + xlen: [32, 64] + args: -m32 -n64 -k128 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_MX_ENABLE -DVX_CFG_TCU_FP8_ENABLE -DVX_CFG_TCU_FP4_ENABLE -DVX_CFG_TCU_MXFP4_ENABLE -DVX_CFG_TCU_NVFP4_ENABLE + -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=mxfp4 -DOTYPE=fp32 -DWGMMA_NRC=8 +- id: sgemm_tcu_tmem_mx-nvfp4 + via: blackbox + drivers: + - simx + - rtlsim + app: sgemm_tcu_tmem_mx + xlen: [32, 64] + args: -m32 -n64 -k128 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_MX_ENABLE -DVX_CFG_TCU_FP8_ENABLE -DVX_CFG_TCU_FP4_ENABLE -DVX_CFG_TCU_MXFP4_ENABLE -DVX_CFG_TCU_NVFP4_ENABLE + -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=nvfp4 -DOTYPE=fp32 -DWGMMA_NRC=32 -DTCU_MX_TLS +- id: model_parity-tmem-mx + check: model_parity + via: blackbox + app: sgemm_tcu_tmem_mx + xlen: [32] + args: -m32 -n64 -k128 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_MX_ENABLE -DVX_CFG_TCU_FP8_ENABLE -DVX_CFG_TCU_FP4_ENABLE -DVX_CFG_TCU_MXFP4_ENABLE -DVX_CFG_TCU_NVFP4_ENABLE + -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=mxfp8 -DOTYPE=fp32 -DWGMMA_NRC=32 +# TMEM builds without per-warp MMAs (VX_CFG_TCU_WMMA_DISABLE): no landing +# queue or metadata store; sparse metadata and MX scales come from TMEM. +- id: sgemm_tcu_tmem-nowmma-sparse-cp + via: blackbox + drivers: + - simx + - rtlsim + app: sgemm_tcu_tmem + xlen: [32, 64] + args: -m64 -n64 -k64 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_WMMA_DISABLE -DVX_CFG_TCU_SPARSE_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 -DTMEM_SPARSE -DTMEM_CP +- id: model_parity-tmem-nowmma + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_WMMA_DISABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 +- id: sgemm_tcu_tmem_mx-nowmma-mxfp8 + via: blackbox + drivers: + - simx + - rtlsim + app: sgemm_tcu_tmem_mx + xlen: [32] + args: -m32 -n64 -k128 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_WMMA_DISABLE -DVX_CFG_TCU_MX_ENABLE -DVX_CFG_TCU_FP8_ENABLE -DVX_CFG_TCU_FP4_ENABLE -DVX_CFG_TCU_MXFP4_ENABLE -DVX_CFG_TCU_NVFP4_ENABLE + -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=mxfp8 -DOTYPE=fp32 -DWGMMA_NRC=32 +- id: flashattention4-nowmma + via: blackbox + drivers: + - simx + - rtlsim + app: flashattention4 + xlen: [32] + args: -l64 -n32 -d64 -b2 -c1 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=16 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TMEM_COLS=512 -DVX_CFG_TCU_WMMA_DISABLE -DVX_CFG_EXT_TFU_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 +# TMEM across warp widths and input types (fp16 at NT=8 is above). FEDP2K's +# B block fills one LMEM bank row only at NT 8 and 32. +- id: model_parity-tmem-nt4-tf32 + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=4 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DVX_CFG_TCU_TF32_ENABLE -DITYPE=tf32 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 +- id: model_parity-tmem-nt16-int8 + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=16 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DVX_CFG_TCU_INT8_ENABLE -DITYPE=int8 -DOTYPE=int32 -DWGMMA_NRC=32 -DPIPE_N=2 +- id: model_parity-tmem-nt32-bf16 + check: model_parity + via: blackbox + app: sgemm_tcu_tmem + xlen: [32] + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=32 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=bf16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 +# The tensor-memory GEMM's cycles (the redo's 64x64x256 workload). +- id: perf_gate-tmem + check: perf_gate + via: blackbox + app: sgemm_tcu_tmem + args: -m64 -n64 -k256 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_ISSUE_WIDTH=4 -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE + -DVX_CFG_TCU_FEDP2K -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_TCU_TYPE_DPI -DVX_CFG_NUM_ALU_BLOCKS=1 -DVX_CFG_NUM_LSU_BLOCKS=1 -DVX_CFG_NUM_FPU_BLOCKS=1 + -DITYPE=fp16 -DOTYPE=fp32 -DWGMMA_NRC=32 -DPIPE_N=2 diff --git a/docs/designs/dxa_async_copy_multicast.md b/docs/designs/dxa_async_copy_multicast.md index ed3a613e83..ded6c54aac 100644 --- a/docs/designs/dxa_async_copy_multicast.md +++ b/docs/designs/dxa_async_copy_multicast.md @@ -58,8 +58,12 @@ There is no software→global path; DXA is GMEM-read / LMEM-write only. ([`VX_types.toml:278-291`](../../VX_types.toml#L278)) — see §7. - **Config** ([`VX_config.toml:40-58`](../../VX_config.toml#L40)): `VX_CFG_NUM_DXA_UNITS = max(1, ceil(NUM_CORES/8))`, - `VX_CFG_DXA_QUEUE_SIZE = 16`, `VX_CFG_DXA_MAX_INFLIGHT = 8`, - `VX_DCR_DXA_DESC_COUNT = 16`. + `VX_CFG_DXA_QUEUE_SIZE = 16`, `VX_DCR_DXA_DESC_COUNT = 16`. + `VX_CFG_DXA_MAX_INFLIGHT` (line reads in flight per worker) follows + Little's law like the cache MSHRs: the worker's share of the bytes in + flight at `PLATFORM_MEMORY_LATENCY`, capped at one line per cycle of + latency, a power of two in [8, 512]. `VX_CFG_DXA_MAX_XFERS` (transfers in + flight per worker) is `MAX_INFLIGHT / 16` in [2, 16]. - **Perf CSRs** `[csr_mpm_dxa]` 0xB03–0xB08 (transfers, gmem_reads, gmem_dedup, lmem_writes, gmem_latency, noslot_stalls), `VX_DCR_MPM_CLASS_DXA = 16` @@ -85,10 +89,11 @@ queue out to `NUM_DXA_UNITS` workers. | [`VX_dxa_dispatch.sv`](../../hw/rtl/dxa/VX_dxa_dispatch.sv) | `VX_stream_dispatch` routing req+desc to the first idle worker. | | [`VX_dxa_desc_table.sv`](../../hw/rtl/dxa/VX_dxa_desc_table.sv) | DCR-written descriptor RAM, single read port. | | [`VX_dxa_worker.sv`](../../hw/rtl/dxa/VX_dxa_worker.sv) | Structural wiring of the active pipeline + watchdog. | -| [`VX_dxa_setup.sv`](../../hw/rtl/dxa/VX_dxa_setup.sv) | Transfer-lifecycle FSM + decoupled setup engine (overlaps setup with prior drain); 3 DSP multipliers compute rolling-cursor deltas, OOB limits, K-major params. | +| [`VX_dxa_setup.sv`](../../hw/rtl/dxa/VX_dxa_setup.sv) | Issue-lifecycle FSM + decoupled setup engine (overlaps setup with the prior transfer's issue); 3 DSP multipliers compute rolling-cursor deltas, OOB limits, K-major params. | +| [`VX_dxa_xfer_table.sv`](../../hw/rtl/dxa/VX_dxa_xfer_table.sv) | Contexts of the `DXA_MAX_XFERS` transfers a worker has in flight (destination geometry, completion target), with per-transfer issued flag and pending-line count. | | [`VX_dxa_addr_gen.sv`](../../hw/rtl/dxa/VX_dxa_addr_gen.sv) | Single rolling-cursor `gmem_cursor_r` + 4-level ripple odometer; one beat/cycle. | -| [`VX_dxa_gmem_req.sv`](../../hw/rtl/dxa/VX_dxa_gmem_req.sv) | Issues GMEM reads; `slot_table_r[MAX_OUTSTANDING]` per-tag credit model (≤8 inflight); direct-drains responses to smem_wr. | -| [`VX_dxa_smem_wr.sv`](../../hw/rtl/dxa/VX_dxa_smem_wr.sv) | Barrel-shift drain → 1 LMEM word/beat; K-major per-element scatter; serial multicast replay; completion flag on last write. | +| [`VX_dxa_gmem_req.sv`](../../hw/rtl/dxa/VX_dxa_gmem_req.sv) | Issues GMEM reads; `slot_table_r[MAX_OUTSTANDING]` per-tag credit model, each slot tagged with its transfer; direct-drains responses to smem_wr. | +| [`VX_dxa_smem_wr.sv`](../../hw/rtl/dxa/VX_dxa_smem_wr.sv) | Barrel-shift drain → 1 LMEM word/beat, lines of any transfer in arrival order; K-major per-element scatter; serial multicast replay; completion flag on each transfer's final write. | | [`VX_dxa_completion.sv`](../../hw/rtl/dxa/VX_dxa_completion.sv) | Instantiated **per core** in [`VX_mem_unit.sv:183`](../../hw/rtl/core/VX_mem_unit.sv#L183) (LMEM side): snoops bank writes, reads the completion attr, pushes `bar_addr` into a depth-`NUM_WARPS` FIFO → `txbar_bus_if`. | | [`VX_dxa_watchdog.sv`](../../hw/rtl/dxa/VX_dxa_watchdog.sv) | `RUNTIME_ASSERT` on `STALL_TIMEOUT` cycles of no progress. | @@ -107,16 +112,20 @@ queue out to `NUM_DXA_UNITS` workers. 4. **Setup.** `VX_dxa_setup` latches metadata, decodes rank/elem/LAYOUT, computes the initial GMEM base, row length, rolling-cursor deltas, OOB limits, and (LAYOUT=1, rank ≤ 2) `dest_kmajor` + `per_lane_stride_bytes`. - Setup overlaps the previous transfer's drain (staged → active). + Setup overlaps the previous transfer's issue (staged → active). A + transfer starts once the previous one has issued its last line and a + transfer context is free, so up to `DXA_MAX_XFERS` transfers drain at + once and their reads share the in-flight pool. 5. **Address gen.** `VX_dxa_addr_gen` emits one `(cl_addr, smem_byte_addr, byte_offset, valid_length, oob, last)` per cycle from the rolling cursor + ripple odometer. 6. **GMEM read.** `VX_dxa_gmem_req` allocates a `slot_table_r` tag - (≤ `DXA_MAX_INFLIGHT=8`) and issues the read (OOB lines synthesize + (≤ `DXA_MAX_INFLIGHT`) and issues the read (OOB lines synthesize immediate arrival, no bus traffic), direct-draining the response. 7. **SMEM write.** `VX_dxa_smem_wr` barrel-shift-aligns and drains one - LMEM word/beat; the last cache line is deferred so it drains last - carrying the completion flag. K-major mode scatters one element/beat at + LMEM word/beat. The cache line loaded once its transfer has issued every + line and has no other line pending drains last and carries the completion + flag. K-major mode scatters one element/beat at `+per_lane_stride_bytes`. 8. **Multicast fan-out.** If `popcount(cta_mask) > 1`: a priority-encoder walk replays each receiver's writes at `+r·smem_stride` — **serial**, diff --git a/docs/designs/tensor_memory.md b/docs/designs/tensor_memory.md new file mode 100644 index 0000000000..58ca1f5f85 --- /dev/null +++ b/docs/designs/tensor_memory.md @@ -0,0 +1,275 @@ +# Tensor Memory (TMEM) and the `tc.*` Engine + +**Scope:** the per-core tensor memory, the single-thread asynchronous MMA +engine that writes it (`tc.mma`, `tc.cp`, `tc.commit`), the warp transfers +(`tmem.ld` / `tmem.st`), allocation, and the launch support (TMEM budget, +block-aligned warp placement). RTL: +[`VX_tcu_tmem.sv`](../../hw/rtl/tcu/VX_tcu_tmem.sv), +[`VX_cta_dispatch.sv`](../../hw/rtl/core/VX_cta_dispatch.sv), +[`VX_kmu.sv`](../../hw/rtl/VX_kmu.sv). SimX: +[`tcu_unit.cpp`](../../sim/simx/tcu/tcu_unit.cpp), +[`cta_dispatcher.cpp`](../../sim/simx/cta_dispatcher.cpp). Software: +[`vx_tmem.h`](../../sw/kernel/include/vx_tmem.h). + +The capability set follows Blackwell's `tcgen05`: accumulators in TMEM +instead of registers, a single thread issuing asynchronous MMAs, completion +signalled to a barrier, sparse metadata in TMEM, A from TMEM, and +shared-memory-to-TMEM copies. The hardware is built from the TCU's existing +pieces (the WGMMA tile buffers, the blocks' FEDP arrays, the barrier unit); +what is TMEM-specific is the storage, the shape logic on the transfer path, +a small op queue and the allocator. + +--- + +## 1. Geometry and storage + +TMEM is `NUM_TCU_BLOCKS * xtileM` lanes by `VX_CFG_TCU_TMEM_COLS` 32-bit +columns. A lane is an M row of an MMA and a column an N element. TCU block +`b` computes, and stores, lanes `[b*xtileM, (b+1)*xtileM)`. + +Storage is **fragment-major**. A storage row holds one C/D fragment: `tcM` +lanes by `tcN` columns, word `i*tcN + j` = lane `m*tcM + i`, column +`g*tcN + j`. Column group `g`'s two M steps are row `g` of two RAMs per +block (`VX_dp_ram`, `NT*32` bits wide, `COLS/tcN` deep). An MMA step reads +C from, and writes D to, one row of one RAM with identity wiring; the +transfer shapes (§3) are the only place data is rearranged. D, metadata and +A-from-TMEM columns, and transfer column addresses, are multiples of `tcN`. + +At XLEN=64, `tmem.ld` NaN-boxes the 32-bit cells into the FP registers. + +## 2. ISA + +| Instruction | Operands | Semantics | +|---|---|---| +| `tc.mma` (custom-0, funct7 6, funct3 4) | rs1 idesc, rs2 A, rs3 (rd field) B | One K step: D (+)= A·B, asynchronous, from thread 0. | +| `tc.cp` (funct3 2) | rs1 `{cols, col}`, rs2 source | Copies pre-packed fragment rows from shared memory, in order with `tc.mma`. | +| `tc.commit` (funct3 1) | rs1 barrier, rs2 arrival count | Arrives once the core's earlier `tc.mma` / `tc.cp` have completed. | +| `tmem.ld` / `tmem.st` (funct7 5, funct3 0/1, +4 = fragment shape) | rs1 taddr, rd FP base, rs2 count-1 | Warp transfer to/from the issuing block's lanes. | +| `tmem.alloc` (funct3 6) | rs1 columns | First column of a power-of-two run, owned by the CTA, in thread 0 only; waits until free. | +| `tmem.dealloc` (funct3 7) | rs1 column, rs2 columns | Frees the CTA's run. | + +**Instruction descriptor** (`tc.mma` rs1, `tmem::make_idesc`): `fmt_s` [4:0], +sparse [5], A in TMEM [6], `acc_init` [7] (D is overwritten, Blackwell's +`enable_input_d` = 0), `n_frag - 1` [14:8], D's first fragment group [22:15], +metadata column [31:23]. The output format is fp32 (int32 for integer +inputs). A and B are the WGMMA shared-memory descriptors +(`tensor::smem_matrix_desc`, offset and leading bytes, never 0: A is +row-major and B K-major, as DXA loads them); with A in TMEM (a `tmem::tmem_col` operand, which sets +bit 6), rs2 is A's TMEM column. There is no descriptor state: every `tc.mma` +carries its whole description, and software loops over K, one instruction +per `fedpK` words of K, as on Blackwell. + +**`tc.cp` source** is TMEM's storage order: column group by group, block by +block, M step by M step, NT words each. The copy moves whole LMEM bank rows +(the source and size are bank-row multiples), each response writing whole +fragment rows with fixed wiring. + +**Sparse metadata** is stored pre-packed: for each K step a lane holds, in +one fragment group from the metadata column, the `VX_tcu_sp_mux` rows of the +step's lower then upper `TC_K` words. It is read once per instruction. + +**MX scale factors** (`fmt_s` an MX format) use the same side column. A step +takes `SF = TCU_MX_MAX_SF` scales per A row and per B column +(`tensor::mx_max_fedp_sf(fedpK)`); scale `s` covers the step's K elements +from `s * step_elems / SF`. From the side column: + +- A: lane `l` (an M row), columns `side + s/4`, byte `s % 4`: one fragment + group, read by the prologue with the metadata's read and latched. +- B: a dense byte stream, byte `q = col * SF + s`, in rows of `NT*4` bytes; + row `r` is M step 1 of block `r % NUM_TCU_BLOCKS`, at group + `side/TC_N + 1 + r / NUM_TCU_BLOCKS`. A step `(m = 0, n)` whose `n` starts a + row reads it on the RAM its C read leaves free; every block takes it, as + they all take B. + +So the scales cost no MMA cycles and no per-step latch beyond one row. A +kernel copies them in with `tc.cp` like the metadata +(`tests/regression/sgemm_tcu_tmem_mx`). + +## 3. Transfers (`tmem.ld` / `tmem.st`) + +A warp's transfers reach only its own block's lanes: warp `w` issues to +block `w % ISSUE_WIDTH`, and `taddr`'s lane is that block's first. Each +block has its own transfer port; nothing crosses blocks. One uop moves one +register: + +- **Lane per thread** (`LANE_PER_THREAD`): thread `t` holds lane `t % xtileM`; + register `r`, column `r*TPL + t/xtileM`. One read or write of both RAMs at + one row; a per-thread `tcN/TPL`:1 select. FlashAttention's softmax uses it + (a thread owns a row, so max and sum need no shuffles). +- **Fragment** (`FRAGMENT`): register `r` is the fragment of M step `r % 2`, + columns `(r/2)*tcN`, in the WGMMA accumulator register layout. One read or + write of one RAM, identity data. Epilogues use it. + +A step's D write-back, then a `tc.cp` row, have a block's write port before +a store; a transfer read has the read port before the engine (which loses +the cycle). + +## 4. The engine + +`tc.mma`, `tc.cp`, `tc.commit` and the allocation ops reach a scalar-only +port (thread 0's operands; a block arbiter). `tc.mma` and `tc.cp` enter a +4-deep in-order queue. A `tc.commit` rides on the youngest op that has not +left the engine (up to two per op); with none it queues as an entry of its +own. + +The engine runs the queue head: + +- **`tc.mma`:** a cycle to set the descriptors, a prologue that reads the + metadata row and/or A's `fedpK/tcN` fragment groups (all blocks in + parallel), then the (m, n) walk, one step per cycle on all blocks in + lockstep over the tile buffers (A stripes per block, B shared). A step waits while its C fragment's write-back + is in flight (the consecutive-MMA row hazard, the only hazard checked in + hardware). +- **`tc.cp`:** waits for the steps in flight to be written back, then reads + one bank row at a time through the tile buffers' LMEM port. + +An op leaving the engine posts its commits with the count of steps issued +so far; a commit arrives on its barrier once that many steps have been +written back, one arrival per cycle through `VX_tcu_bar_if`. + +## 5. Ordering contract + +As on Blackwell, ordering between transfers and MMAs is the software's: +`tmem.ld` of columns an MMA writes needs that MMA's `tc.commit` and a +barrier wait; an MMA reading columns a warp stored needs `tmem::wait_st` +(`vx_wsync`) and a barrier first. The hardware has no range interlock. SimX +checks the contract: a transfer or dealloc touching columns of an +unsettled op of its CTA aborts with the op it raced. + +**Undefined behavior.** As in PTX, misuse of tensor memory is undefined: +the hardware does not check it, and the result is unspecified (it may +overwrite other columns, another CTA's included, or wait forever). RTL +simulation asserts on each case below and SimX checks the ordering +contract; an FPGA reports nothing, as for the rest of the core (a +misaligned access or an illegal instruction is also checked only in +simulation). Undefined: + +- a `tc.mma` whose D, A or metadata columns are unaligned or out of range, + or whose shared-memory descriptors are invalid; +- a `tc.cp` whose columns, size or source are unaligned or out of range; +- a `tmem.alloc` or `tmem.dealloc` size that is not a power-of-two number + of 32-column chunks within TMEM, a dealloc of columns its CTA does not + own, and allocations beyond the launch's TMEM budget (§6); +- a transfer of another block's lanes or at a column that is not a + multiple of `tcN`, and one issued with any thread inactive (a transfer is + warp-wide, as `tcgen05.ld/st` are `.sync.aligned`); +- a `tc.*` or allocation op issued without thread 0 active; +- breaking the ordering contract above; +- a WGMMA instruction in a TMEM build (§7). + +## 6. Allocation and launch + +`tmem.alloc` waits off the scalar port until a run of its size is free, so +a waiting allocation never blocks other ops. Runs are tagged with the owner +CTA, and a CTA's runs are freed when its last warp retires; a dealloc of +another CTA's run is undefined (§5). + +A kernel declares its CTAs' TMEM in `vx_launch_info_t::tmem_cols` (the KMU +DCR `VX_DCR_KMU_TMEM_COLS`). The budget, rounded up to a power-of-two run, +counts toward occupancy like LMEM, so co-resident CTAs' allocations always +fit and an allocation within budget never waits on a CTA that is not +running. A launch with a budget also places its warps block-aligned: rank +`r` runs on launch lane, and TCU block, `r % ISSUE_WIDTH` (TMEM builds have +one launch lane per block). The runtime writes the DCR only when a budget +is set or was set, so other launches are unchanged. + +## 7. TMEM builds and WGMMA + +A TMEM build drives the tile buffers from the engine, so warps issue no +WGMMA: the per-warp WGMMA expansion and its front-end logic are left out +(`TCU_WARP_WGMMA`), and a WGMMA instruction is undefined (§5): simulation +rejects it at decode. The tile buffers keep only the layouts a `tc.mma` +takes, row-major A and K-major B, which DXA loads. + +WMMA stays unless `VX_CFG_TCU_WMMA_ENABLE` is off (`-DVX_CFG_TCU_WMMA_DISABLE`, +TMEM builds only). Without it, `tcu.wmma` and `tcu.ld` are undefined and +rejected at decode, and every core op is a tensor op's step: the core reads +its operands from the tile buffers only, its results go straight to TMEM +with no landing queue or ordering queue, and sparse and MX builds lose the +per-block metadata store (tensor ops take metadata and scales from TMEM). +Beacon on `tcuw` (§8 configuration): 106,551 → 101,447 LUT and 62,412 → +61,220 FF dense; sparse and every-format builds save 10.9k and 20.4k LUT +and 1,592 flip-flops. No real Blackwell kernel mixes `mma.sync` with +`tcgen05` in one launch, so a TMEM kernel loses nothing. + +## 8. Results + +4 TCU blocks, 8 warps, issue width 4, FEDP2K, fp16 → fp32, TMEM 512 +columns (NT=8: 32 lanes, 64 KB; NT=32: 128 lanes, 256 KB). Area: Beacon on +the `tcuw` DUT (`VX_tcu_unit` + `VX_tcu_shared` at full issue width, TFR +FEDP; `make tcuw-beacon` in `hw/syn/xilinx/dut`). Cycles: rtlsim, SimX in +parentheses, NT=8 with the configs of `ci/testcases/tensor_wg.yaml` (16 +warps). + +**Area against the same build without TMEM** (LUT / FF; TMEM adds 32 block +RAMs at NT=8 and 116 at NT=32): + +| Build | WGMMA only | TMEM | TMEM, no WMMA (§7) | +|---|---|---|---| +| NT=8 FP16 | 100,302 / 60,960 | +6.2% / +2.4% | +1.1% / +0.4% | +| NT=8 sparse | 109,580 / 61,360 | +12.6% / +5.7% | +2.7% / +3.1% | +| NT=8 every format | 1,121,926 / 263,728 | +1.4% / +1.8% | −0.1% / +1.2% | +| NT=32 FP16 | 680,638 / 378,042 | +3.0% / +0.4% | −1.6% / −0.7% | +| NT=32 sparse | 744,037 / 378,538 | +12.5% / +2.6% | +0.5% / +1.3% | + +Most of the sparse cost is the full-K step's second row of 2:4 selects and +its upper-half B gather; a WGMMA-only build shares one select row per FEDP +row. + +| Where they go, FP16 (TMEM − WGMMA only) | NT=8 LUT | NT=8 FF | NT=32 LUT | NT=32 FF | +|---|---|---|---|---| +| `VX_tcu_tmem` | 4,790 | 1,846 | 12,225 | 2,061 | +| A buffers: the A-from-TMEM fill (4 blocks) | 936 | 0 | 4,052 | 0 | +| B buffer: K-major row merging, wide N step | −26 | 41 | 1,242 | 43 | +| Tile-buffer LMEM port: the `tc.cp` master | 105 | 1 | 397 | 1 | +| Blocks: engine steps beside warp ops | 912 | 0 | 3,044 | 0 | +| Blocks: completion order queue | 76 | 76 | 76 | 76 | +| Cores | −256 | −240 | −460 | −336 | +| Warp WGMMA logic left out (§7) | −297 | −272 | −297 | −272 | + +**Inside `VX_tcu_tmem`.** Flip-flops are exact (register widths in the +mapped netlist). LUTs are the netlist's LUTs by source line, scaled to +Beacon's module total, so they are approximate. + +| Part | NT=8 LUT | NT=8 FF | NT=32 LUT | NT=32 FF | +|---|---|---|---|---| +| RAM write data (D, `tc.cp` row, store in either shape) and port control | ~1,730 | 0 | ~7,290 | 0 | +| Op slots: one registered op per block, without the store data | ~870 | 744 | ~1,040 | 840 | +| `tmem.ld` / `tmem.st` transfer units | ~440 | — | ~1,250 | — | +| Response headers and the load/alloc result | — | 391 | — | 511 | +| Engine: decode, walk, step register, prologue, write-back queues | ~640 | 348 | ~1,400 | 347 | +| Shared next-state logic | ~460 | — | ~470 | — | +| Op queue and commits (attach, post, fire) | ~290 | 258 | ~400 | 258 | +| Allocator | ~270 | 64 | ~300 | 64 | +| Row-hazard check | ~50 | 24 | ~55 | 24 | +| `tc.cp` sequencing | ~30 | 17 | ~15 | 17 | + +The RAM write data is one 6-input LUT per bit: a 4-way select whose +encoding is computed once per RAM. A `tmem.st` writes from the block's +dispatch output, which holds its data until accepted, so the op slot keeps +only thread 0's operands. `tmem.alloc` returns its column in thread 0 only, +which thread 0 stores to shared memory for the CTA, as `tcgen05.alloc` does. + +**Builds without TMEM** keep their cycle counts: every non-TMEM perf gate is +unchanged. The tile buffers' K-major write path, a fixed shifter per storage +word, makes WGMMA builds smaller (logic gate `tcu` DUT 117,205 → 96,340 LUT, +same flip-flops and depth). + +**Cycles:** + +| Kernel | TMEM | WGMMA only | Speedup | +|---|---|---|---| +| GEMM 128×128×128 | 47,036 (48,328) | 113,243 (113,900) | 2.41× | +| GEMM 128×128×512 | 184,044 (185,630) | 454,704 (457,421) | 2.47× | +| Sparse GEMM 64×64×64, metadata by `tc.cp` | 8,191 (8,509) | 35,475 (34,047) | 4.33× | +| FlashAttention-4, 4 tiles (`-l64 -n32 -d64 -b4`) | 61,935 (61,588) | — | — | + +The WGMMA builds drop TMEM and run `sgemm_tcu_wg_dxa` (`WGMMA_NRC=32`), the +kernel `sgemm_tcu_tmem` derives from, and `sgemm_tcu_wg_sp`. No WGMMA kernel +matches FlashAttention-4: `flash_attn_tcu_wg` computes softmax with +software `expf` and does not split softmax and MMA across warps. + +## 9. Not covered + +- WGMMA and TMEM in one build. +- `.ws`, `cta_group::2`, `shift`, multicast commit. diff --git a/hw/rtl/VX_define.vh b/hw/rtl/VX_define.vh index 2117c259f5..dab49ea478 100644 --- a/hw/rtl/VX_define.vh +++ b/hw/rtl/VX_define.vh @@ -173,12 +173,49 @@ `endif // Convenience flag: the TCU metadata SRAM is present when any metadata-consuming -// mode (MX or sparse) is enabled. Internal derived macro — not a VX_CFG_* knob. +// mode (MX or sparse) is enabled with per-warp MMAs; tensor ops take theirs from +// tensor memory. Internal derived macro — not a VX_CFG_* knob. +`ifdef VX_CFG_TCU_WMMA_ENABLE `ifdef VX_CFG_TCU_MX_ENABLE `define TCU_META_ENABLE `elsif VX_CFG_TCU_SPARSE_ENABLE `define TCU_META_ENABLE `endif +`endif + +// Warps issue WGMMA (the per-warp expansion and its front-end logic) unless +// tensor memory owns the tile buffers: a TMEM build has no warp WGMMA. +`ifdef VX_CFG_TCU_WGMMA_ENABLE +`ifndef VX_CFG_TCU_TMEM_ENABLE + `define TCU_WARP_WGMMA +`endif +`endif + +// A tensor op's sparse step fills the doubled-K FEDP with compressed A (both +// half-K metadata banks of its m-step). Internal derived macro. +`ifdef VX_CFG_TCU_TMEM_ENABLE +`ifdef VX_CFG_TCU_SPARSE_ENABLE +`ifdef VX_CFG_TCU_FEDP2K + `define TCU_SP_FULLK +`endif +`endif +`endif + +`ifndef VX_CFG_TCU_WMMA_ENABLE + `ifndef VX_CFG_TCU_TMEM_ENABLE + `error "disabling VX_CFG_TCU_WMMA_ENABLE requires VX_CFG_TCU_TMEM_ENABLE" + `endif +`endif + +// Tensor jobs drive the WGMMA tile buffers. +`ifdef VX_CFG_TCU_TMEM_ENABLE + `ifndef VX_CFG_TCU_WGMMA_ENABLE + `error "VX_CFG_TCU_TMEM_ENABLE requires VX_CFG_TCU_WGMMA_ENABLE" + `endif + `ifndef VX_CFG_EXT_DXA_ENABLE + `error "VX_CFG_TCU_TMEM_ENABLE requires VX_CFG_EXT_DXA_ENABLE" + `endif +`endif // Integer mul/div via DPI: simulation only (not synthesis) with DPI enabled. // Internal derived macros — not VX_CFG_* knobs. diff --git a/hw/rtl/VX_gpu_pkg.sv b/hw/rtl/VX_gpu_pkg.sv index afb37c1a4e..cf3109d190 100644 --- a/hw/rtl/VX_gpu_pkg.sv +++ b/hw/rtl/VX_gpu_pkg.sv @@ -1064,6 +1064,18 @@ package VX_gpu_pkg; `ifdef TCU_META_ENABLE // TCU_LD — warp-level load into a metadata SRAM namespace. localparam INST_TCU_LD = 4'h5; +`endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + // TMEM transfers (one uop per register), allocation and tcgen05-style ops. + // op_args.tcu: fmt_s = register count - 1 (macro), fmt_d = register index + // (uop), a_from_smem = one lane per register. + localparam INST_TCU_TMEM_LD = 4'h6; + localparam INST_TCU_TMEM_ST = 4'h7; + localparam INST_TCU_TC_CP = 4'h8; + localparam INST_TCU_TMEM_ALLOC = 4'hA; + localparam INST_TCU_TMEM_DEALLOC = 4'hB; + localparam INST_TCU_TC_MMA = 4'hC; + localparam INST_TCU_TC_COMMIT = 4'hD; `endif localparam INST_TCU_BITS = 4; `endif @@ -1132,6 +1144,14 @@ package VX_gpu_pkg; logic is_done; } txbar_t; +`ifdef VX_CFG_TCU_TMEM_ENABLE + // tc.commit arrival. + typedef struct packed { + logic [BAR_ADDR_W-1:0] addr; + logic [BAR_SIZE_W-1:0] size_m1; // arrival count - 1 + } tcu_bar_t; +`endif + typedef struct packed { logic rw; logic [VX_DCR_ADDR_WIDTH-1:0] addr; @@ -1235,7 +1255,10 @@ package VX_gpu_pkg; logic [`VX_CFG_MEM_ADDR_WIDTH-1:0] param; logic [7:0] ctx_id; logic [`VX_CFG_LMEM_LOG_SIZE:0] aligned_lmem_size; - logic [`VX_CFG_NUM_WARPS-1:0] lmem_slots; // see lmem_slots_fit + logic [`VX_CFG_NUM_WARPS-1:0] lmem_slots; // see lmem_slots_fit (and the TMEM budget) + `ifdef VX_CFG_TCU_TMEM_ENABLE + logic tmem; // the CTAs allocate TMEM: block-aligned warps + `endif kmu_args_t args; // .compute | .fragment } kmu_req_t; @@ -1817,6 +1840,11 @@ package VX_gpu_pkg; logic [PERF_CTR_BITS-1:0] wgmma_stalls; // cycles: WGMMA valid but stalled (tbuf or mdata) logic [PERF_CTR_BITS-1:0] wgmma_instrs; // WGMMA µops executed logic [PERF_CTR_BITS-1:0] tbuf_stalls; // cycles: WGMMA valid but stalled (uop cannot enter TCU core because tbuf data not ready) + logic [PERF_CTR_BITS-1:0] mma_busy; // block-cycles a tensor-op MMA step fired + logic [PERF_CTR_BITS-1:0] opnd_waits; // cycles a running tensor op waits on operands + logic [PERF_CTR_BITS-1:0] job_other; // cycles of op drain or tc.cp only + logic [PERF_CTR_BITS-1:0] idle; // cycles with no tensor-op work + logic [PERF_CTR_BITS-1:0] tmem_xfers; // tmem.ld/st transfers } tcu_perf_t; `endif @@ -1993,12 +2021,11 @@ package VX_gpu_pkg; localparam DXA_LMEM_OUT_TAG_W = DXA_LMEM_TAG_W + `ARB_SEL_BITS(`VX_CFG_NUM_DXA_CORES, 1); // TCU lmem tag and attr widths for DMA arb. - // Masters into the TCU LMEM port: BLOCK_SIZE abufs + 1 shared bbuf. - // (Sparse metadata does not fetch from LMEM — it preloads into the - // VX_tcu_sp_meta SRAM via TCU_LD ahead of the MMA dispatch.) + // Masters into the TCU LMEM port: BLOCK_SIZE abufs + 1 shared bbuf, and + // the tensor-job copy engine in TMEM builds. localparam TCU_LMEM_ATTR_W = 1; localparam TCU_LMEM_BLK_TAG_W = UUID_WIDTH + 1; - localparam TCU_LMEM_NUM_MASTERS = `VX_CFG_NUM_TCU_BLOCKS + 1; + localparam TCU_LMEM_NUM_MASTERS = `VX_CFG_NUM_TCU_BLOCKS + 1 + `VX_CFG_TCU_TMEM_ENABLED; localparam TCU_LMEM_TAG_W = TCU_LMEM_BLK_TAG_W + `ARB_SEL_BITS(TCU_LMEM_NUM_MASTERS, 1); // LMEM DMA port parameters. (The raster FWD needs no LMEM DMA agent — @@ -2292,11 +2319,18 @@ package VX_gpu_pkg; localparam UMMU_DXA_IDX = UMMU_RTCACHE_IDX + `VX_CFG_EXT_RTU_ENABLED; localparam UMMU_NUM_REQS = `VX_CFG_EXT_TEX_ENABLED + `VX_CFG_EXT_RTU_ENABLED + `VX_CFG_EXT_DXA_ENABLED; - // Widest tag among the socket arb inputs (DXA adapts to the given budget) + // Widest tag among the socket arb inputs. A DXA read carries its worker's + // in-flight slot under the select bits of the DXA's worker arbiter. +`ifdef VX_CFG_EXT_DXA_ENABLE + localparam DXA_MEM_TAG_WIDTH = UUID_WIDTH + `CLOG2(`VX_CFG_DXA_MAX_INFLIGHT) + `ARB_SEL_BITS(`VX_CFG_NUM_DXA_CORES, 1); + localparam SOCKET_MEM_TAG_W0 = `MAX(L1_MEM_TAG_WIDTH, DXA_MEM_TAG_WIDTH); +`else + localparam SOCKET_MEM_TAG_W0 = L1_MEM_TAG_WIDTH; +`endif `ifdef VX_CFG_EXT_TEX_ENABLE - localparam SOCKET_MEM_TAG_W1 = `MAX(L1_MEM_TAG_WIDTH, TCACHE_MEM_TAG_WIDTH); + localparam SOCKET_MEM_TAG_W1 = `MAX(SOCKET_MEM_TAG_W0, TCACHE_MEM_TAG_WIDTH); `else - localparam SOCKET_MEM_TAG_W1 = L1_MEM_TAG_WIDTH; + localparam SOCKET_MEM_TAG_W1 = SOCKET_MEM_TAG_W0; `endif `ifdef VX_CFG_EXT_RTU_ENABLE localparam SOCKET_MEM_TAG_WIDTH = `MAX(SOCKET_MEM_TAG_W1, RTCACHE_MEM_TAG_WIDTH); diff --git a/hw/rtl/VX_kmu.sv b/hw/rtl/VX_kmu.sv index cae8f136fe..b683a927de 100644 --- a/hw/rtl/VX_kmu.sv +++ b/hw/rtl/VX_kmu.sv @@ -46,6 +46,9 @@ module VX_kmu import VX_gpu_pkg::*; import VX_trace_pkg::*; #( reg [`VX_CFG_XLEN-1:0] dcr_param; reg [CTA_TID_WIDTH:0] dcr_block_size; reg [`VX_CFG_LMEM_LOG_SIZE:0] dcr_lmem_size; +`ifdef VX_CFG_TCU_TMEM_ENABLE + reg [31:0] dcr_tmem_cols; +`endif reg [2:0][CTA_TID_WIDTH-1:0] dcr_warp_step; // Cluster shape: CTAs in the same cluster are guaranteed // co-resident on the same core. Default (1,1,1) reproduces the @@ -79,6 +82,21 @@ module VX_kmu import VX_gpu_pkg::*; import VX_trace_pkg::*; #( reg [2:0][31:0] block_idx_r; reg is_first_r; +`ifdef VX_CFG_TCU_TMEM_ENABLE + // A CTA's TMEM budget, a power-of-two run of 32-column chunks, counts toward + // occupancy like its LMEM: m CTAs fit iff m budgets fit the core's TMEM. + function automatic logic [`VX_CFG_NUM_WARPS-1:0] tmem_slots_fit(input logic [31:0] cols); + logic [31:0] budget; + budget = 32; + for (integer i = 0; i < 6; ++i) begin + if (budget < cols) budget = budget << 1; + end + for (integer m = 1; m <= `VX_CFG_NUM_WARPS; ++m) begin + tmem_slots_fit[m-1] = (m == 1) || (cols == 0) || (budget * m <= `VX_CFG_TCU_TMEM_COLS); + end + endfunction +`endif + // Per-kernel launch constants, computed once here and broadcast to every // core's dispatcher (identical for all cores, stable for the whole kernel). // cluster_size : K = cluster_dim product, bounded by NUM_WARPS (cluster @@ -105,7 +123,11 @@ module VX_kmu import VX_gpu_pkg::*; import VX_trace_pkg::*; #( cluster_size_r <= (NW_WIDTH+1)'(dcr_cluster_dim[0] * dcr_cluster_dim[1] * dcr_cluster_dim[2]); aligned_lmem_size_r <= aligned_lmem_size_w; + `ifdef VX_CFG_TCU_TMEM_ENABLE + lmem_slots_r <= lmem_slots_fit(aligned_lmem_size_w) & tmem_slots_fit(dcr_tmem_cols); + `else lmem_slots_r <= lmem_slots_fit(aligned_lmem_size_w); + `endif end end @@ -117,6 +139,17 @@ module VX_kmu import VX_gpu_pkg::*; import VX_trace_pkg::*; #( // Defaults to (1,1,1): the cluster shape sizes the launch message, so // a launch that never programs it would otherwise stall the stream. dcr_cluster_dim <= {3{(NW_WIDTH+1)'(1)}}; + dcr_PC <= '0; + dcr_entry <= '0; + dcr_grid_dim <= '0; + dcr_block_dim <= '0; + dcr_param <= '0; + dcr_block_size <= '0; + dcr_lmem_size <= '0; + `ifdef VX_CFG_TCU_TMEM_ENABLE + dcr_tmem_cols <= '0; + `endif + dcr_warp_step <= '0; end else if (dcr_req_valid && dcr_req_rw) begin case(dcr_req_addr) // Program startup PC @@ -142,6 +175,10 @@ module VX_kmu import VX_gpu_pkg::*; import VX_trace_pkg::*; #( `VX_DCR_KMU_BLOCK_DIM_Z: dcr_block_dim[2] <= dcr_req_data[CTA_TID_WIDTH:0]; // Local memory size `VX_DCR_KMU_LMEM_SIZE: dcr_lmem_size <= dcr_req_data[`VX_CFG_LMEM_LOG_SIZE:0]; + `ifdef VX_CFG_TCU_TMEM_ENABLE + // TMEM columns a CTA may allocate + `VX_DCR_KMU_TMEM_COLS: dcr_tmem_cols <= dcr_req_data; + `endif // Block size (total threads per CTA) `VX_DCR_KMU_BLOCK_SIZE: dcr_block_size <= dcr_req_data[CTA_TID_WIDTH:0]; // Warp steps @@ -363,6 +400,9 @@ module VX_kmu import VX_gpu_pkg::*; import VX_trace_pkg::*; #( assign kmu_req.ctx_id = ctx_id_r; assign kmu_req.aligned_lmem_size = aligned_lmem_size_r; assign kmu_req.lmem_slots = lmem_slots_r; +`ifdef VX_CFG_TCU_TMEM_ENABLE + assign kmu_req.tmem = (dcr_tmem_cols != 0); +`endif assign kmu_req.args.compute = kmu_comp; // A compute message is one CLUSTER and carries no placement hint: the fan-out diff --git a/hw/rtl/core/VX_backend_slice.sv b/hw/rtl/core/VX_backend_slice.sv index 42c9630e8b..4fa045e06d 100644 --- a/hw/rtl/core/VX_backend_slice.sv +++ b/hw/rtl/core/VX_backend_slice.sv @@ -90,6 +90,9 @@ import VX_tcu_pkg::*; input wire [TCU_WG_RS2_WIDTH-1:0][`VX_CFG_XLEN-1:0] tcu_tbuf_rs2_data, input wire tcu_tbuf_ready, `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_job_if.block tcu_job_if, +`endif // core-wide warp control and CTA contexts VX_warp_shared_if.master warp_shared_if, @@ -172,6 +175,9 @@ import VX_tcu_pkg::*; .tcu_tbuf_rs1_data (tcu_tbuf_rs1_data), .tcu_tbuf_rs2_data (tcu_tbuf_rs2_data), .tcu_tbuf_ready (tcu_tbuf_ready), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .tcu_job_if (tcu_job_if), `endif .warp_shared_if (warp_shared_if), .warp_ctl_if (warp_ctl_if), diff --git a/hw/rtl/core/VX_compute_slice.sv b/hw/rtl/core/VX_compute_slice.sv index 4d8c0b6619..0511a0263c 100644 --- a/hw/rtl/core/VX_compute_slice.sv +++ b/hw/rtl/core/VX_compute_slice.sv @@ -93,6 +93,9 @@ import VX_tcu_pkg::*; input wire [TCU_WG_RS2_WIDTH-1:0][`VX_CFG_XLEN-1:0] tcu_tbuf_rs2_data, input wire tcu_tbuf_ready, `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_job_if.block tcu_job_if, +`endif // core-wide warp control VX_warp_shared_if.master warp_shared_if @@ -324,6 +327,9 @@ import VX_tcu_pkg::*; .tcu_tbuf_rs1_data (tcu_tbuf_rs1_data), .tcu_tbuf_rs2_data (tcu_tbuf_rs2_data), .tcu_tbuf_ready (tcu_tbuf_ready), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .tcu_job_if (tcu_job_if), `endif .warp_shared_if (warp_shared_if), .cta_bcast (cta_bcast) diff --git a/hw/rtl/core/VX_core.sv b/hw/rtl/core/VX_core.sv index fa0c9b3e79..7ea0b1c3cd 100644 --- a/hw/rtl/core/VX_core.sv +++ b/hw/rtl/core/VX_core.sv @@ -298,6 +298,15 @@ import VX_tcu_pkg::*; cta_bcast_t cta_bcast; +`ifdef VX_CFG_TCU_TMEM_ENABLE + wire cta_exit_valid; + wire [NCTA_WIDTH-1:0] cta_exit_id; +`endif + +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_bar_if tcu_bar_if(); +`endif + VX_scheduler #( .INSTANCE_ID (`SFORMATF(("%s-scheduler", INSTANCE_ID))) ) scheduler ( @@ -311,9 +320,16 @@ import VX_tcu_pkg::*; .warp_shared_if (warp_shared_if), `ifdef VX_CFG_EXT_DXA_ENABLE .txbar_bus_if (dxa_txbar_bus_if), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .tcu_bar_if (tcu_bar_if), `endif .committed_warps(committed_warps), .cta_bcast (cta_bcast), + `ifdef VX_CFG_TCU_TMEM_ENABLE + .cta_exit_valid (cta_exit_valid), + .cta_exit_id (cta_exit_id), + `endif .kmu_bus_if (kmu_bus_if), .gbar_bus_if (gbar_bus_if), .cycles (sched_cycles), @@ -356,6 +372,9 @@ import VX_tcu_pkg::*; wire [`VX_CFG_NUM_TCU_BLOCKS-1:0][TCU_WG_RS2_WIDTH-1:0][`VX_CFG_XLEN-1:0] tcu_tbuf_rs2_data; wire [`VX_CFG_NUM_TCU_BLOCKS-1:0] tcu_tbuf_ready; `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_job_if tcu_job_if [`VX_CFG_NUM_TCU_BLOCKS](); +`endif VX_sfu_shared #( .INSTANCE_ID (`SFORMATF(("%s-sfu-shared", INSTANCE_ID))) @@ -392,6 +411,12 @@ import VX_tcu_pkg::*; .tbuf_rs2_data (tcu_tbuf_rs2_data), .tbuf_ready_eff (tcu_tbuf_ready), .tcu_lmem_if (tcu_lmem_if), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .job_if (tcu_job_if), + .tcu_bar_if (tcu_bar_if), + .cta_exit_valid (cta_exit_valid), + .cta_exit_id (cta_exit_id), `endif .clk (clk), .reset (reset) @@ -492,6 +517,9 @@ import VX_tcu_pkg::*; .tcu_tbuf_rs1_data (tcu_tbuf_rs1_data[i]), .tcu_tbuf_rs2_data (tcu_tbuf_rs2_data[i]), .tcu_tbuf_ready (tcu_tbuf_ready[i]), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .tcu_job_if (tcu_job_if[i]), `endif .warp_shared_if (warp_shared_if[i]) ); @@ -711,6 +739,9 @@ import VX_tcu_pkg::*; .tcu_tbuf_rs1_data (tcu_tbuf_rs1_data[i]), .tcu_tbuf_rs2_data (tcu_tbuf_rs2_data[i]), .tcu_tbuf_ready (tcu_tbuf_ready[i]), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .tcu_job_if (tcu_job_if[i]), `endif .warp_shared_if (warp_shared_if[i]), .cta_bcast (cta_bcast) @@ -790,6 +821,9 @@ import VX_tcu_pkg::*; .tcu_tbuf_rs2_data (tcu_tbuf_rs2_data), .tcu_tbuf_ready (tcu_tbuf_ready), `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .tcu_job_if (tcu_job_if), + `endif `ifdef VX_CFG_EXT_DXA_ENABLE .dxa_req_bus_if (block_dxa_req_bus_if), `endif diff --git a/hw/rtl/core/VX_csr_mpm.sv b/hw/rtl/core/VX_csr_mpm.sv index 4acdd07c1c..3007825c61 100644 --- a/hw/rtl/core/VX_csr_mpm.sv +++ b/hw/rtl/core/VX_csr_mpm.sv @@ -187,6 +187,11 @@ module VX_csr_mpm import VX_gpu_pkg::*; #( `CSR_READ_64(`VX_CSR_MPM_TCU_TBUF_STALLS, dcr_data_w, pipeline_perf.tcu.tbuf_stalls); `CSR_READ_64(`VX_CSR_MPM_TCU_TBUF_CACHE_HITS, dcr_data_w, pipeline_perf.tcu.tbuf_cache_hits); `CSR_READ_64(`VX_CSR_MPM_TCU_LMEM_READS, dcr_data_w, pipeline_perf.tcu.lmem_reads); + `CSR_READ_64(`VX_CSR_MPM_TCU_MMA_BUSY, dcr_data_w, pipeline_perf.tcu.mma_busy); + `CSR_READ_64(`VX_CSR_MPM_TCU_OPND_WAITS, dcr_data_w, pipeline_perf.tcu.opnd_waits); + `CSR_READ_64(`VX_CSR_MPM_TCU_JOB_OTHER, dcr_data_w, pipeline_perf.tcu.job_other); + `CSR_READ_64(`VX_CSR_MPM_TCU_IDLE, dcr_data_w, pipeline_perf.tcu.idle); + `CSR_READ_64(`VX_CSR_MPM_TCU_TMEM_XFERS, dcr_data_w, pipeline_perf.tcu.tmem_xfers); default:; endcase end diff --git a/hw/rtl/core/VX_cta_dispatch.sv b/hw/rtl/core/VX_cta_dispatch.sv index 98cd9ccc7b..1e88af5959 100644 --- a/hw/rtl/core/VX_cta_dispatch.sv +++ b/hw/rtl/core/VX_cta_dispatch.sv @@ -44,6 +44,12 @@ module VX_cta_dispatch import VX_gpu_pkg::*; #( output cta_bcast_t cta_bcast, output cta_lane_bcast_t [NUM_LANES-1:0] cta_lane_bcast, +`ifdef VX_CFG_TCU_TMEM_ENABLE + // a CTA's last warp retired (its TMEM columns are freed) + output wire cta_exit_valid, + output wire [NCTA_WIDTH-1:0] cta_exit_id, +`endif + output wire busy ); `UNUSED_SPARAM (INSTANCE_ID) @@ -297,12 +303,29 @@ module VX_cta_dispatch import VX_gpu_pkg::*; #( wire [NUM_LANES-1:0] lane_sel; wire [NUM_LANES-1:0][LANE_WIDTH-1:0] lane_order; wire [LCNT_WIDTH-1:0] lane_cnt; +`ifdef VX_CFG_TCU_TMEM_ENABLE + // A TMEM CTA's warp of rank r runs on TCU block r % ISSUE_WIDTH, the block + // of launch lane r % NUM_LANES: its warps launch as a run of consecutive + // lanes from the rotation start, which tracks its rank. + `STATIC_ASSERT (NUM_LANES == `VX_CFG_ISSUE_WIDTH, ("TMEM needs one launch lane per TCU block")) + reg tmem_cta_r; + wire [NUM_LANES-1:0] lane_go; + for (genvar l = 0; l < NUM_LANES; ++l) begin : g_lane_go + wire [NUM_LANES-1:0] ahead; + for (genvar m = 0; m < NUM_LANES; ++m) begin : g_ahead + assign ahead[m] = (LANE_WIDTH'(m) - lane_rr_r) < (LANE_WIDTH'(l) - lane_rr_r); + end + assign lane_go[l] = lane_ready[l] && (~tmem_cta_r || (&(lane_ready | ~ahead))); + end +`else + wire [NUM_LANES-1:0] lane_go = lane_ready; +`endif for (genvar l = 0; l < NUM_LANES; ++l) begin : g_lane_sel wire [NUM_LANES-1:0] ahead; for (genvar m = 0; m < NUM_LANES; ++m) begin : g_ahead assign ahead[m] = (LANE_WIDTH'(m) - lane_rr_r) < (LANE_WIDTH'(l) - lane_rr_r); end - wire [NUM_LANES-1:0] ready_ahead = lane_ready & ahead; + wire [NUM_LANES-1:0] ready_ahead = lane_go & ahead; wire [LCNT_WIDTH-1:0] order; VX_popcount #( .N (NUM_LANES) @@ -311,7 +334,7 @@ module VX_cta_dispatch import VX_gpu_pkg::*; #( .data_out (order) ); assign lane_order[l] = LANE_WIDTH'(order); - assign lane_sel[l] = launch_en && lane_ready[l] && 1'(rem_gt >> order); + assign lane_sel[l] = launch_en && lane_go[l] && 1'(rem_gt >> order); end VX_popcount #( .N (NUM_LANES) @@ -450,6 +473,10 @@ module VX_cta_dispatch import VX_gpu_pkg::*; #( wire cta_done = warp_done_r_dly && slot_valid_r[done_slot_r_dly] && (rem_warps_rdata_fwd == (NW_WIDTH+1)'(1)); +`ifdef VX_CFG_TCU_TMEM_ENABLE + assign cta_exit_valid = cta_done; + assign cta_exit_id = NCTA_WIDTH'(done_slot_r_dly); +`endif // ------------------------------------------------------------------------- // Admission control — fixed-stride LMEM slots @@ -494,8 +521,14 @@ module VX_cta_dispatch import VX_gpu_pkg::*; #( // reset the valid bit alone, so an idle beat carries arbitrary bits. `RUNTIME_ASSERT(~kmu_bus_if.valid || (stride == 0) || (PROD_W'(stride) <= PROD_W'(LMEM_SIZE)), ("%t: %s CTA shared-memory footprint %0d exceeds the %0d-byte capacity; the CTA overruns its slot", $time, INSTANCE_ID, stride, LMEM_SIZE)) +`ifdef VX_CFG_TCU_TMEM_ENABLE + // The TMEM budget can only narrow the slots the LMEM footprint fits. + `RUNTIME_ASSERT(~kmu_bus_if.valid || ((usable_therm & ~lmem_slots_fit(stride)) == '0), + ("%t: %s slot map %b does not match the %0d-byte CTA footprint", $time, INSTANCE_ID, usable_therm, stride)) +`else `RUNTIME_ASSERT(~kmu_bus_if.valid || (usable_therm == lmem_slots_fit(stride)), ("%t: %s slot map %b does not match the %0d-byte CTA footprint", $time, INSTANCE_ID, usable_therm, stride)) +`endif // A cluster member's slot base is either the round-robin tail or slot 0: the // tail is normalized to 0 when a kernel transition shrank the usable range @@ -621,6 +654,9 @@ module VX_cta_dispatch import VX_gpu_pkg::*; #( warp_order_r <= '0; nfired_r <= '0; lane_rr_r <= '0; + `ifdef VX_CFG_TCU_TMEM_ENABLE + tmem_cta_r <= 1'b0; + `endif init_cnt_r <= '0; shape_step_r <= '0; shape_dim_r <= '0; @@ -705,6 +741,12 @@ module VX_cta_dispatch import VX_gpu_pkg::*; #( warp_step_r <= kmu_req.args.compute.warp_step; cluster_size_r <= eff_cluster_size; cta_rank_r <= '0; + `ifdef VX_CFG_TCU_TMEM_ENABLE + tmem_cta_r <= kmu_req.tmem; + if (kmu_req.tmem) begin + lane_rr_r <= '0; // rank 0 on lane 0 + end + `endif group_step_r <= (NUM_LANES == 1) ? kmu_req.args.compute.warp_step : group_step_r; // A new block shape rebuilds the window constants before launching. if (shape_new) begin diff --git a/hw/rtl/core/VX_decode.sv b/hw/rtl/core/VX_decode.sv index 35698a128a..7c367470ed 100644 --- a/hw/rtl/core/VX_decode.sv +++ b/hw/rtl/core/VX_decode.sv @@ -798,6 +798,7 @@ module VX_decode import op_type = INST_OP_BITS'(funct3); end `ifdef VX_CFG_EXT_TCU_ENABLE + `ifdef VX_CFG_TCU_WMMA_ENABLE 7'h02: begin ex_type = EX_TCU; `ifdef TCU_META_ENABLE @@ -831,7 +832,7 @@ module VX_decode import // Sparse variants live in a separate op_type so // tcu_args_t doesn't carry a per-uop is_sparse bit. if (rs2[0]) begin - `ifdef VX_CFG_TCU_WGMMA_ENABLE + `ifdef TCU_WARP_WGMMA op_type = funct3[0] ? INST_OP_BITS'(INST_TCU_WGMMA_SP) : INST_OP_BITS'(INST_TCU_WMMA_SP); `else @@ -843,7 +844,7 @@ module VX_decode import end else `endif begin - `ifdef VX_CFG_TCU_WGMMA_ENABLE + `ifdef TCU_WARP_WGMMA op_type = funct3[0] ? INST_OP_BITS'(INST_TCU_WGMMA) : INST_OP_BITS'(INST_TCU_WMMA); `else @@ -872,6 +873,65 @@ module VX_decode import end end `endif + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + 7'h05: begin // TMEM transfers and tensor jobs + ex_type = EX_TCU; + op_args.tcu = '0; + case (funct3) + 3'h0, 3'h4: begin // TMEM_LD fd, (rs1), n: rs2 field = n-1 + op_type = INST_OP_BITS'(INST_TCU_TMEM_LD); + op_args.tcu.fmt_s = rs2; + op_args.tcu.a_from_smem = funct3[2]; + `USED_FREG (rd); + `USED_IREG (rs1); + end + 3'h1, 3'h5: begin // TMEM_ST fs, (rs1), n: rd field = first source + op_type = INST_OP_BITS'(INST_TCU_TMEM_ST); + op_args.tcu.fmt_s = rs2; + op_args.tcu.a_from_smem = funct3[2]; + `USED_IREG (rs1); + reg_ids[RV_RS2] = make_reg_num(REG_TYPE_F, RV_REGS_BITS'(rd)); + use_regs[RV_RS2] = 1'b1; + end + 3'h6: begin // TMEM_ALLOC rd, rs1: rs1 columns + op_type = INST_OP_BITS'(INST_TCU_TMEM_ALLOC); + `USED_IREG (rd); + `USED_IREG (rs1); + end + 3'h7: begin // TMEM_DEALLOC rs1, rs2: rs2 columns from column rs1 + op_type = INST_OP_BITS'(INST_TCU_TMEM_DEALLOC); + `USED_IREG (rs1); + `USED_IREG (rs2); + end + default:; + endcase + end + 7'h06: begin // tcgen05-style async tensor ops + ex_type = EX_TCU; + op_args.tcu = '0; + case (funct3) + 3'h1: begin // TC_COMMIT rs1, rs2: barrier id, arrival count + op_type = INST_OP_BITS'(INST_TCU_TC_COMMIT); + `USED_IREG (rs1); + `USED_IREG (rs2); + end + 3'h2: begin // TC_CP rs1, rs2: {columns, taddr}, source + op_type = INST_OP_BITS'(INST_TCU_TC_CP); + `USED_IREG (rs1); + `USED_IREG (rs2); + end + 3'h4: begin // TC_MMA rs1, rs2, rs3 (rd field): instruction descriptor, A, B + op_type = INST_OP_BITS'(INST_TCU_TC_MMA); + `USED_IREG (rs1); + `USED_IREG (rs2); + reg_ids[RV_RS3] = make_reg_num(REG_TYPE_I, RV_REGS_BITS'(rd)); + use_regs[RV_RS3] = 1'b1; + end + default:; + endcase + end + `endif `ifdef VX_CFG_EXT_DXA_ENABLE 7'h03: begin // DXA issue // Multicast is determined by cta_mask (>1 bit set). @@ -1052,9 +1112,22 @@ module VX_decode import endcase end +`ifdef VX_CFG_TCU_TMEM_ENABLE + // A tensor-memory build has no warp WGMMA: the TCU's MMAs are tc.mma. + `RUNTIME_ASSERT(~(fetch_if.valid && (opcode == INST_EXT1) && (funct7 == 7'h02) && (funct3 == 3'h1)), + ("%t: %s WGMMA in a tensor-memory build, wid=%0d, PC=0x%0h (#%0d)", $time, INSTANCE_ID, fetch_if.data.wid, to_fullPC(fetch_if.data.PC), fetch_if.data.uuid)) +`endif + // Without its extension a TCU, DXA, wide or matrix load/store instruction // decodes to no unit, and its undefined ex/op fields would dispatch an // arbitrary operation. +`ifdef VX_CFG_EXT_TCU_ENABLE +`ifndef VX_CFG_TCU_WMMA_ENABLE + `RUNTIME_ASSERT(~(fetch_if.valid && (opcode == INST_EXT1) && (funct7 == 7'h02)), + ("%t: %s per-warp MMA or TCU_LD on a core built without VX_CFG_TCU_WMMA_ENABLE, wid=%0d, PC=0x%0h (#%0d)", + $time, INSTANCE_ID, fetch_if.data.wid, to_fullPC(fetch_if.data.PC), fetch_if.data.uuid)) +`endif +`endif `ifndef VX_CFG_EXT_TCU_ENABLE `RUNTIME_ASSERT(~(fetch_if.valid && (opcode == INST_EXT1) && (funct7 == 7'h02)), ("%t: %s TCU instruction on a core built without VX_CFG_EXT_TCU_ENABLE, wid=%0d, PC=0x%0h (#%0d)", diff --git a/hw/rtl/core/VX_execute.sv b/hw/rtl/core/VX_execute.sv index 7a7b394cdd..439ccbae44 100644 --- a/hw/rtl/core/VX_execute.sv +++ b/hw/rtl/core/VX_execute.sv @@ -77,6 +77,9 @@ import VX_tcu_pkg::*; input wire [`VX_CFG_NUM_TCU_BLOCKS-1:0][TCU_WG_RS2_WIDTH-1:0][`VX_CFG_XLEN-1:0] tcu_tbuf_rs2_data, input wire [`VX_CFG_NUM_TCU_BLOCKS-1:0] tcu_tbuf_ready, `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_job_if.block tcu_job_if [`VX_CFG_NUM_TCU_BLOCKS], +`endif // scheduler interfaces VX_sched_csr_if.slave sched_csr_if [`VX_CFG_NUM_SFU_BLOCKS], @@ -164,6 +167,9 @@ import VX_tcu_pkg::*; .tbuf_rs2_data (tcu_tbuf_rs2_data), .tbuf_ready (tcu_tbuf_ready), `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .job_if (tcu_job_if), + `endif `ifdef TCU_META_ENABLE .tcu_mem_if (lsu_tcu_mem_if), `endif diff --git a/hw/rtl/core/VX_execute_slice.sv b/hw/rtl/core/VX_execute_slice.sv index 4c541de173..a3e5283f3a 100644 --- a/hw/rtl/core/VX_execute_slice.sv +++ b/hw/rtl/core/VX_execute_slice.sv @@ -80,6 +80,9 @@ import VX_tcu_pkg::*; input wire [TCU_WG_RS2_WIDTH-1:0][`VX_CFG_XLEN-1:0] tcu_tbuf_rs2_data, input wire tcu_tbuf_ready, `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_job_if.block tcu_job_if, +`endif // SFU warp control and CSRs VX_warp_shared_if.master warp_shared_if, @@ -387,6 +390,9 @@ import VX_tcu_pkg::*; .tbuf_rs2_data (tcu_tbuf_rs2_data), .tbuf_ready (tcu_tbuf_ready), `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .job_if (tcu_job_if), + `endif `ifdef TCU_META_ENABLE .tcu_mem_if (lsu_tcu_mem_if), `endif diff --git a/hw/rtl/core/VX_scheduler.sv b/hw/rtl/core/VX_scheduler.sv index c16017a9d9..4564f2dee0 100644 --- a/hw/rtl/core/VX_scheduler.sv +++ b/hw/rtl/core/VX_scheduler.sv @@ -32,11 +32,19 @@ module VX_scheduler import VX_gpu_pkg::*; #( VX_warp_shared_if.slave warp_shared_if [`VX_CFG_NUM_SFU_BLOCKS], `ifdef VX_CFG_EXT_DXA_ENABLE VX_txbar_bus_if.slave txbar_bus_if, +`endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_bar_if.slave tcu_bar_if, `endif input wire [`VX_CFG_NUM_WARPS-1:0] committed_warps, // CTA context writes, to every SFU block's copy output cta_bcast_t cta_bcast, +`ifdef VX_CFG_TCU_TMEM_ENABLE + // a CTA's last warp retired (its TMEM columns are freed) + output wire cta_exit_valid, + output wire [NCTA_WIDTH-1:0] cta_exit_id, +`endif VX_kmu_bus_if.slave kmu_bus_if, @@ -103,12 +111,17 @@ module VX_scheduler import VX_gpu_pkg::*; #( .cta_init (cta_init), .cta_bcast (cta_bcast), .cta_lane_bcast(cta_lane_bcast), + `ifdef VX_CFG_TCU_TMEM_ENABLE + .cta_exit_valid (cta_exit_valid), + .cta_exit_id (cta_exit_id), + `endif .busy (cta_dispatcher_busy) ); // core-wide warp-control resources wire bar_unlock_valid; wire [`VX_CFG_NUM_WARPS-1:0] bar_unlock_mask; + wire bar_active; wire wspawn_apply; wire [`VX_CFG_NUM_WARPS-1:0] wspawn_wmask; wire [PC_BITS-1:0] wspawn_pc; @@ -125,8 +138,12 @@ module VX_scheduler import VX_gpu_pkg::*; #( .warp_shared_if (warp_shared_if), `ifdef VX_CFG_EXT_DXA_ENABLE .txbar_bus_if (txbar_bus_if), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .tcu_bar_if (tcu_bar_if), `endif .active_warps (active_warps), + .bar_active (bar_active), .bar_unlock_valid(bar_unlock_valid), .bar_unlock_mask (bar_unlock_mask), .gbar_bus_if (gbar_bus_if), @@ -271,9 +288,10 @@ module VX_scheduler import VX_gpu_pkg::*; #( if (| cta_fire) begin timeout_enable <= 1; end - if (timeout_enable && active_warps !=0 && active_warps == stalled_warps) begin + // Barrier traffic from async units (DXA, tc.commit) is progress while every warp waits. + if (timeout_enable && active_warps !=0 && active_warps == stalled_warps && !bar_active) begin timeout_ctr <= timeout_ctr + 1; - end else if (active_warps == 0 || active_warps != stalled_warps) begin + end else if (active_warps == 0 || active_warps != stalled_warps || bar_active) begin timeout_ctr <= '0; end end diff --git a/hw/rtl/core/VX_uop_sequencer.sv b/hw/rtl/core/VX_uop_sequencer.sv index 2b888a8cce..f6b8bb1a38 100644 --- a/hw/rtl/core/VX_uop_sequencer.sv +++ b/hw/rtl/core/VX_uop_sequencer.sv @@ -130,14 +130,18 @@ module VX_uop_sequencer import // ------------------------------------------------------------------ assign uop_in_valid[UOP_TCU] = (uop_in_data.ex_type == EX_TCU) && (uop_in_data.op_type == INST_TCU_WMMA - `ifdef VX_CFG_TCU_WGMMA_ENABLE + `ifdef TCU_WARP_WGMMA || uop_in_data.op_type == INST_TCU_WGMMA `endif `ifdef VX_CFG_TCU_SPARSE_ENABLE || uop_in_data.op_type == INST_TCU_WMMA_SP - `ifdef VX_CFG_TCU_WGMMA_ENABLE + `ifdef TCU_WARP_WGMMA || uop_in_data.op_type == INST_TCU_WGMMA_SP `endif + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + || uop_in_data.op_type == INST_TCU_TMEM_LD + || uop_in_data.op_type == INST_TCU_TMEM_ST `endif ); VX_tcu_uops tcu_uops ( diff --git a/hw/rtl/core/VX_warp_shared_unit.sv b/hw/rtl/core/VX_warp_shared_unit.sv index de5ed3db5f..06328618f0 100644 --- a/hw/rtl/core/VX_warp_shared_unit.sv +++ b/hw/rtl/core/VX_warp_shared_unit.sv @@ -35,8 +35,14 @@ module VX_warp_shared_unit import VX_gpu_pkg::*; #( VX_warp_shared_if.slave warp_shared_if [NUM_REQS], `ifdef VX_CFG_EXT_DXA_ENABLE VX_txbar_bus_if.slave txbar_bus_if, +`endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + // tc.commit arrivals + VX_tcu_bar_if.slave tcu_bar_if, `endif input wire [`VX_CFG_NUM_WARPS-1:0] active_warps, + // a barrier request applies this cycle + output wire bar_active, // barrier release output wire bar_unlock_valid, @@ -121,11 +127,13 @@ module VX_warp_shared_unit import VX_gpu_pkg::*; #( wire txbar_req_valid; barrier_t txbar_req; - wire [BAR_ADDR_W-1:0] bar_read_addr; + wire txbar_valid; + wire [BAR_ADDR_W-1:0] txbar_addr; `ifdef VX_CFG_EXT_DXA_ENABLE + assign txbar_valid = txbar_bus_if.valid; + assign txbar_addr = txbar_bus_if.data.addr; assign txbar_bus_if.ready = ~is_bar; wire txbar_fire = txbar_bus_if.valid && txbar_bus_if.ready; - assign bar_read_addr = is_bar ? req.bar_addr : txbar_bus_if.data.addr; // a completion releases one pending transaction event barrier_t txbar_req_w; assign txbar_req_w.id = '0; @@ -146,11 +154,63 @@ module VX_warp_shared_unit import VX_gpu_pkg::*; #( .data_out ({txbar_req_valid, txbar_req}) ); `else - assign bar_read_addr = req.bar_addr; + assign txbar_valid = 1'b0; + assign txbar_addr = '0; assign txbar_req_valid = 1'b0; assign txbar_req = '0; `endif + // a tc.commit arrival takes the barrier unit when neither a request nor a + // transaction completion does + wire tcu_req_valid; + barrier_t tcu_req; + wire tcu_valid; + wire [BAR_ADDR_W-1:0] tcu_addr; +`ifdef VX_CFG_TCU_TMEM_ENABLE + assign tcu_valid = tcu_bar_if.req_valid; + assign tcu_addr = tcu_bar_if.req_data.addr; + assign tcu_bar_if.req_ready = ~is_bar && ~txbar_valid; + wire tcu_fire = tcu_bar_if.req_valid && tcu_bar_if.req_ready; + barrier_t tcu_req_w; + assign tcu_req_w.id = '0; + assign tcu_req_w.is_event = 1'b0; + assign tcu_req_w.is_sync = 1'b0; + assign tcu_req_w.is_global = 1'b0; + assign tcu_req_w.is_arrive = 1'b1; + assign tcu_req_w.phase = 1'b0; + assign tcu_req_w.size_m1 = tcu_bar_if.req_data.size_m1; + VX_pipe_register #( + .DATAW (1 + $bits(barrier_t)), + .RESETW (1) + ) tcu_bar_reg ( + .clk (clk), + .reset (reset), + .enable (1'b1), + .data_in ({tcu_fire, tcu_req_w}), + .data_out ({tcu_req_valid, tcu_req}) + ); +`else + assign tcu_valid = 1'b0; + assign tcu_addr = '0; + assign tcu_req_valid = 1'b0; + assign tcu_req = '0; +`endif + `UNUSED_VAR (tcu_valid) + + wire [BAR_ADDR_W-1:0] bar_read_addr; +`ifdef VX_CFG_TCU_TMEM_ENABLE + assign bar_read_addr = is_bar ? req.bar_addr : (txbar_valid ? txbar_addr : tcu_addr); +`elsif VX_CFG_EXT_DXA_ENABLE + assign bar_read_addr = is_bar ? req.bar_addr : txbar_addr; + `UNUSED_VAR (txbar_valid) + `UNUSED_VAR (tcu_addr) +`else + assign bar_read_addr = req.bar_addr; + `UNUSED_VAR (txbar_valid) + `UNUSED_VAR (txbar_addr) + `UNUSED_VAR (tcu_addr) +`endif + // the barrier request applies the cycle after its phase is read, as the // read must see the barrier before this arrival reg bar_valid_r; @@ -168,15 +228,17 @@ module VX_warp_shared_unit import VX_gpu_pkg::*; #( wire bar_read_phase; + assign bar_active = bar_valid_r || txbar_req_valid || tcu_req_valid; + VX_bar_unit #( .INSTANCE_ID (`SFORMATF(("%s-barrier", INSTANCE_ID))) ) bar_unit ( .clk (clk), .reset (reset), .core_id (core_id), - .req_valid (bar_valid_r || txbar_req_valid), + .req_valid (bar_valid_r || txbar_req_valid || tcu_req_valid), .req_wid (bar_wid_r), - .req_data (bar_valid_r ? bar_r : txbar_req), + .req_data (bar_valid_r ? bar_r : (txbar_req_valid ? txbar_req : tcu_req)), .read_addr (bar_read_addr), .read_phase (bar_read_phase), .active_warps (active_warps), diff --git a/hw/rtl/dxa/VX_dxa_addr_gen.sv b/hw/rtl/dxa/VX_dxa_addr_gen.sv index f7067aee95..6d9661cca3 100644 --- a/hw/rtl/dxa/VX_dxa_addr_gen.sv +++ b/hw/rtl/dxa/VX_dxa_addr_gen.sv @@ -52,20 +52,9 @@ module VX_dxa_addr_gen import VX_gpu_pkg::*, VX_dxa_pkg::*; #( output wire out_oob, output wire out_last, - // Pass-through params for downstream (stable during transfer). - output wire [31:0] out_cfill, - output wire out_dest_kmajor, - output wire [15:0] out_per_lane_stride_bytes, - output wire [3:0] out_elem_bytes, - // Tiled (Flat/BlockMajor) scatter: stable geometry + per-CL (k_row, n_base). - output wire [1:0] out_dest_mode, - output wire [3:0] out_lg_ratio, - output wire [3:0] out_lg_tcN, - output wire [3:0] out_lg_nsteps, - output wire [3:0] out_lg_bkK, + // Tiled (Flat/BlockMajor) scatter: per-CL (k_row, n_base). output wire [15:0] out_k_row, // dim1 index (K-row) of this CL - output wire [15:0] out_n_base, // N index of this CL's element 0 - output wire [DXA_SMEM_ADDR_W-1:0] out_smem_base // tile SMEM byte base (for tiled dest) + output wire [15:0] out_n_base // N index of this CL's element 0 ); localparam VLEN_W = CL_OFF_BITS + 1; @@ -96,9 +85,8 @@ module VX_dxa_addr_gen import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // K-major scatter-mode state. // km_row_base_r: SMEM base for the current outer-dim row (= initial + // dim_count[0] * elem_bytes). Updates only at row wrap. - // km_dest_kmajor_r / km_per_lane_stride / km_elem_bytes: stable params. + // km_dest_kmajor_r / km_elem_bytes: stable params. reg km_dest_kmajor_r; - reg [15:0] km_per_lane_stride_r; reg [3:0] km_elem_bytes_r; // per_lane_stride / elem_bytes, held stable per transfer. elem_bytes is a // power of 2 (per_lane_stride = tile1 * elem_bytes), so the divide is an @@ -109,29 +97,12 @@ module VX_dxa_addr_gen import VX_gpu_pkg::*, VX_dxa_pkg::*; #( : (setup_params.elem_bytes == 4'd2) ? 2'd1 : 2'd0; reg [DXA_SMEM_ADDR_W-1:0] km_row_base_r; - // Tiled (Flat/BlockMajor) scatter: stable geometry + per-CL token state. - reg [1:0] tiled_mode_r; - reg [3:0] tiled_lg_ratio_r, tiled_lg_tcN_r, tiled_lg_nsteps_r; - reg [3:0] tiled_lg_bkK_r; + // Tiled (Flat/BlockMajor) scatter: per-CL token state. reg [3:0] km_esize_r; // log2(elem_bytes) reg [15:0] n_base_r; // N index of current CL's element 0 - reg [DXA_SMEM_ADDR_W-1:0] tiled_base_r; // tile SMEM byte base (stable) - // Pass-through latched params. - reg [31:0] cfill_r; - - assign out_cfill = cfill_r; - assign out_dest_kmajor = km_dest_kmajor_r; - assign out_per_lane_stride_bytes = km_per_lane_stride_r; - assign out_elem_bytes = km_elem_bytes_r; - assign out_dest_mode = tiled_mode_r; - assign out_lg_ratio = tiled_lg_ratio_r; - assign out_lg_tcN = tiled_lg_tcN_r; - assign out_lg_nsteps = tiled_lg_nsteps_r; - assign out_lg_bkK = tiled_lg_bkK_r; assign out_k_row = dim_count_r[0][15:0]; assign out_n_base = n_base_r; - assign out_smem_base = tiled_base_r; wire [CL_OFF_BITS-1:0] first_off = gmem_cursor_r[CL_OFF_BITS-1:0]; @@ -224,23 +195,12 @@ module VX_dxa_addr_gen import VX_gpu_pkg::*, VX_dxa_pkg::*; #( is_first_r <= 1'b0; last_vend_r <= '0; smem_byte_addr_r <= '0; - // Reset K-major params so out_dest_kmajor (a mux selector - // downstream in smem_wr) doesn't carry X before the first - // pipeline_start. Without this, fb_word_data / fb_word_byteen - // muxes propagate X into the bus even though transfer_active=0. km_dest_kmajor_r <= 1'b0; - km_per_lane_stride_r <= '0; km_elem_bytes_r <= '0; km_tile1_r <= '0; km_row_base_r <= '0; - tiled_mode_r <= DXA_DEST_ROWMAJOR; - tiled_lg_ratio_r <= '0; - tiled_lg_tcN_r <= '0; - tiled_lg_nsteps_r<= '0; - tiled_lg_bkK_r <= '0; km_esize_r <= '0; n_base_r <= '0; - tiled_base_r <= '0; for (int d = 0; d < DXA_MAX_OUTER_DIMS; d++) begin dim_count_r[d] <= '0; end @@ -253,22 +213,14 @@ module VX_dxa_addr_gen import VX_gpu_pkg::*, VX_dxa_pkg::*; #( lines_left_r <= calc_num_lines(start_span); is_first_r <= 1'b1; last_vend_r <= calc_last_vend(start_span[CL_OFF_BITS-1:0]); - cfill_r <= setup_params.cfill; smem_byte_addr_r <= setup_params.initial_smem_base; km_dest_kmajor_r <= setup_params.dest_kmajor; - km_per_lane_stride_r <= setup_params.per_lane_stride_bytes; km_elem_bytes_r <= setup_params.elem_bytes; km_tile1_r <= (setup_params.elem_bytes == 4'd0) ? 32'd0 : (32'(setup_params.per_lane_stride_bytes) >> start_km_esize); km_row_base_r <= setup_params.initial_smem_base; - tiled_mode_r <= setup_params.dest_mode; - tiled_lg_ratio_r <= setup_params.lg_ratio; - tiled_lg_tcN_r <= setup_params.lg_tcN; - tiled_lg_nsteps_r<= setup_params.lg_nsteps; - tiled_lg_bkK_r <= setup_params.lg_bkK; km_esize_r <= 4'(start_km_esize); n_base_r <= '0; - tiled_base_r <= setup_params.initial_smem_base; for (int d = 0; d < DXA_MAX_OUTER_DIMS; d++) begin dim_count_r[d] <= '0; dim_penult_r[d] <= setup_params.dim_tiles[d] - 32'd2; @@ -348,6 +300,13 @@ module VX_dxa_addr_gen import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // km_step is LMEM-bounded; only the low DXA_SMEM_ADDR_W bits feed smem_byte_addr_r. `UNUSED_VAR (km_step[31:DXA_SMEM_ADDR_W]) + // destination geometry the SMEM writer takes from the transfer table + `UNUSED_VAR (setup_params.cfill) + `UNUSED_VAR (setup_params.dest_mode) + `UNUSED_VAR (setup_params.lg_ratio) + `UNUSED_VAR (setup_params.lg_tcN) + `UNUSED_VAR (setup_params.lg_nsteps) + `UNUSED_VAR (setup_params.lg_bkK) // the outermost dim only steps (all-last ends the transfer), never wraps to 0 `UNUSED_VAR (dim_single_r[DXA_MAX_OUTER_DIMS-1]) diff --git a/hw/rtl/dxa/VX_dxa_gmem_req.sv b/hw/rtl/dxa/VX_dxa_gmem_req.sv index 43e467ab46..6eb454289a 100644 --- a/hw/rtl/dxa/VX_dxa_gmem_req.sv +++ b/hw/rtl/dxa/VX_dxa_gmem_req.sv @@ -15,35 +15,38 @@ // // Manages a slot-table-indexed pool of MAX_OUTSTANDING in-flight tags. On // each accept, allocates a free slot and writes per-tag metadata. GMEM -// responses (out-of-order from the L1) are streamed directly to smem_wr -// via the `sw_*` channel — no rsp_buf BRAM. OOB entries skip the bus and -// are presented to smem_wr via an oob_pending[] bitvector. +// responses (out-of-order from the L1) pass through a one-entry stage, +// where their slot is read from the slot RAM, to smem_wr on the `sw_*` +// channel — no rsp_buf. OOB entries skip the bus and are presented to +// smem_wr through a FIFO of their tags. // -// Tag reuse is per-slot via a busy[] bitvector and outstanding counter; -// release order is independent of issue order (OOO drain in smem_wr). +// Released tags are reused in release order through a free-tag FIFO; +// release order is independent of issue order (OOO drain in smem_wr). Each +// slot records its transfer, so the reads of consecutive transfers share +// the pool. `include "VX_define.vh" module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( parameter MAX_OUTSTANDING = 8, + parameter NUM_XFERS = 2, parameter GMEM_ADDR_WIDTH = `VX_CFG_MEM_ADDR_WIDTH - `CLOG2(`VX_CFG_L1_LINE_SIZE), parameter GMEM_TAG_WIDTH = SOCKET_MEM_TAG_WIDTH, parameter CL_OFF_BITS = `CLOG2(`VX_CFG_L1_LINE_SIZE), parameter SMEM_ADDR_W = DXA_SMEM_ADDR_W, localparam TAG_W = `CLOG2(MAX_OUTSTANDING), - localparam SEQ_W = `CLOG2(MAX_OUTSTANDING + 1), + localparam XFER_W = `LOG2UP(NUM_XFERS), localparam GMEM_BYTES = 2**CL_OFF_BITS, localparam GMEM_DATAW = GMEM_BYTES * 8 ) ( input wire clk, input wire reset, - input wire transfer_active, - input wire transfer_start, // UUID for GMEM request tagging. input wire [UUID_WIDTH-1:0] active_uuid, - // From addr_gen (valid/ready). + // From addr_gen (valid/ready), for transfer ag_xfer. + input wire [XFER_W-1:0] ag_xfer, input wire ag_valid, output wire ag_ready, input wire [GMEM_ADDR_WIDTH-1:0] ag_cl_addr, @@ -51,7 +54,6 @@ module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( input wire [CL_OFF_BITS-1:0] ag_byte_offset, input wire [CL_OFF_BITS:0] ag_valid_length, input wire ag_oob, - input wire ag_last, input wire [15:0] ag_k_row, // tiled scatter: K-row of this CL input wire [15:0] ag_n_base, // tiled scatter: N index of CL element 0 @@ -62,15 +64,14 @@ module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( output wire sw_valid, input wire sw_ready, output wire [TAG_W-1:0] sw_tag, + output wire [XFER_W-1:0] sw_xfer, output wire [GMEM_DATAW-1:0] sw_data, output wire [SMEM_ADDR_W-1:0] sw_smem_byte_addr, output wire [CL_OFF_BITS-1:0] sw_byte_offset, output wire [CL_OFF_BITS:0] sw_valid_length, output wire sw_oob, - output wire sw_last, output wire [15:0] sw_k_row, output wire [15:0] sw_n_base, - output wire [SEQ_W-1:0] sw_outstanding, // # slots busy (incl. presented-to-smem_wr). // Resource release (from smem_wr) — per-tag, OOO. input wire release_en, @@ -79,12 +80,6 @@ module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // Progress events. output wire gmem_req_fire, output wire stall_no_slot - -`ifdef PERF_ENABLE - , - output wire [31:0] perf_gmem_reqs, - output wire [31:0] perf_gmem_span_cycles -`endif ); localparam GMEM_TAG_VALUEW = GMEM_TAG_WIDTH - UUID_WIDTH; @@ -102,51 +97,80 @@ module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // Slot table: per-tag metadata. // ════════════════════════════════════════════════════════════════════ typedef struct packed { + logic [XFER_W-1:0] xfer; logic [SMEM_ADDR_W-1:0] smem_byte_addr; logic [CL_OFF_BITS-1:0] byte_offset; logic [CL_OFF_BITS:0] valid_length; logic oob; - logic last; logic [15:0] k_row; // tiled scatter logic [15:0] n_base; // tiled scatter } slot_t; - slot_t slot_table_r [MAX_OUTSTANDING]; // ════════════════════════════════════════════════════════════════════ - // Per-tag occupancy bookkeeping. - // busy[T] : slot is currently in flight (issued, not released). - // oob_pending[T] : OOB slot that hasn't been presented to smem_wr yet. - // outstanding_count_r : # of set bits in busy. + // Tag pools. The pool is sized to the memory latency, so tags are handed + // out in FIFO order rather than picked by a pool-wide priority encoder: + // never-used tags count up from 0, released tags recycle through a FIFO. + // OOB lines wait for smem_wr in a FIFO of their tags, in issue order. // ════════════════════════════════════════════════════════════════════ - reg [MAX_OUTSTANDING-1:0] busy_r; - reg [MAX_OUTSTANDING-1:0] oob_pending_r; - reg [SEQ_W-1:0] outstanding_count_r; - - // Free-tag picker: priority-encode the inverse of busy_r. - wire [TAG_W-1:0] free_tag; - wire have_free_tag; - VX_priority_encoder #( - .N (MAX_OUTSTANDING) - ) free_pe ( - .data_in (~busy_r), - .index_out (free_tag), - .valid_out (have_free_tag), - `UNUSED_PIN (onehot_out) + reg [TAG_W:0] fresh_r; + wire fresh_avail = ~fresh_r[TAG_W]; + wire [TAG_W-1:0] recycled_tag; + wire recycled_empty; + wire accept; + + VX_fifo_queue #( + .DATAW (TAG_W), + .DEPTH (MAX_OUTSTANDING) + ) free_fifo ( + .clk (clk), + .reset (reset), + .push (release_en), + .pop (accept && ~fresh_avail), + .data_in (release_tag), + .data_out (recycled_tag), + .empty (recycled_empty), + `UNUSED_PIN (alm_empty), + `UNUSED_PIN (full), + `UNUSED_PIN (alm_full), + `UNUSED_PIN (size) ); - // OOB-tag picker: priority-encode oob_pending_r. + wire have_free_tag = fresh_avail || ~recycled_empty; + wire [TAG_W-1:0] free_tag = fresh_avail ? fresh_r[TAG_W-1:0] : recycled_tag; + + always @(posedge clk) begin + if (reset) begin + fresh_r <= '0; + end else if (accept && fresh_avail) begin + fresh_r <= fresh_r + (TAG_W+1)'(1); + end + end + wire [TAG_W-1:0] oob_tag; - wire have_oob; - VX_priority_encoder #( - .N (MAX_OUTSTANDING) - ) oob_pe ( - .data_in (oob_pending_r), - .index_out (oob_tag), - .valid_out (have_oob), - `UNUSED_PIN (onehot_out) + wire oob_empty; + wire oob_fire; + wire oob_take; + + VX_fifo_queue #( + .DATAW (TAG_W), + .DEPTH (MAX_OUTSTANDING) + ) oob_fifo ( + .clk (clk), + .reset (reset), + .push (oob_fire), + .pop (oob_take), + .data_in (free_tag), + .data_out (oob_tag), + .empty (oob_empty), + `UNUSED_PIN (alm_empty), + `UNUSED_PIN (full), + `UNUSED_PIN (alm_full), + `UNUSED_PIN (size) ); + wire have_oob = ~oob_empty; + // ════════════════════════════════════════════════════════════════════ // Issue logic // ════════════════════════════════════════════════════════════════════ @@ -154,8 +178,8 @@ module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( wire can_alloc = have_free_tag; wire normal_fire = ag_valid && ~ag_oob && can_alloc && mem_bus_w.req_ready; - wire oob_fire = ag_valid && ag_oob && can_alloc; - wire accept = normal_fire || oob_fire; + assign oob_fire = ag_valid && ag_oob && can_alloc; + assign accept = normal_fire || oob_fire; wire [TAG_W-1:0] alloc_tag = free_tag; @@ -164,34 +188,76 @@ module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( assign stall_no_slot = ag_valid && ~ag_oob && ~have_free_tag; // ════════════════════════════════════════════════════════════════════ - // Direct-drain channel arbitration. - // Prefer real GMEM responses (so the bus never stalls when smem_wr is - // ready). OOB-synthetic CLs fill in cycles when there's no bus rsp. + // Response stage. The slot table is sized to the memory latency, so it + // lives in a RAM with a registered read: a CL spends one cycle here while + // its slot is read. A real GMEM response has priority (so the bus never + // stalls while smem_wr is ready); OOB-synthetic CLs fill the other cycles. // ════════════════════════════════════════════════════════════════════ wire bus_rsp_present = mem_bus_w.rsp_valid; wire [TAG_W-1:0] bus_rsp_tag = TAG_W'(mem_bus_w.rsp_data.tag.value); - wire present_oob = ~bus_rsp_present && have_oob; - - wire [TAG_W-1:0] present_tag = bus_rsp_present ? bus_rsp_tag : oob_tag; - slot_t present_slot; - assign present_slot = slot_table_r[present_tag]; - - assign sw_valid = bus_rsp_present || present_oob; - assign sw_tag = present_tag; - assign sw_data = mem_bus_w.rsp_data.data; // don't-care when sw_oob. - assign sw_smem_byte_addr = present_slot.smem_byte_addr; - assign sw_byte_offset = present_slot.byte_offset; - assign sw_valid_length = present_slot.valid_length; - assign sw_oob = present_slot.oob; - assign sw_last = present_slot.last; - assign sw_k_row = present_slot.k_row; - assign sw_n_base = present_slot.n_base; - assign sw_outstanding = outstanding_count_r; - - // The bus is accepted by smem_wr (via sw_ready) only when we present - // a real rsp; OOB presentations don't touch the bus port. - assign mem_bus_w.rsp_ready = sw_ready && bus_rsp_present; + wire in_valid = bus_rsp_present || have_oob; + wire [TAG_W-1:0] in_tag = bus_rsp_present ? bus_rsp_tag : oob_tag; + + reg stg_valid_r; + reg [TAG_W-1:0] stg_tag_r; + reg [GMEM_DATAW-1:0] stg_data_r; + + wire stg_load = in_valid && (~stg_valid_r || sw_ready); + assign oob_take = stg_load && ~bus_rsp_present; + + slot_t alloc_slot, stg_slot; + assign alloc_slot.xfer = ag_xfer; + assign alloc_slot.smem_byte_addr = ag_smem_byte_addr; + assign alloc_slot.byte_offset = ag_byte_offset; + assign alloc_slot.valid_length = ag_valid_length; + assign alloc_slot.oob = ag_oob; + assign alloc_slot.k_row = ag_k_row; + assign alloc_slot.n_base = ag_n_base; + + VX_dp_ram #( + .DATAW ($bits(slot_t)), + .SIZE (MAX_OUTSTANDING), + .OUT_REG (1), + .RDW_MODE ("W") + ) slot_store ( + .clk (clk), + .reset (reset), + .read (1'b1), + .write (accept), + .wren (1'b1), + .waddr (alloc_tag), + .wdata (alloc_slot), + .raddr (stg_load ? in_tag : stg_tag_r), + .rdata (stg_slot) + ); + + always @(posedge clk) begin + if (reset) begin + stg_valid_r <= 1'b0; + end else if (stg_load) begin + stg_valid_r <= 1'b1; + end else if (sw_ready) begin + stg_valid_r <= 1'b0; + end + if (stg_load) begin + stg_tag_r <= in_tag; + stg_data_r <= mem_bus_w.rsp_data.data; // don't-care for an OOB CL + end + end + + assign sw_valid = stg_valid_r; + assign sw_tag = stg_tag_r; + assign sw_xfer = stg_slot.xfer; + assign sw_data = stg_data_r; + assign sw_smem_byte_addr = stg_slot.smem_byte_addr; + assign sw_byte_offset = stg_slot.byte_offset; + assign sw_valid_length = stg_slot.valid_length; + assign sw_oob = stg_slot.oob; + assign sw_k_row = stg_slot.k_row; + assign sw_n_base = stg_slot.n_base; + + assign mem_bus_w.rsp_ready = stg_load && bus_rsp_present; // ════════════════════════════════════════════════════════════════════ // GMEM bus wiring (read-only requests) @@ -205,43 +271,6 @@ module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( assign mem_bus_w.req_data.tag.uuid = active_uuid; assign mem_bus_w.req_data.tag.value = GMEM_TAG_VALUEW'(alloc_tag); - // ════════════════════════════════════════════════════════════════════ - // Sequential update - // ════════════════════════════════════════════════════════════════════ - wire oob_present_fire = present_oob && sw_ready; - wire [MAX_OUTSTANDING-1:0] busy_set = accept ? (MAX_OUTSTANDING'(1) << alloc_tag) : '0; - wire [MAX_OUTSTANDING-1:0] busy_clr = release_en ? (MAX_OUTSTANDING'(1) << release_tag) : '0; - wire [MAX_OUTSTANDING-1:0] oob_pending_set = oob_fire ? (MAX_OUTSTANDING'(1) << alloc_tag) : '0; - wire [MAX_OUTSTANDING-1:0] oob_pending_clr = oob_present_fire ? (MAX_OUTSTANDING'(1) << oob_tag) : '0; - - always @(posedge clk) begin - if (reset) begin - busy_r <= '0; - oob_pending_r <= '0; - outstanding_count_r <= '0; - end else begin - if (accept) begin - slot_table_r[alloc_tag].smem_byte_addr <= ag_smem_byte_addr; - slot_table_r[alloc_tag].byte_offset <= ag_byte_offset; - slot_table_r[alloc_tag].valid_length <= ag_valid_length; - slot_table_r[alloc_tag].oob <= ag_oob; - slot_table_r[alloc_tag].last <= ag_last; - slot_table_r[alloc_tag].k_row <= ag_k_row; - slot_table_r[alloc_tag].n_base <= ag_n_base; - end - - busy_r <= (busy_r | busy_set ) & ~busy_clr; - oob_pending_r <= (oob_pending_r | oob_pending_set) & ~oob_pending_clr; - - // Outstanding count: increments on accept, decrements on release. - case ({accept, release_en}) - 2'b10: outstanding_count_r <= outstanding_count_r + SEQ_W'(1); - 2'b01: outstanding_count_r <= outstanding_count_r - SEQ_W'(1); - default: ; - endcase - end - end - VX_mem_bus_slice #( .DATA_SIZE (GMEM_BYTES), .TAG_WIDTH (GMEM_TAG_WIDTH), @@ -254,57 +283,23 @@ module VX_dxa_gmem_req import VX_gpu_pkg::*, VX_dxa_pkg::*; #( .bus_out_if (gmem_bus_if) ); -`ifdef PERF_ENABLE - reg [31:0] rdp_total_gmem_req_r; - reg [31:0] rdp_cycle_ctr_r; - reg [31:0] rdp_first_req_cycle_r; - reg [31:0] rdp_last_rsp_cycle_r; - reg rdp_has_req_r; - - always @(posedge clk) begin - if (reset || transfer_start) begin - rdp_total_gmem_req_r <= '0; - rdp_cycle_ctr_r <= '0; - rdp_first_req_cycle_r <= '0; - rdp_last_rsp_cycle_r <= '0; - rdp_has_req_r <= 1'b0; - end else begin - rdp_cycle_ctr_r <= rdp_cycle_ctr_r + 32'd1; - if (normal_fire) begin - rdp_total_gmem_req_r <= rdp_total_gmem_req_r + 32'd1; - if (!rdp_has_req_r) begin - rdp_first_req_cycle_r <= rdp_cycle_ctr_r; - rdp_has_req_r <= 1'b1; - end - end - if (release_en) begin - rdp_last_rsp_cycle_r <= rdp_cycle_ctr_r; - end - end - end - - assign perf_gmem_reqs = rdp_total_gmem_req_r; - assign perf_gmem_span_cycles = (rdp_has_req_r && rdp_last_rsp_cycle_r >= rdp_first_req_cycle_r) - ? (rdp_last_rsp_cycle_r - rdp_first_req_cycle_r + 32'd1) : 32'd0; -`endif - `ifdef DBG_TRACE_DXA always @(posedge clk) begin - if (~reset && transfer_active) begin + if (~reset) begin if (normal_fire) begin - $write("DXA_PIPE,%0d,GMEM_REQ,addr=0x%0h,tag=%0d,smem=0x%0h\n", - $time, ag_cl_addr, alloc_tag, ag_smem_byte_addr); + $write("DXA_PIPE,%0d,GMEM_REQ,addr=0x%0h,tag=%0d,xfer=%0d,smem=0x%0h\n", + $time, ag_cl_addr, alloc_tag, ag_xfer, ag_smem_byte_addr); end if (oob_fire) begin - $write("DXA_PIPE,%0d,GMEM_OOB,tag=%0d,smem=0x%0h,last=%0d\n", - $time, alloc_tag, ag_smem_byte_addr, ag_last); + $write("DXA_PIPE,%0d,GMEM_OOB,tag=%0d,xfer=%0d,smem=0x%0h\n", + $time, alloc_tag, ag_xfer, ag_smem_byte_addr); end end end `endif - `UNUSED_VAR (transfer_active) - `UNUSED_VAR (transfer_start) - `UNUSED_VAR (mem_bus_w.req_data.tag.value[GMEM_TAG_VALUEW-1:TAG_W]) + if (GMEM_TAG_VALUEW > TAG_W) begin : g_tag_unused + `UNUSED_VAR (mem_bus_w.req_data.tag.value[GMEM_TAG_VALUEW-1:TAG_W]) + end endmodule diff --git a/hw/rtl/dxa/VX_dxa_pkg.sv b/hw/rtl/dxa/VX_dxa_pkg.sv index f87414b545..d83c56f835 100644 --- a/hw/rtl/dxa/VX_dxa_pkg.sv +++ b/hw/rtl/dxa/VX_dxa_pkg.sv @@ -124,6 +124,41 @@ package VX_dxa_pkg; logic [3:0] lg_bkK; // log2(dense B block K extent, in elements) } dxa_setup_params_t; + // Per-transfer context the SMEM writer reads for every line it drains. A + // worker issues its next transfer while earlier ones drain, so each line + // names its transfer and finds its destination and completion here. + typedef struct packed { + logic [NC_WIDTH-1:0] core_id; + logic [UUID_WIDTH-1:0] uuid; + logic [BAR_ADDR_W-1:0] bar_addr; + logic notify_smem_done; + logic is_multicast; + logic [`VX_CFG_NUM_WARPS-1:0] cta_mask; + logic [DXA_LMEM_ADDR_W-1:0] stride_words; // multicast receiver step + logic [31:0] cfill; + logic scatter; // one element per beat (K-major or tiled) + logic tiled; // Flat/BlockMajor permuted destination + logic is_flat; + logic [3:0] elem_bytes; + logic [DXA_SMEM_ADDR_W-1:0] lane_stride; // K-major step per element + // Tiled destination: per-beat step inside an n-block and across a block + // wrap, and the per-line element-0 permute terms (see VX_dxa_smem_wr). + logic [DXA_SMEM_ADDR_W-1:0] tiled_step; + logic [DXA_SMEM_ADDR_W-1:0] tiled_wrap; + logic [15:0] tcn_mask; + logic [3:0] lg_tcN; + logic [3:0] lg_ratio; + logic [3:0] lg_bkK; + logic [3:0] lg_nsteps; + logic [3:0] esize; + logic [4:0] calc_sh2; + logic [4:0] intra_khi_sh; + logic [4:0] intra_n_sh; + logic [15:0] intra_khi_mask; + logic [15:0] intra_klo_mask; + logic [DXA_SMEM_ADDR_W-1:0] smem_base; + } dxa_xfer_t; + // SMEM byte destination for B element (k = K-row, n = N-col) under the // bbuf-native Flat / BlockMajor layouts. Mirrors vx_tensor.h::b_sp_flat_idx // and b_blockmajor_idx; tcK == tcN for canonical WGMMA configs. Every diff --git a/hw/rtl/dxa/VX_dxa_setup.sv b/hw/rtl/dxa/VX_dxa_setup.sv index bcb3db0454..f5cf11663d 100644 --- a/hw/rtl/dxa/VX_dxa_setup.sv +++ b/hw/rtl/dxa/VX_dxa_setup.sv @@ -11,13 +11,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -// DXA Setup: owns transfer lifecycle, issue decode, metadata latching, +// DXA Setup: owns the issue lifecycle, issue decode, metadata latching, // and DSP-based parameter precomputation. The setup engine runs in -// parallel with an active transfer's drain: a new request is accepted +// parallel with an active transfer's issue: a new request is accepted // the cycle the DSPs are idle, the result lands in `staged_*`, and is // promoted to the live `r_*` registers the cycle the previous transfer -// completes. Setup latency overlaps with drain, eliminating the -// pipeline bubble for streamed transfers. +// issues its last line, provided a transfer context is free. Earlier +// transfers keep draining meanwhile. // // Rank-dependent setup latency (cycles from launch_accept to staged): // rank 1-2: 4, rank 3: 6, rank 4: 8, rank 5: 10. @@ -36,11 +36,12 @@ module VX_dxa_setup import VX_gpu_pkg::*, VX_dxa_pkg::*; ( input wire dxa_req_data_t req_data, input wire dxa_desc_t desc_data, - // Transfer done (from smem_wr). - input wire transfer_done, + // The issuing transfer's last line was accepted (from gmem_req). + input wire issue_done, + // A transfer context is free for the next transfer. + input wire xfer_avail, // State outputs. - output wire transfer_active, output wire pipeline_start, // Precomputed parameters (stable during ACTIVE). @@ -61,14 +62,13 @@ module VX_dxa_setup import VX_gpu_pkg::*, VX_dxa_pkg::*; ( localparam MUL_LATENCY = 2; // ════════════════════════════════════════════════════════════════════ - // Transfer state: TS_IDLE / TS_ACTIVE. + // Issue state: TS_IDLE / TS_ACTIVE (a transfer is issuing its lines). // (TS_SETUP is gone — setup is tracked separately by setup_state_r.) // ════════════════════════════════════════════════════════════════════ localparam TS_IDLE = 1'b0; localparam TS_ACTIVE = 1'b1; reg state_r; - assign transfer_active = (state_r == TS_ACTIVE); // ════════════════════════════════════════════════════════════════════ // Setup engine state: SS_IDLE / SS_RUNNING / SS_STAGED. @@ -368,12 +368,12 @@ module VX_dxa_setup import VX_gpu_pkg::*, VX_dxa_pkg::*; ( // ════════════════════════════════════════════════════════════════════ // Promote: copy staged → active and pulse pipeline_start. - // Fires when a staged result exists AND the active slot is free - // (either idle, or completing this cycle via transfer_done). + // Fires when a staged result exists, a transfer context is free, AND the + // issuer is free (either idle, or issuing its last line this cycle). // ════════════════════════════════════════════════════════════════════ - wire promote_now = (setup_state_r == SS_STAGED) - && (state_r == TS_IDLE || transfer_done); + wire promote_now = (setup_state_r == SS_STAGED) && xfer_avail + && (state_r == TS_IDLE || issue_done); reg pipeline_start_r; assign pipeline_start = pipeline_start_r; @@ -449,8 +449,8 @@ module VX_dxa_setup import VX_gpu_pkg::*, VX_dxa_pkg::*; ( state_r <= TS_ACTIVE; pipeline_start_r <= 1'b1; setup_state_r <= SS_IDLE; - end else if (state_r == TS_ACTIVE && transfer_done) begin - // Active drain complete, no staged result waiting. + end else if (state_r == TS_ACTIVE && issue_done) begin + // Active issue complete, no staged result waiting. state_r <= TS_IDLE; end diff --git a/hw/rtl/dxa/VX_dxa_smem_wr.sv b/hw/rtl/dxa/VX_dxa_smem_wr.sv index c39682b77b..7bcf75969f 100644 --- a/hw/rtl/dxa/VX_dxa_smem_wr.sv +++ b/hw/rtl/dxa/VX_dxa_smem_wr.sv @@ -15,10 +15,10 @@ // // Receives CLs directly from gmem_req on the `sw_*` channel, no rsp_buf // in the middle. The pend slot is filled asynchronously by whatever rsp -// (real or OOB-synthetic) gmem_req presents. The CL marked `last` is -// special — it must drain LAST because its bus packet carries -// notify_smem_done; we hold it in `defer_*_r` until all other CLs have -// released, then promote it to pend. +// (real or OOB-synthetic) gmem_req presents, from any transfer in flight; +// each CL carries its transfer's context. The transfer's notify_smem_done +// rides the write of whichever CL drains last: the one loaded into the fill +// buffer once its transfer has issued every CL and has nothing else pending. // // Drain: pend → barrel-shift → fb_data_r → SMEM_WORD beats. // 1 SMEM-word/cycle steady state. @@ -27,82 +27,56 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( parameter MAX_OUTSTANDING = 8, + parameter NUM_XFERS = 2, parameter CL_SIZE = `VX_CFG_L1_LINE_SIZE, parameter SMEM_WORD_SIZE = DXA_LMEM_WORD_SIZE, parameter SMEM_ADDR_WIDTH = DXA_LMEM_ADDR_W, parameter GMEM_DATAW = CL_SIZE * 8, localparam CL_OFF_BITS = `CLOG2(CL_SIZE), localparam TAG_W = `CLOG2(MAX_OUTSTANDING), - localparam SEQ_W = `CLOG2(MAX_OUTSTANDING + 1) + localparam SEQ_W = `CLOG2(MAX_OUTSTANDING + 1), + localparam XFER_W = `LOG2UP(NUM_XFERS) ) ( input wire clk, input wire reset, - input wire transfer_active, - input wire transfer_start, - // cfill (stable during transfer). - input wire [31:0] cfill, - - // Metadata for SMEM bus tag + completion attr. - input wire [NC_WIDTH-1:0] active_core_id, - input wire [UUID_WIDTH-1:0] active_uuid, - input wire [BAR_ADDR_W-1:0] active_bar_addr, - input wire active_notify_smem_done, + // Transfer contexts (registered read for the captured CL, combinational + // read of the arrival fields), and per transfer: all CLs issued, CLs not + // yet written. + output wire [XFER_W-1:0] pend_raddr, + input dxa_xfer_t pend_rdata, + input wire [31:0] cap_cfill, + input wire cap_scatter, + input wire cap_tiled, + input wire [3:0] cap_lg_tcN, + input wire [NUM_XFERS-1:0] xfer_issued, + input wire [NUM_XFERS-1:0][SEQ_W-1:0] xfer_pending, // Direct drain channel (from gmem_req). input wire sw_valid, output wire sw_ready, input wire [TAG_W-1:0] sw_tag, + input wire [XFER_W-1:0] sw_xfer, input wire [GMEM_DATAW-1:0] sw_data, input wire [DXA_SMEM_ADDR_W-1:0] sw_smem_byte_addr, input wire [CL_OFF_BITS-1:0] sw_byte_offset, input wire [CL_OFF_BITS:0] sw_valid_length, input wire sw_oob, - input wire sw_last, input wire [15:0] sw_k_row, // tiled scatter input wire [15:0] sw_n_base, // tiled scatter - input wire [SEQ_W-1:0] sw_outstanding, // Resource release to gmem_req (per-tag, OOO). output wire release_en, output wire [TAG_W-1:0] release_tag, + output wire [XFER_W-1:0] release_xfer, // SMEM bus interface (writes only). VX_mem_bus_if.master smem_bus_if, // Completion. - output wire transfer_done, - output wire [31:0] wr_done_count, - output wire smem_req_fire, - - // Multicast (always available; active when is_multicast is set). - input wire is_multicast, - input wire [`VX_CFG_NUM_WARPS-1:0] cta_mask, - input wire [31:0] smem_stride, - - // K-major scatter mode (stable per transfer): - // dest_kmajor=1 → drain one element (elem_bytes wide) per SMEM beat, - // with per-beat addr += per_lane_stride_bytes. byteen masks all bytes - // except the `elem_bytes`-wide window at the current in-word offset. - input wire dest_kmajor, - input wire [15:0] per_lane_stride_bytes, - input wire [3:0] elem_bytes, - - // Tiled (Flat/BlockMajor) scatter geometry (stable per transfer). When - // dest_mode is Flat/BlockMajor the per-element SMEM byte address is the - // bbuf-native index dxa_tiled_dest_byte(k_row, n), drained 1 element/beat - // like K-major but with a permuted (non-uniform) destination. - input wire [1:0] dest_mode, - input wire [3:0] lg_ratio, - input wire [3:0] lg_tcN, - input wire [3:0] lg_nsteps, - input wire [3:0] lg_bkK, - input wire [DXA_SMEM_ADDR_W-1:0] smem_base // tile SMEM byte base - -`ifdef PERF_ENABLE - , - output wire [31:0] perf_lmem_writes -`endif + output wire xfer_done, + output wire [XFER_W-1:0] xfer_done_idx, + output wire smem_req_fire ); localparam SMEM_OFF_W = `CLOG2(SMEM_WORD_SIZE); localparam SMEM_DATAW = SMEM_WORD_SIZE * 8; @@ -117,93 +91,22 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( localparam ENGINE_VALUE_W = DXA_LMEM_ENGINE_TAG_W - UUID_WIDTH; localparam SMEM_TAG_VALUE_W = DXA_LMEM_TAG_W - UUID_WIDTH; - // ════════════════════════════════════════════════════════════════════ - // Per-transfer descriptor snapshot. These fields are constant from - // transfer_start until completion, and the first CL arrives only after - // the GMEM round-trip; registering them locally keeps every beat-rate - // cone sourced at local registers instead of routing from the - // setup/addr-gen configuration registers on every beat. - // ════════════════════════════════════════════════════════════════════ - reg [1:0] dest_mode_q; - reg dest_kmajor_q; - reg [3:0] elem_bytes_q; - reg [3:0] lg_ratio_q, lg_tcN_q, lg_nsteps_q, lg_bkK_q; - reg [DXA_SMEM_ADDR_W-1:0] smem_base_q; - reg [DXA_SMEM_ADDR_W-1:0] per_lane_stride_q; - always @(posedge clk) begin - dest_mode_q <= dest_mode; - dest_kmajor_q <= dest_kmajor; - elem_bytes_q <= elem_bytes; - lg_ratio_q <= lg_ratio; - lg_tcN_q <= lg_tcN; - lg_nsteps_q <= lg_nsteps; - lg_bkK_q <= lg_bkK; - smem_base_q <= smem_base; - per_lane_stride_q <= DXA_SMEM_ADDR_W'(per_lane_stride_bytes); - end - - // ════════════════════════════════════════════════════════════════════ - // Scatter mode: K-major (uniform stride) OR tiled Flat/BlockMajor - // (permuted dest). Both drain 1 element/beat (vs row-major streaming). - // ════════════════════════════════════════════════════════════════════ - wire dest_tiled = (dest_mode_q == DXA_DEST_FLAT) || (dest_mode_q == DXA_DEST_BLOCKMAJOR); - wire scatter = dest_kmajor_q || dest_tiled; - // esize = log2(elem_bytes), for the tiled destination formula. - wire [3:0] esize = (elem_bytes_q == 4'd8) ? 4'd3 - : (elem_bytes_q == 4'd4) ? 4'd2 - : (elem_bytes_q == 4'd2) ? 4'd1 : 4'd0; - - // Incremental tiled addressing: within a transfer, n advances by one per - // drain beat and dxa_tiled_dest_byte is affine in n inside an n-block, so - // the per-beat byte delta is one of two per-transfer constants (in-block - // step, block-wrap step). Deriving them once here removes the per-beat - // permute from the drain path entirely; the full permute runs only once - // per CL at capture (sw_dest_addr below). - // FLAT: step = 1 << (lg_ratio+esize) - // wrap = ((1 << (2*lg_tcN+1)) - (tcN-1)) << (lg_ratio+esize) - // BlockMajor: step = 1 << (lg_bkK+esize) - // wrap = ((1 << lg_tcN) - (tcN-1)) << (lg_bkK+esize) (= step) - reg [15:0] tcn_mask_q; - reg [DXA_SMEM_ADDR_W-1:0] tiled_step_q; - reg [DXA_SMEM_ADDR_W-1:0] tiled_wrap_q; - reg [4:0] calc_sh2_q; - reg [15:0] intra_khi_mask_q, intra_klo_mask_q; - reg [4:0] intra_khi_sh_q, intra_n_sh_q; - reg [3:0] esize_q; - wire is_flat_w = (dest_mode_q == DXA_DEST_FLAT); - wire [15:0] tcn_mask_w = (16'd1 << lg_tcN_q) - 16'd1; - wire [4:0] step_sh_w = is_flat_w ? (5'(lg_ratio_q) + 5'(esize)) - : (5'(lg_bkK_q) + 5'(esize)); - wire [DXA_SMEM_ADDR_W-1:0] wrap_elems_w = is_flat_w - ? ((DXA_SMEM_ADDR_W'(1) << (5'(lg_tcN_q) + 5'(lg_tcN_q) + 5'd1)) - DXA_SMEM_ADDR_W'(tcn_mask_w)) - : ((DXA_SMEM_ADDR_W'(1) << lg_tcN_q) - DXA_SMEM_ADDR_W'(tcn_mask_w)); - always @(posedge clk) begin - tcn_mask_q <= tcn_mask_w; - tiled_step_q <= DXA_SMEM_ADDR_W'(1) << step_sh_w; - tiled_wrap_q <= wrap_elems_w << step_sh_w; - // block-index shift of the per-CL dest calc (stage 2 below): - // FLAT: 2*lg_tcN+1+lg_ratio+esize BM: lg_tcN+lg_bkK+esize - calc_sh2_q <= is_flat_w - ? (5'(lg_tcN_q) + 5'(lg_tcN_q) + 5'd1 + 5'(lg_ratio_q) + 5'(esize)) - : (5'(lg_tcN_q) + 5'(lg_bkK_q) + 5'(esize)); - // intra-block term of the per-CL dest calc (stage 1 below), as disjoint - // k/n bit fields shifted into place: - // FLAT: k[hi] << (lg_tcN+esize) | n_in << (lg_ratio+esize) | k[lo] << esize - // hi = ((2 << lg_tcN) - 1) << lg_ratio, lo = (1 << lg_ratio) - 1 - // BM: n_in << (lg_bkK+esize) | k[lo] << esize, lo = (1 << lg_bkK) - 1 - intra_khi_mask_q <= is_flat_w ? (((16'd2 << lg_tcN_q) - 16'd1) << lg_ratio_q) : 16'd0; - intra_khi_sh_q <= 5'(lg_tcN_q) + 5'(esize); - intra_n_sh_q <= step_sh_w; - intra_klo_mask_q <= (16'd1 << (is_flat_w ? lg_ratio_q : lg_bkK_q)) - 16'd1; - esize_q <= esize; - end + // The context of the captured CL (dest calc, fb-load) comes from the + // context RAM, addressed one cycle ahead so it lands with pend_xfer_r; the + // arriving CL (capture) reads only its few arrival fields. A CL's context is + // copied into fb_x_r at fb-load, so every beat-rate cone starts at a local + // register. + dxa_xfer_t pend_x; + reg [XFER_W-1:0] pend_xfer_r; + assign pend_x = pend_rdata; + wire [15:0] cap_tcn_mask = (16'd1 << cap_lg_tcN) - 16'd1; // ════════════════════════════════════════════════════════════════════ // Cfill replication (for OOB CLs) // ════════════════════════════════════════════════════════════════════ wire [GMEM_DATAW-1:0] cfill_replicated; for (genvar i = 0; i < CL_SIZE / 4; ++i) begin : g_cfill - assign cfill_replicated[i*32 +: 32] = cfill; + assign cfill_replicated[i*32 +: 32] = cap_cfill; end // ════════════════════════════════════════════════════════════════════ @@ -213,7 +116,6 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( reg [TAG_W-1:0] pend_tag_r; reg [DXA_SMEM_ADDR_W-1:0] pend_smem_byte_addr_r; reg [CL_OFF_BITS:0] pend_valid_length_r; - reg pend_last_r; // Tiled scatter: the CL's raw (k, n) captured from the sw channel, its n // phase within an n-block, and the element-0 destination computed by the // shared permute one cycle after capture (pend_calc_r marks it pending; @@ -229,27 +131,13 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( reg [FILL_CAP*8-1:0] pend_data_r; reg [COARSE_W-1:0] pend_coarse_r; - // ════════════════════════════════════════════════════════════════════ - // Deferred-last slot — holds the CL marked `last` while other CLs - // drain ahead of it. Promoted to pend when only this CL remains. - // ════════════════════════════════════════════════════════════════════ - reg defer_valid_r; - reg [TAG_W-1:0] defer_tag_r; - reg [DXA_SMEM_ADDR_W-1:0] defer_smem_byte_addr_r; - reg [CL_OFF_BITS:0] defer_valid_length_r; - reg [FILL_CAP*8-1:0] defer_data_r; // fine-positioned (see pend_data_r) - reg [COARSE_W-1:0] defer_coarse_r; // coarse word count (see pend_coarse_r) - reg [15:0] defer_k_r, defer_n_r; - reg [DXA_SMEM_ADDR_W-1:0] defer_dest_addr_r; - reg [15:0] defer_n_in_r; - reg defer_calc_r; - reg defer_addr_rdy_r; - // ════════════════════════════════════════════════════════════════════ // Drain fill buffer // ════════════════════════════════════════════════════════════════════ reg fb_active_r; reg [TAG_W-1:0] fb_tag_r; + reg [XFER_W-1:0] fb_xfer_r; + dxa_xfer_t fb_x_r; reg fb_last_r; reg [FILL_CAP*8-1:0] fb_data_r; reg [FILL_W-1:0] fb_level_r; @@ -273,7 +161,8 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // K-major/tiled drain quantum (in bytes) = 1 element per beat in scatter // mode, SMEM_WORD_SIZE bytes per beat in row-major streaming mode. - wire [FILL_W-1:0] drain_q_bytes = scatter ? FILL_W'(elem_bytes_q) : FILL_W'(SMEM_WORD_SIZE); + wire scatter = fb_x_r.scatter; + wire [FILL_W-1:0] drain_q_bytes = scatter ? FILL_W'(fb_x_r.elem_bytes) : FILL_W'(SMEM_WORD_SIZE); // Effective per-element SMEM byte address: both scatter sub-modes read // the fb_byte_addr_r accumulator. wire [SMEM_OFF_W-1:0] km_in_word_off = fb_byte_addr_r[SMEM_OFF_W-1:0]; @@ -321,7 +210,7 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // K-major byteen: `elem_bytes` contiguous bytes at km_in_word_off. wire [SMEM_WORD_SIZE-1:0] km_elem_mask_raw = - SMEM_WORD_SIZE'((SMEM_WORD_SIZE'(1) << elem_bytes_q) - SMEM_WORD_SIZE'(1)); + SMEM_WORD_SIZE'((SMEM_WORD_SIZE'(1) << fb_x_r.elem_bytes) - SMEM_WORD_SIZE'(1)); wire [SMEM_WORD_SIZE-1:0] km_byteen = km_elem_mask_raw << km_in_word_off; wire [SMEM_WORD_SIZE-1:0] rm_byteen; @@ -340,73 +229,35 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // sw-channel accept + load scheduling // ════════════════════════════════════════════════════════════════════ // - // The arriving sw CL takes one of two paths: - // (a) Capture into pend (the 1-deep skid; loaded into fb on the next - // fill-empty boundary). All non-deferred CLs use this path. - // (b) Capture into defer_*_r (it's the `last` CL and we still have - // other CLs outstanding to drain first). - // - // Promotion from defer_*_r to fb fires when the last drain leaves only the - // deferred CL outstanding. - - wire sw_is_last_defer = sw_valid && sw_last && (sw_outstanding > SEQ_W'(1)); - wire can_defer = sw_is_last_defer && ~defer_valid_r; - - wire can_capture_pend = ~pend_valid_r; - - // sw_ready conditions: - // - If sw is the last-to-defer: defer is empty → accept. - // - Else: pend can capture → accept. - assign sw_ready = sw_is_last_defer ? can_defer : can_capture_pend; - - wire sw_accept = sw_valid && sw_ready; - wire sw_defer_path = sw_accept && sw_is_last_defer; - // Every non-deferred CL is captured into pend (no combinational sw→fb bypass), - // so the fb-load source is always a register; only the shallow coarse shift is - // on the load path. The extra cycle is at fill-empty boundaries only. - wire sw_pend_path = sw_accept && ~sw_is_last_defer; - - // Deferred-CL promotion to fb: fires when fb is emptying and we are - // about to be down to 1 outstanding (= just the deferred). - // Equivalent: sw_outstanding == 2 && drain_emptying_now, or - // sw_outstanding == 1 with fb idle (no other CL in flight). - // Tiled loads additionally wait for the slot's dest-addr calc pipeline - // (2 cycles after capture) to complete. - wire pend_addr_ok = pend_addr_rdy_r; - wire defer_addr_ok = defer_addr_rdy_r; - - wire promote_defer = defer_valid_r && defer_addr_ok && fb_will_be_empty && ~pend_valid_r - && ((sw_outstanding == SEQ_W'(1)) - || (sw_outstanding == SEQ_W'(2) && drain_emptying_now)); - - // pend → fb load (existing pend has data ready, fb emptying). - wire load_pend_to_fb = pend_valid_r && pend_addr_ok && fb_will_be_empty; - - // ════════════════════════════════════════════════════════════════════ - // fb-load source select (pend preferred over a promoted defer) + metadata. - // ════════════════════════════════════════════════════════════════════ - wire use_pend_for_fb = load_pend_to_fb; - wire use_defer_for_fb = promote_defer && ~use_pend_for_fb; - wire fb_load_now = use_pend_for_fb || use_defer_for_fb; + // Every arriving CL is captured into pend (no combinational sw→fb bypass), + // so the fb-load source is always a register; only the shallow coarse shift + // is on the load path. The extra cycle is at fill-empty boundaries only. + assign sw_ready = ~pend_valid_r; + wire sw_accept = sw_valid && sw_ready; + assign pend_raddr = sw_accept ? sw_xfer : pend_xfer_r; + + // pend → fb load (pend has data and, for tiled loads, its dest address). + wire fb_load_now = pend_valid_r && pend_addr_rdy_r && fb_will_be_empty; + + // The CL being loaded is its transfer's final one when the transfer has + // issued every CL and this is the only one still pending (the CL draining + // out of fb this cycle releases its count as this one loads). + wire [SEQ_W-1:0] pend_xfer_left = xfer_pending[pend_xfer_r] + - SEQ_W'(drain_emptying_now && (fb_xfer_r == pend_xfer_r)); + wire pend_final = xfer_issued[pend_xfer_r] && (pend_xfer_left == SEQ_W'(1)); // Apply the coarse whole-word shift the capture stage deferred; with the fine - // shift already in pend/defer this fully positions the payload. - wire [FILL_CAP*8-1:0] fb_load_fine = use_pend_for_fb ? pend_data_r : defer_data_r; - wire [COARSE_W-1:0] fb_load_coarse = use_pend_for_fb ? pend_coarse_r : defer_coarse_r; - wire [FILL_CAP*8-1:0] fb_load_data = fb_load_fine >> {fb_load_coarse, {SMEM_DATAW_LOG{1'b0}}}; - wire [DXA_SMEM_ADDR_W-1:0] fb_load_smem_byte_addr = use_pend_for_fb ? pend_smem_byte_addr_r : defer_smem_byte_addr_r; - wire [CL_OFF_BITS:0] fb_load_valid_length = use_pend_for_fb ? pend_valid_length_r : defer_valid_length_r; - wire [TAG_W-1:0] fb_load_tag = use_pend_for_fb ? pend_tag_r : defer_tag_r; - wire fb_load_last = use_pend_for_fb ? pend_last_r : 1'b1; // promoted defer is the last - wire [DXA_SMEM_ADDR_W-1:0] fb_load_dest_addr = use_pend_for_fb ? pend_dest_addr_r : defer_dest_addr_r; - wire [15:0] fb_load_n_in = use_pend_for_fb ? pend_n_in_r : defer_n_in_r; + // shift already in pend this fully positions the payload. + wire [FILL_CAP*8-1:0] fb_load_data = pend_data_r >> {pend_coarse_r, {SMEM_DATAW_LOG{1'b0}}}; + wire [DXA_SMEM_ADDR_W-1:0] fb_load_smem_byte_addr = pend_smem_byte_addr_r; + wire [CL_OFF_BITS:0] fb_load_valid_length = pend_valid_length_r; wire [SMEM_OFF_W-1:0] new_smem_byte_off = fb_load_smem_byte_addr[SMEM_OFF_W-1:0]; wire [SMEM_ADDR_WIDTH-1:0] new_start_word = SMEM_ADDR_WIDTH'(fb_load_smem_byte_addr >> SMEM_OFF_W); // Row-major fill level = leading-offset padding + valid bytes. // K-major fill level = exactly valid_length (each elem drained alone). wire [FILL_W-1:0] new_fill_level = - scatter ? FILL_W'(fb_load_valid_length) + pend_x.scatter ? FILL_W'(fb_load_valid_length) : (FILL_W'(new_smem_byte_off) + FILL_W'(fb_load_valid_length)); // Positioning drops the CL byte_offset and lands bytes at their destination; @@ -419,7 +270,7 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // up to 256B) POS_BIAS+byte_offset exceeds 8 bits, so size to FILL_W to avoid // wrap (which would mis-shift word-aligned rows and drop their data). wire [SMEM_OFF_W-1:0] sw_smem_off = sw_smem_byte_addr[SMEM_OFF_W-1:0]; - wire [FILL_W-1:0] sw_pos_amt = scatter + wire [FILL_W-1:0] sw_pos_amt = cap_scatter ? (FILL_W'(POS_BIAS) + FILL_W'(sw_byte_offset)) : ((FILL_W'(POS_BIAS) + FILL_W'(sw_byte_offset)) - FILL_W'(sw_smem_off)); // Fine = intra-word bytes (capture barrel); coarse = whole words (at fb-load). @@ -431,33 +282,30 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // trees), so it is pipelined over two: stage 1 decomposes the (k, n) // captured the cycle before and folds every element-granular term into // an esize-scaled intra term; stage 2 shifts the block index by the - // registered constant and sums with the base. Per-CL rate makes the - // latency free (a CL drains over many beats); captures are at least a - // cycle apart, so one shared pipeline serves both slots, pend first. - wire calc_pend = pend_calc_r; - wire calc_defer = defer_calc_r && ~pend_calc_r; - wire [15:0] calc_k = calc_pend ? pend_k_r : defer_k_r; - wire [15:0] calc_n = calc_pend ? pend_n_r : defer_n_r; - - wire [15:0] calc_n_blk = calc_n >> lg_tcN_q; - wire [15:0] calc_n_in = calc_n & tcn_mask_q; - wire [15:0] f_k_word = calc_k >> lg_ratio_q; - wire [15:0] f_k_blk = f_k_word >> (lg_tcN_q + 4'd1); - wire [15:0] b_k_blk = calc_k >> lg_bkK_q; - - wire [15:0] calc_k_blk = is_flat_w ? f_k_blk : b_k_blk; - wire [31:0] calc_blk_w = (32'(calc_k_blk) << lg_nsteps_q) + 32'(calc_n_blk); + // transfer's constant and sums with the base. Per-CL rate makes the + // latency free (a CL drains over many beats). pend holds its CL, hence + // its transfer, until both stages have landed. + wire calc_pend = pend_calc_r; + + wire [15:0] calc_n_blk = pend_n_r >> pend_x.lg_tcN; + wire [15:0] calc_n_in = pend_n_r & pend_x.tcn_mask; + wire [15:0] f_k_word = pend_k_r >> pend_x.lg_ratio; + wire [15:0] f_k_blk = f_k_word >> (pend_x.lg_tcN + 4'd1); + wire [15:0] b_k_blk = pend_k_r >> pend_x.lg_bkK; + + wire [15:0] calc_k_blk = pend_x.is_flat ? f_k_blk : b_k_blk; + wire [31:0] calc_blk_w = (32'(calc_k_blk) << pend_x.lg_nsteps) + 32'(calc_n_blk); // the masked fields are disjoint, so the nested shift-adds are one OR - wire [31:0] calc_intra_w = (32'(calc_k & intra_khi_mask_q) << intra_khi_sh_q) - | (32'(calc_n_in) << intra_n_sh_q) - | (32'(calc_k & intra_klo_mask_q) << esize_q); + wire [31:0] calc_intra_w = (32'(pend_k_r & pend_x.intra_khi_mask) << pend_x.intra_khi_sh) + | (32'(calc_n_in) << pend_x.intra_n_sh) + | (32'(pend_k_r & pend_x.intra_klo_mask) << pend_x.esize); reg [31:0] calc_blk_r, calc_intra_r; - reg calc2_valid_r, calc2_pend_r; - wire [DXA_SMEM_ADDR_W-1:0] calc_dest_addr = smem_base_q - + DXA_SMEM_ADDR_W'((calc_blk_r << calc_sh2_q) + calc_intra_r); + reg calc2_valid_r; + wire [DXA_SMEM_ADDR_W-1:0] calc_dest_addr = pend_x.smem_base + + DXA_SMEM_ADDR_W'((calc_blk_r << pend_x.calc_sh2) + calc_intra_r); - wire [15:0] sw_n_in = sw_n_base & tcn_mask_q; + wire [15:0] sw_n_in = sw_n_base & cap_tcn_mask; wire [GMEM_DATAW-1:0] sw_payload = sw_oob ? cfill_replicated : sw_data; wire [FILL_CAP*8-1:0] sw_padded = (FILL_CAP*8)'(sw_payload) << (POS_BIAS*8); @@ -469,13 +317,11 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // Sequential update // ════════════════════════════════════════════════════════════════════ always @(posedge clk) begin - if (reset || transfer_start) begin + if (reset) begin pend_valid_r <= 1'b0; - defer_valid_r <= 1'b0; + pend_xfer_r <= '0; pend_calc_r <= 1'b0; - defer_calc_r <= 1'b0; pend_addr_rdy_r <= 1'b0; - defer_addr_rdy_r <= 1'b0; calc2_valid_r <= 1'b0; fb_active_r <= 1'b0; fb_data_r <= '0; @@ -488,6 +334,8 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( fb_n_in_r <= '0; fb_n_wrap_r <= 1'b0; fb_tag_r <= '0; + fb_xfer_r <= '0; + fb_x_r <= '0; fb_last_r <= 1'b0; end else begin // ── Drain advance (mid-CL beat) ── @@ -496,13 +344,13 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // Read pointer advances; fb_data_r is NOT shifted. K-major // strides the dest uniformly; tiled advances it by the // in-block/wrap constant selected by the registered flag. - km_rd_off_r <= km_rd_off_r + CL_OFF_BITS'(elem_bytes_q); + km_rd_off_r <= km_rd_off_r + CL_OFF_BITS'(fb_x_r.elem_bytes); fb_level_r <= fb_level_r - drain_q_bytes; fb_byte_addr_r <= fb_byte_addr_r - + (dest_tiled ? (fb_n_wrap_r ? tiled_wrap_q : tiled_step_q) - : per_lane_stride_q); + + (fb_x_r.tiled ? (fb_n_wrap_r ? fb_x_r.tiled_wrap : fb_x_r.tiled_step) + : fb_x_r.lane_stride); fb_n_in_r <= fb_n_wrap_r ? 16'd0 : (fb_n_in_r + 16'd1); - fb_n_wrap_r <= ((fb_n_wrap_r ? 16'd0 : (fb_n_in_r + 16'd1)) == tcn_mask_q); + fb_n_wrap_r <= ((fb_n_wrap_r ? 16'd0 : (fb_n_in_r + 16'd1)) == fb_x_r.tcn_mask); end else begin // Row-major: fixed whole-word shift (free), per-beat slice // is the low SMEM_DATAW bits. @@ -513,7 +361,7 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( end // ── Load fill buffer with the next CL ── - // fb_load_data is already fully positioned (fine from pend/defer + + // fb_load_data is already fully positioned (fine from pend + // coarse applied above), so this is a plain register load. if (fb_load_now) begin fb_data_r <= fb_load_data; @@ -521,12 +369,14 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( fb_word_addr_r <= new_start_word; fb_byte_offset_r <= new_smem_byte_off; fb_start_word_r <= new_start_word; - fb_byte_addr_r <= dest_tiled ? fb_load_dest_addr : fb_load_smem_byte_addr; + fb_byte_addr_r <= pend_x.tiled ? pend_dest_addr_r : fb_load_smem_byte_addr; km_rd_off_r <= '0; - fb_n_in_r <= fb_load_n_in; - fb_n_wrap_r <= (fb_load_n_in == tcn_mask_q); - fb_tag_r <= fb_load_tag; - fb_last_r <= fb_load_last; + fb_n_in_r <= pend_n_in_r; + fb_n_wrap_r <= (pend_n_in_r == pend_x.tcn_mask); + fb_tag_r <= pend_tag_r; + fb_xfer_r <= pend_xfer_r; + fb_x_r <= pend_x; + fb_last_r <= pend_final; fb_active_r <= 1'b1; end else if (drain_emptying_now) begin fb_data_r <= '0; @@ -535,61 +385,34 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( end // ── Per-CL dest-addr calc pipeline: stage-1 issue, stage-2 land ── - calc2_valid_r <= calc_pend || calc_defer; - calc2_pend_r <= calc_pend; - if (calc_pend || calc_defer) begin + calc2_valid_r <= calc_pend; + if (calc_pend) begin calc_blk_r <= calc_blk_w; calc_intra_r <= calc_intra_w; - end - if (calc_pend) begin - pend_calc_r <= 1'b0; - end else if (calc_defer) begin - defer_calc_r <= 1'b0; + pend_calc_r <= 1'b0; end if (calc2_valid_r) begin - if (calc2_pend_r) begin - pend_dest_addr_r <= calc_dest_addr; - pend_addr_rdy_r <= 1'b1; - end else begin - defer_dest_addr_r <= calc_dest_addr; - defer_addr_rdy_r <= 1'b1; - end + pend_dest_addr_r <= calc_dest_addr; + pend_addr_rdy_r <= 1'b1; end // ── pend slot management ── - if (sw_pend_path) begin + if (sw_accept) begin pend_tag_r <= sw_tag; + pend_xfer_r <= sw_xfer; pend_smem_byte_addr_r <= sw_smem_byte_addr; pend_valid_length_r <= sw_valid_length; - pend_last_r <= sw_last; pend_data_r <= sw_fine_shifted; pend_coarse_r <= sw_coarse_amt; pend_k_r <= sw_k_row; pend_n_r <= sw_n_base; pend_n_in_r <= sw_n_in; - pend_calc_r <= dest_tiled; - pend_addr_rdy_r <= ~dest_tiled; + pend_calc_r <= cap_tiled; + pend_addr_rdy_r <= ~cap_tiled; pend_valid_r <= 1'b1; - end else if (use_pend_for_fb) begin + end else if (fb_load_now) begin pend_valid_r <= 1'b0; end - - // ── defer slot management ── - if (sw_defer_path) begin - defer_tag_r <= sw_tag; - defer_smem_byte_addr_r <= sw_smem_byte_addr; - defer_valid_length_r <= sw_valid_length; - defer_data_r <= sw_fine_shifted; - defer_coarse_r <= sw_coarse_amt; - defer_k_r <= sw_k_row; - defer_n_r <= sw_n_base; - defer_n_in_r <= sw_n_in; - defer_calc_r <= dest_tiled; - defer_addr_rdy_r <= ~dest_tiled; - defer_valid_r <= 1'b1; - end else if (use_defer_for_fb) begin - defer_valid_r <= 1'b0; - end end end @@ -598,8 +421,9 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // ════════════════════════════════════════════════════════════════════ wire drain_complete = drain_fire && drain_will_empty; - assign release_en = drain_complete; - assign release_tag = fb_tag_r; + assign release_en = drain_complete; + assign release_tag = fb_tag_r; + assign release_xfer = fb_xfer_r; // ════════════════════════════════════════════════════════════════════ // SMEM write output (with optional multicast replay) @@ -615,7 +439,7 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // ════════════════════════════════════════════════════════════════════ // Pipelined multicast replay control // ════════════════════════════════════════════════════════════════════ - // cta_mask/smem_stride are stable per transfer, so the replay walk is a + // cta_mask/smem_stride are stable per CL, so the replay walk is a // deterministic iteration over the set bits of a fixed mask. The // NUM_WARPS-wide priority encoder + popcount are kept in the // register-input path; only registered control reaches the drain-ready @@ -635,17 +459,19 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( wire replay_has_remaining = replay_has_rem_r; wire replay_is_last = replay_is_last_r; - wire mc_write_valid = transfer_active && drain_valid - && (!is_multicast || replay_has_remaining); + wire is_multicast = fb_x_r.is_multicast; + wire mc_write_valid = drain_valid && (!is_multicast || replay_has_remaining); wire mc_write_fire = mc_write_valid && smem_bus_if.req_ready; assign smem_wr_ready_internal = is_multicast ? (smem_bus_if.req_ready && (!replay_has_remaining || replay_is_last)) : smem_bus_if.req_ready; - // Next-cycle replay mask: clear the bit that fires this beat, reload - // cta_mask at word boundaries (after the last receiver) and whenever the + // Next-cycle replay mask: clear the bit that fires this beat, reload the + // mask at word boundaries (after the last receiver) and whenever the // engine is idle, so the first beat of any word starts from the full mask - // without a reload bubble (reproduces the old combinational reload_now). + // without a reload bubble. The mask reloaded is that of the CL in fb next + // cycle: the one loading now, if any. + wire [`VX_CFG_NUM_WARPS-1:0] cta_mask = fb_load_now ? pend_x.cta_mask : fb_x_r.cta_mask; wire replay_beat_fire = mc_write_fire && replay_has_remaining; wire [`VX_CFG_NUM_WARPS-1:0] replay_vec_next = ~drain_valid ? cta_mask // idle: keep primed @@ -653,11 +479,9 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( : replay_is_last ? cta_mask // word done: reload : (replay_vec_r & ~replay_onehot_r); // advance in word - // stride_words: smem_stride is byte units on the bus; convert to word units - // (SMEM_OFF_W = log2(SMEM_WORD_SIZE)). The accumulator mirrors the - // replay_vec_next state machine: 0 when idle/word-boundary, hold on stall, - // +stride_words per serviced receiver. - wire [SMEM_ADDR_WIDTH-1:0] stride_words = SMEM_ADDR_WIDTH'(smem_stride >> SMEM_OFF_W); + // The accumulator mirrors the replay_vec_next state machine: 0 when + // idle/word-boundary, hold on stall, +stride_words per serviced receiver. + wire [SMEM_ADDR_WIDTH-1:0] stride_words = SMEM_ADDR_WIDTH'(fb_x_r.stride_words); wire [SMEM_ADDR_WIDTH-1:0] beat_offset_next = ~drain_valid ? '0 // idle: prime to 0 : ~replay_beat_fire ? beat_offset_r // stalled mid-word @@ -680,14 +504,14 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( && (replay_vec_next == replay_onehot_next); always @(posedge clk) begin - if (reset || transfer_start) begin - replay_vec_r <= cta_mask; + if (reset) begin + replay_vec_r <= '0; replay_next_idx_r <= '0; replay_onehot_r <= '0; replay_has_rem_r <= 1'b0; replay_is_last_r <= 1'b0; beat_offset_r <= '0; - end else if (transfer_active && is_multicast) begin + end else begin replay_vec_r <= replay_vec_next; replay_next_idx_r <= replay_idx_next; replay_onehot_r <= replay_onehot_next; @@ -706,13 +530,6 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( ("the CTA slot pitch must be a whole number of SMEM words")) wire [SMEM_ADDR_WIDTH-1:0] base_word_addr = scatter ? km_word_addr : fb_word_addr_r; wire [SMEM_ADDR_WIDTH-1:0] replay_addr = base_word_addr + beat_offset_r; - // Only the low SMEM_ADDR_WIDTH+SMEM_OFF_W bits of smem_stride are used. - `UNUSED_VAR (smem_stride) - // per_lane_stride_bytes is LMEM-bounded; only the low DXA_SMEM_ADDR_W bits feed fb_byte_addr_r. - // Wide LMEM configurations consume the whole field, leaving no high bits to tag. - if (DXA_SMEM_ADDR_W < 16) begin : g_stride_hi_unused - `UNUSED_VAR (per_lane_stride_bytes[15:DXA_SMEM_ADDR_W]) - end assign smem_wr_valid = mc_write_valid; assign smem_wr_addr = is_multicast ? replay_addr : base_word_addr; @@ -727,11 +544,11 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // it on the request side closes a comb cycle through the downstream // LMEM arbiter. Attr is sampled by the receiver only when req_valid // && req_ready, so qualifying with req_ready here is redundant. - wire smem_wr_attr_last = active_notify_smem_done && ( + wire smem_wr_attr_last = fb_x_r.notify_smem_done && ( is_multicast ? (mc_write_valid && is_last_drain) : smem_wr_last_pkt); wire [BAR_ADDR_W-1:0] smem_wr_attr_bar = is_multicast - ? BAR_ADDR_W'(active_bar_addr + (BAR_ADDR_W'(replay_next_idx) << NB_BITS)) - : active_bar_addr; + ? BAR_ADDR_W'(fb_x_r.bar_addr + (BAR_ADDR_W'(replay_next_idx) << NB_BITS)) + : fb_x_r.bar_addr; // ════════════════════════════════════════════════════════════════════ // SMEM bus wiring @@ -742,48 +559,26 @@ module VX_dxa_smem_wr import VX_gpu_pkg::*, VX_dxa_pkg::*; #( assign smem_bus_if.req_data.data = fb_word_data; assign smem_bus_if.req_data.byteen = fb_word_byteen; assign smem_bus_if.req_data.attr = {smem_wr_attr_last, smem_wr_attr_bar}; - assign smem_bus_if.req_data.tag.uuid = active_uuid; // tag DXA write with its issuing uuid - assign smem_bus_if.req_data.tag.value = SMEM_TAG_VALUE_W'(active_core_id) << ENGINE_VALUE_W; + assign smem_bus_if.req_data.tag.uuid = fb_x_r.uuid; // tag DXA write with its issuing uuid + assign smem_bus_if.req_data.tag.value = SMEM_TAG_VALUE_W'(fb_x_r.core_id) << ENGINE_VALUE_W; assign smem_bus_if.rsp_ready = 1'b0; `UNUSED_VAR (smem_bus_if.rsp_valid) `UNUSED_VAR (smem_bus_if.rsp_data) - // ════════════════════════════════════════════════════════════════════ - // Completion tracking - // ════════════════════════════════════════════════════════════════════ - reg [31:0] wr_count_r; + assign xfer_done = smem_req_fire && smem_wr_last_pkt; + assign xfer_done_idx = fb_xfer_r; - always @(posedge clk) begin - if (reset || transfer_start) begin - wr_count_r <= '0; - end else if (smem_req_fire) begin - wr_count_r <= wr_count_r + 32'd1; - end - end - - assign wr_done_count = wr_count_r; - assign transfer_done = transfer_active && smem_req_fire && smem_wr_last_pkt; - -`ifdef PERF_ENABLE - reg [31:0] wrp_total_lmem_writes_r; - always @(posedge clk) begin - if (reset || transfer_start) begin - wrp_total_lmem_writes_r <= '0; - end else if (smem_req_fire) begin - wrp_total_lmem_writes_r <= wrp_total_lmem_writes_r + 32'd1; - end - end - assign perf_lmem_writes = wrp_total_lmem_writes_r + 32'(smem_req_fire); -`endif + // Each stage reads only the context fields it needs. + `UNUSED_VAR (pend_x) + `UNUSED_VAR (fb_x_r) `ifdef DBG_TRACE_DXA always @(posedge clk) begin if (~reset) begin if (sw_accept) begin - $write("DXA_PIPE,%0d,SW_RX,tag=%0d,oob=%0d,last=%0d,path=%s\n", - $time, sw_tag, sw_oob, sw_last, - sw_defer_path ? "defer" : "pend"); + $write("DXA_PIPE,%0d,SW_RX,tag=%0d,xfer=%0d,oob=%0d\n", + $time, sw_tag, sw_xfer, sw_oob); end if (smem_req_fire) begin $write("DXA_PIPE,%0d,SMEM_WR,addr=0x%0h,byteen=0x%0h,last=%0d\n", diff --git a/hw/rtl/dxa/VX_dxa_worker.sv b/hw/rtl/dxa/VX_dxa_worker.sv index fd8f0d5e25..197b572cef 100644 --- a/hw/rtl/dxa/VX_dxa_worker.sv +++ b/hw/rtl/dxa/VX_dxa_worker.sv @@ -43,17 +43,19 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( localparam SMEM_ADDR_WIDTH = DXA_LMEM_ADDR_W; localparam MAX_OUTSTANDING = `VX_CFG_DXA_MAX_INFLIGHT; + localparam NUM_XFERS = `VX_CFG_DXA_MAX_XFERS; localparam TAG_W = `CLOG2(MAX_OUTSTANDING); localparam SEQ_W = `CLOG2(MAX_OUTSTANDING + 1); + localparam XFER_W = `LOG2UP(NUM_XFERS); // the outstanding-request queue and its tags need a power of two of at least 2 `STATIC_ASSERT (`IS_POW2(MAX_OUTSTANDING) && (MAX_OUTSTANDING >= 2), ("invalid parameter")) + `STATIC_ASSERT (`IS_POW2(NUM_XFERS) && (NUM_XFERS >= 2), ("invalid parameter")) // ════════════════════════════════════════════════════════════════════ // Inter-module wires // ════════════════════════════════════════════════════════════════════ // setup → downstream - wire transfer_active; wire pipeline_start; dxa_setup_params_t setup_params; wire [NC_WIDTH-1:0] active_core_id; @@ -65,6 +67,23 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( wire [`VX_CFG_NUM_WARPS-1:0] active_cta_mask; wire [31:0] active_smem_stride; + // transfer table + wire xfer_avail; + wire [XFER_W-1:0] issue_xfer; + wire [XFER_W-1:0] ctx_pend_raddr; + dxa_xfer_t ctx_pend_rdata; + wire [31:0] ctx_cap_cfill; + wire ctx_cap_scatter; + wire ctx_cap_tiled; + wire [3:0] ctx_cap_lg_tcN; +`ifdef DBG_TRACE_DXA + wire [NC_WIDTH-1:0] trace_done_core_id; + wire [BAR_ADDR_W-1:0] trace_done_bar_addr; +`endif + wire [NUM_XFERS-1:0] xfer_issued; + wire [NUM_XFERS-1:0][SEQ_W-1:0] xfer_pending; + wire xfer_busy; + // addr_gen → gmem_req wire ag_valid; wire ag_ready; @@ -74,40 +93,33 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( wire [GMEM_OFF_BITS:0] ag_valid_length; wire ag_oob; wire ag_last; - wire [31:0] ag_cfill; - wire ag_dest_kmajor; - wire [15:0] ag_per_lane_stride_bytes; - wire [3:0] ag_elem_bytes; - wire [1:0] ag_dest_mode; - wire [3:0] ag_lg_ratio; - wire [3:0] ag_lg_tcN; - wire [3:0] ag_lg_nsteps; - wire [3:0] ag_lg_bkK; wire [15:0] ag_k_row; wire [15:0] ag_n_base; - wire [DXA_SMEM_ADDR_W-1:0] ag_smem_base; + + // the issuing transfer's last line is accepted + wire issue_done = ag_valid && ag_ready && ag_last; // gmem_req → smem_wr (direct-drain channel). wire sw_valid; wire sw_ready; wire [TAG_W-1:0] sw_tag; + wire [XFER_W-1:0] sw_xfer; wire [GMEM_DATAW-1:0] sw_data; wire [DXA_SMEM_ADDR_W-1:0] sw_smem_byte_addr; wire [GMEM_OFF_BITS-1:0] sw_byte_offset; wire [GMEM_OFF_BITS:0] sw_valid_length; wire sw_oob; - wire sw_last; wire [15:0] sw_k_row; wire [15:0] sw_n_base; - wire [SEQ_W-1:0] sw_outstanding; - // smem_wr → gmem_req (release) + // smem_wr → gmem_req / table (release) wire sw_release_en; wire [TAG_W-1:0] sw_release_tag; + wire [XFER_W-1:0] sw_release_xfer; - // smem_wr → setup (completion) - wire transfer_done; - wire [31:0] wr_done_count; + // smem_wr → table (completion) + wire xfer_done; + wire [XFER_W-1:0] xfer_done_idx; wire smem_req_fire; // gmem_req → watchdog @@ -115,9 +127,7 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( wire stall_no_slot; `ifdef PERF_ENABLE - wire [31:0] perf_gmem_reqs; - wire [31:0] perf_gmem_span_cycles; - wire [31:0] perf_lmem_writes; + wire [31:0] perf_xfer_latency; `endif // ════════════════════════════════════════════════════════════════════ @@ -131,8 +141,8 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( .req_ready (req_if.ready), .req_data (req_if.req_data), .desc_data (req_if.desc_data), - .transfer_done (transfer_done), - .transfer_active (transfer_active), + .issue_done (issue_done), + .xfer_avail (xfer_avail), .pipeline_start (pipeline_start), .setup_params (setup_params), .active_core_id (active_core_id), @@ -145,6 +155,54 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( .active_smem_stride (active_smem_stride) ); + // ════════════════════════════════════════════════════════════════════ + // Transfer table: contexts of the transfers in flight + // ════════════════════════════════════════════════════════════════════ + + VX_dxa_xfer_table #( + .NUM_XFERS (NUM_XFERS), + .MAX_OUTSTANDING (MAX_OUTSTANDING) + ) xfer_table ( + .clk (clk), + .reset (reset), + .alloc_ready (xfer_avail), + .alloc_en (pipeline_start), + .alloc_core_id (active_core_id), + .alloc_uuid (active_uuid), + .alloc_bar_addr (active_bar_addr), + .alloc_notify_smem_done (active_notify_smem_done), + .alloc_is_multicast (active_is_multicast), + .alloc_cta_mask (active_cta_mask), + .alloc_smem_stride (active_smem_stride), + .alloc_params (setup_params), + .issue_xfer (issue_xfer), + .issue_en (ag_valid && ag_ready), + .issue_last (ag_last), + .release_en (sw_release_en), + .release_xfer (sw_release_xfer), + .done_en (xfer_done), + .done_xfer (xfer_done_idx), + .pend_raddr (ctx_pend_raddr), + .pend_rdata (ctx_pend_rdata), + .cap_raddr (sw_xfer), + .cap_cfill (ctx_cap_cfill), + .cap_scatter (ctx_cap_scatter), + .cap_tiled (ctx_cap_tiled), + .cap_lg_tcN (ctx_cap_lg_tcN), + .xfer_issued (xfer_issued), + .xfer_pending (xfer_pending), + .busy (xfer_busy) + `ifdef PERF_ENABLE + , + .done_latency (perf_xfer_latency) + `endif + `ifdef DBG_TRACE_DXA + , + .done_core_id (trace_done_core_id), + .done_bar_addr (trace_done_bar_addr) + `endif + ); + // ════════════════════════════════════════════════════════════════════ // Stage 2: Address Generator // ════════════════════════════════════════════════════════════════════ @@ -165,18 +223,8 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( .out_valid_length (ag_valid_length), .out_oob (ag_oob), .out_last (ag_last), - .out_cfill (ag_cfill), - .out_dest_kmajor (ag_dest_kmajor), - .out_per_lane_stride_bytes (ag_per_lane_stride_bytes), - .out_elem_bytes (ag_elem_bytes), - .out_dest_mode (ag_dest_mode), - .out_lg_ratio (ag_lg_ratio), - .out_lg_tcN (ag_lg_tcN), - .out_lg_nsteps (ag_lg_nsteps), - .out_lg_bkK (ag_lg_bkK), .out_k_row (ag_k_row), - .out_n_base (ag_n_base), - .out_smem_base (ag_smem_base) + .out_n_base (ag_n_base) ); // ════════════════════════════════════════════════════════════════════ @@ -187,6 +235,7 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( // gmem_bus_if is already a clean flopped producer boundary here. VX_dxa_gmem_req #( .MAX_OUTSTANDING (MAX_OUTSTANDING), + .NUM_XFERS (NUM_XFERS), .GMEM_ADDR_WIDTH (GMEM_ADDR_WIDTH), .GMEM_TAG_WIDTH (GMEM_TAG_WIDTH), .CL_OFF_BITS (GMEM_OFF_BITS), @@ -194,13 +243,8 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( ) gmem_req ( .clk (clk), .reset (reset), - `ifdef PERF_ENABLE - .perf_gmem_reqs (perf_gmem_reqs), - .perf_gmem_span_cycles(perf_gmem_span_cycles), - `endif - .transfer_active (transfer_active), - .transfer_start (pipeline_start), .active_uuid (active_uuid), + .ag_xfer (issue_xfer), .ag_valid (ag_valid), .ag_ready (ag_ready), .ag_cl_addr (ag_cl_addr), @@ -208,22 +252,20 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( .ag_byte_offset (ag_byte_offset), .ag_valid_length (ag_valid_length), .ag_oob (ag_oob), - .ag_last (ag_last), .ag_k_row (ag_k_row), .ag_n_base (ag_n_base), .gmem_bus_if (gmem_bus_if), .sw_valid (sw_valid), .sw_ready (sw_ready), .sw_tag (sw_tag), + .sw_xfer (sw_xfer), .sw_data (sw_data), .sw_smem_byte_addr (sw_smem_byte_addr), .sw_byte_offset (sw_byte_offset), .sw_valid_length (sw_valid_length), .sw_oob (sw_oob), - .sw_last (sw_last), .sw_k_row (sw_k_row), .sw_n_base (sw_n_base), - .sw_outstanding (sw_outstanding), .release_en (sw_release_en), .release_tag (sw_release_tag), .gmem_req_fire (gmem_req_fire), @@ -231,13 +273,13 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( ); // ════════════════════════════════════════════════════════════════════ - // Stage 4: SMEM Writer (gmem_req drives smem_wr directly via the - // sw_* channel; smem_wr's pend slot + deferred-last register handle - // out-of-order drain). + // Stage 4: SMEM Writer (gmem_req drives smem_wr directly via the sw_* + // channel; each CL reads its transfer's context from the table). // ════════════════════════════════════════════════════════════════════ VX_dxa_smem_wr #( .MAX_OUTSTANDING (MAX_OUTSTANDING), + .NUM_XFERS (NUM_XFERS), .CL_SIZE (GMEM_BYTES), .SMEM_WORD_SIZE (SMEM_BYTES), .SMEM_ADDR_WIDTH (SMEM_ADDR_WIDTH), @@ -245,46 +287,32 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( ) smem_wr ( .clk (clk), .reset (reset), - `ifdef PERF_ENABLE - .perf_lmem_writes (perf_lmem_writes), - `endif - .transfer_active (transfer_active), - .transfer_start (pipeline_start), - .cfill (ag_cfill), - .active_core_id (active_core_id), - .active_uuid (active_uuid), - .active_bar_addr (active_bar_addr), - .active_notify_smem_done (active_notify_smem_done), + .pend_raddr (ctx_pend_raddr), + .pend_rdata (ctx_pend_rdata), + .cap_cfill (ctx_cap_cfill), + .cap_scatter (ctx_cap_scatter), + .cap_tiled (ctx_cap_tiled), + .cap_lg_tcN (ctx_cap_lg_tcN), + .xfer_issued (xfer_issued), + .xfer_pending (xfer_pending), .sw_valid (sw_valid), .sw_ready (sw_ready), .sw_tag (sw_tag), + .sw_xfer (sw_xfer), .sw_data (sw_data), .sw_smem_byte_addr (sw_smem_byte_addr), .sw_byte_offset (sw_byte_offset), .sw_valid_length (sw_valid_length), .sw_oob (sw_oob), - .sw_last (sw_last), .sw_k_row (sw_k_row), .sw_n_base (sw_n_base), - .sw_outstanding (sw_outstanding), .release_en (sw_release_en), .release_tag (sw_release_tag), + .release_xfer (sw_release_xfer), .smem_bus_if (smem_bus_if), - .transfer_done (transfer_done), - .wr_done_count (wr_done_count), - .smem_req_fire (smem_req_fire), - .is_multicast (active_is_multicast), - .cta_mask (active_cta_mask), - .smem_stride (active_smem_stride), - .dest_kmajor (ag_dest_kmajor), - .per_lane_stride_bytes (ag_per_lane_stride_bytes), - .elem_bytes (ag_elem_bytes), - .dest_mode (ag_dest_mode), - .lg_ratio (ag_lg_ratio), - .lg_tcN (ag_lg_tcN), - .lg_nsteps (ag_lg_nsteps), - .lg_bkK (ag_lg_bkK), - .smem_base (ag_smem_base) + .xfer_done (xfer_done), + .xfer_done_idx (xfer_done_idx), + .smem_req_fire (smem_req_fire) ); // ════════════════════════════════════════════════════════════════════ @@ -296,7 +324,7 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( ) watchdog ( .clk (clk), .reset (reset), - .transfer_active (transfer_active), + .transfer_active (xfer_busy), .gmem_req_fire (gmem_req_fire), .gmem_rsp_valid (sw_valid && sw_ready), // any CL delivered to smem_wr .smem_req_fire (smem_req_fire), @@ -312,7 +340,6 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( `ifdef PERF_ENABLE reg [PERF_CTR_BITS-1:0] perf_transfers_r; reg [PERF_CTR_BITS-1:0] perf_gmem_reads_r; - reg [PERF_CTR_BITS-1:0] perf_gmem_dedup_r; reg [PERF_CTR_BITS-1:0] perf_lmem_writes_r; reg [PERF_CTR_BITS-1:0] perf_gmem_lt_r; reg [PERF_CTR_BITS-1:0] perf_noslot_r; @@ -320,7 +347,6 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( if (reset) begin perf_transfers_r <= '0; perf_gmem_reads_r <= '0; - perf_gmem_dedup_r <= '0; perf_lmem_writes_r <= '0; perf_gmem_lt_r <= '0; perf_noslot_r <= '0; @@ -328,56 +354,53 @@ module VX_dxa_worker import VX_gpu_pkg::*, VX_dxa_pkg::*; #( if (stall_no_slot) begin perf_noslot_r <= perf_noslot_r + PERF_CTR_BITS'(1); end - if (transfer_active && transfer_done) begin - perf_transfers_r <= perf_transfers_r + PERF_CTR_BITS'(1); - perf_gmem_reads_r <= perf_gmem_reads_r + PERF_CTR_BITS'(perf_gmem_reqs); - perf_lmem_writes_r <= perf_lmem_writes_r + PERF_CTR_BITS'(perf_lmem_writes); - perf_gmem_lt_r <= perf_gmem_lt_r + PERF_CTR_BITS'(perf_gmem_span_cycles); + if (gmem_req_fire) begin + perf_gmem_reads_r <= perf_gmem_reads_r + PERF_CTR_BITS'(1); + end + if (smem_req_fire) begin + perf_lmem_writes_r <= perf_lmem_writes_r + PERF_CTR_BITS'(1); + end + if (xfer_done) begin + perf_transfers_r <= perf_transfers_r + PERF_CTR_BITS'(1); + perf_gmem_lt_r <= perf_gmem_lt_r + PERF_CTR_BITS'(perf_xfer_latency); end end end assign dxa_perf.transfers = perf_transfers_r; assign dxa_perf.gmem_reads = perf_gmem_reads_r; - assign dxa_perf.gmem_dedup = perf_gmem_dedup_r; + assign dxa_perf.gmem_dedup = '0; assign dxa_perf.lmem_writes = perf_lmem_writes_r; assign dxa_perf.gmem_latency = perf_gmem_lt_r; assign dxa_perf.noslot_stalls = perf_noslot_r; `else `UNUSED_VAR (stall_no_slot) `endif -`ifndef DBG_TRACE_DXA - `UNUSED_VAR (wr_done_count) -`endif `ifdef DBG_TRACE_DXA always @(posedge clk) begin if (~reset) begin if (pipeline_start) begin - `TRACE(1, ("%t: %s setup-done: core=%0d, wid=%0d, bar=%0d\n", - $time, INSTANCE_ID, active_core_id, active_wid, active_bar_addr)) + `TRACE(1, ("%t: %s setup-done: core=%0d, wid=%0d, bar=%0d, xfer=%0d\n", + $time, INSTANCE_ID, active_core_id, active_wid, active_bar_addr, issue_xfer)) $write("DXA_TL,%0d,SETUP_DONE,core=%0d,wid=%0d,bar=%0d\n", $time, active_core_id, active_wid, active_bar_addr); end - if (transfer_active) begin - if (gmem_req_fire) begin - `TRACE(2, ("%t: %s gmem-req-fire\n", $time, INSTANCE_ID)) - end - if (sw_valid && sw_ready) begin - `TRACE(2, ("%t: %s sw-deliver: tag=%0d, oob=%0d, last=%0d\n", - $time, INSTANCE_ID, sw_tag, sw_oob, sw_last)) - end - if (smem_req_fire) begin - `TRACE(2, ("%t: %s smem-wr-fire: count=%0d\n", - $time, INSTANCE_ID, wr_done_count)) - end + if (gmem_req_fire) begin + `TRACE(2, ("%t: %s gmem-req-fire\n", $time, INSTANCE_ID)) + end + if (sw_valid && sw_ready) begin + `TRACE(2, ("%t: %s sw-deliver: tag=%0d, xfer=%0d, oob=%0d\n", + $time, INSTANCE_ID, sw_tag, sw_xfer, sw_oob)) + end + if (smem_req_fire) begin + `TRACE(2, ("%t: %s smem-wr-fire\n", $time, INSTANCE_ID)) end - if (transfer_active && transfer_done) begin - `TRACE(1, ("%t: %s done: core=%0d, wid=%0d, bar=%0d, wr_count=%0d\n", - $time, INSTANCE_ID, active_core_id, active_wid, - active_bar_addr, wr_done_count)) - $write("DXA_TL,%0d,XFER_DONE,core=%0d,wid=%0d,bar=%0d,wr_count=%0d\n", - $time, active_core_id, active_wid, active_bar_addr, - wr_done_count); + if (xfer_done) begin + `TRACE(1, ("%t: %s done: core=%0d, bar=%0d, xfer=%0d\n", + $time, INSTANCE_ID, trace_done_core_id, + trace_done_bar_addr, xfer_done_idx)) + $write("DXA_TL,%0d,XFER_DONE,core=%0d,bar=%0d\n", + $time, trace_done_core_id, trace_done_bar_addr); end end end diff --git a/hw/rtl/dxa/VX_dxa_xfer_table.sv b/hw/rtl/dxa/VX_dxa_xfer_table.sv new file mode 100644 index 0000000000..346123637f --- /dev/null +++ b/hw/rtl/dxa/VX_dxa_xfer_table.sv @@ -0,0 +1,269 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// DXA transfer table: the contexts of the transfers a worker has in flight. +// +// A worker issues one transfer at a time but lets the next one issue while +// earlier ones drain, so the reads of several transfers share the in-flight +// pool. Each line names its transfer; the SMEM writer reads the transfer's +// destination geometry and completion target here. A context is taken when +// its transfer starts issuing and freed when its last write fires. + +`include "VX_define.vh" + +module VX_dxa_xfer_table import VX_gpu_pkg::*, VX_dxa_pkg::*; #( + parameter NUM_XFERS = 2, + parameter MAX_OUTSTANDING = 8, + localparam XFER_W = `LOG2UP(NUM_XFERS), + localparam SEQ_W = `CLOG2(MAX_OUTSTANDING + 1) +) ( + input wire clk, + input wire reset, + + // Allocation: a free context lets setup start the next transfer. + output wire alloc_ready, + input wire alloc_en, + input wire [NC_WIDTH-1:0] alloc_core_id, + input wire [UUID_WIDTH-1:0] alloc_uuid, + input wire [BAR_ADDR_W-1:0] alloc_bar_addr, + input wire alloc_notify_smem_done, + input wire alloc_is_multicast, + input wire [`VX_CFG_NUM_WARPS-1:0] alloc_cta_mask, + input wire [31:0] alloc_smem_stride, + input wire dxa_setup_params_t alloc_params, + + // Issue: the transfer being issued, and its accepted lines. + output wire [XFER_W-1:0] issue_xfer, + input wire issue_en, + input wire issue_last, + + // Drain: a line written, and a transfer completed. + input wire release_en, + input wire [XFER_W-1:0] release_xfer, + input wire done_en, + input wire [XFER_W-1:0] done_xfer, + + // Context reads. The wide read is registered: pend_raddr is the next + // value of the address, and pend_rdata follows it by one cycle. The + // capture read is combinational and returns only the fields a line + // needs as it arrives. + input wire [XFER_W-1:0] pend_raddr, + output dxa_xfer_t pend_rdata, + input wire [XFER_W-1:0] cap_raddr, + output wire [31:0] cap_cfill, + output wire cap_scatter, + output wire cap_tiled, + output wire [3:0] cap_lg_tcN, + output wire [NUM_XFERS-1:0] xfer_issued, + output wire [NUM_XFERS-1:0][SEQ_W-1:0] xfer_pending, + output wire busy + +`ifdef PERF_ENABLE + , + output wire [31:0] done_latency +`endif +`ifdef DBG_TRACE_DXA + , + output wire [NC_WIDTH-1:0] done_core_id, + output wire [BAR_ADDR_W-1:0] done_bar_addr +`endif +); + localparam SMEM_OFF_W = `CLOG2(DXA_LMEM_WORD_SIZE); + + reg [NUM_XFERS-1:0] valid_r; + reg [NUM_XFERS-1:0] issued_r; + reg [NUM_XFERS-1:0][SEQ_W-1:0] pending_r; + reg [XFER_W-1:0] issue_xfer_r; + + wire [XFER_W-1:0] free_idx; + VX_priority_encoder #( + .N (NUM_XFERS) + ) free_pe ( + .data_in (~valid_r), + .index_out (free_idx), + .valid_out (alloc_ready), + `UNUSED_PIN (onehot_out) + ); + + // Derive the drain-side constants once per transfer, so every beat-rate + // cone in the SMEM writer starts at a register. + wire [1:0] dm = alloc_params.dest_mode; + wire tiled = (dm == DXA_DEST_FLAT) || (dm == DXA_DEST_BLOCKMAJOR); + wire is_flat = (dm == DXA_DEST_FLAT); + wire [3:0] esize = (alloc_params.elem_bytes == 4'd8) ? 4'd3 + : (alloc_params.elem_bytes == 4'd4) ? 4'd2 + : (alloc_params.elem_bytes == 4'd2) ? 4'd1 : 4'd0; + wire [3:0] lg_tcN = alloc_params.lg_tcN; + wire [3:0] lg_ratio = alloc_params.lg_ratio; + wire [3:0] lg_bkK = alloc_params.lg_bkK; + + // Incremental tiled addressing: inside an n-block the destination is + // affine in n, so a beat adds one of two per-transfer constants. + // FLAT: step = 1 << (lg_ratio+esize) + // wrap = ((1 << (2*lg_tcN+1)) - (tcN-1)) << (lg_ratio+esize) + // BlockMajor: step = 1 << (lg_bkK+esize) + // wrap = ((1 << lg_tcN) - (tcN-1)) << (lg_bkK+esize) (= step) + wire [15:0] tcn_mask = (16'd1 << lg_tcN) - 16'd1; + wire [4:0] step_sh = is_flat ? (5'(lg_ratio) + 5'(esize)) : (5'(lg_bkK) + 5'(esize)); + wire [DXA_SMEM_ADDR_W-1:0] wrap_elems = is_flat + ? ((DXA_SMEM_ADDR_W'(1) << (5'(lg_tcN) + 5'(lg_tcN) + 5'd1)) - DXA_SMEM_ADDR_W'(tcn_mask)) + : ((DXA_SMEM_ADDR_W'(1) << lg_tcN) - DXA_SMEM_ADDR_W'(tcn_mask)); + + dxa_xfer_t alloc_x; + always @(*) begin + alloc_x.core_id = alloc_core_id; + alloc_x.uuid = alloc_uuid; + alloc_x.bar_addr = alloc_bar_addr; + alloc_x.notify_smem_done = alloc_notify_smem_done; + alloc_x.is_multicast = alloc_is_multicast; + alloc_x.cta_mask = alloc_cta_mask; + alloc_x.stride_words = DXA_LMEM_ADDR_W'(alloc_smem_stride >> SMEM_OFF_W); + alloc_x.cfill = alloc_params.cfill; + alloc_x.scatter = alloc_params.dest_kmajor || tiled; + alloc_x.tiled = tiled; + alloc_x.is_flat = is_flat; + alloc_x.elem_bytes = alloc_params.elem_bytes; + alloc_x.lane_stride = DXA_SMEM_ADDR_W'(alloc_params.per_lane_stride_bytes); + alloc_x.tiled_step = DXA_SMEM_ADDR_W'(1) << step_sh; + alloc_x.tiled_wrap = wrap_elems << step_sh; + alloc_x.tcn_mask = tcn_mask; + alloc_x.lg_tcN = lg_tcN; + alloc_x.lg_ratio = lg_ratio; + alloc_x.lg_bkK = lg_bkK; + alloc_x.lg_nsteps = alloc_params.lg_nsteps; + alloc_x.esize = esize; + // block-index shift of the per-line destination: + // FLAT: 2*lg_tcN+1+lg_ratio+esize BM: lg_tcN+lg_bkK+esize + alloc_x.calc_sh2 = is_flat + ? (5'(lg_tcN) + 5'(lg_tcN) + 5'd1 + 5'(lg_ratio) + 5'(esize)) + : (5'(lg_tcN) + 5'(lg_bkK) + 5'(esize)); + // intra-block term as disjoint k/n bit fields shifted into place: + // FLAT: k[hi] << (lg_tcN+esize) | n_in << (lg_ratio+esize) | k[lo] << esize + // hi = ((2 << lg_tcN) - 1) << lg_ratio, lo = (1 << lg_ratio) - 1 + // BM: n_in << (lg_bkK+esize) | k[lo] << esize, lo = (1 << lg_bkK) - 1 + alloc_x.intra_khi_mask = is_flat ? (((16'd2 << lg_tcN) - 16'd1) << lg_ratio) : 16'd0; + alloc_x.intra_khi_sh = 5'(lg_tcN) + 5'(esize); + alloc_x.intra_n_sh = step_sh; + alloc_x.intra_klo_mask = (16'd1 << (is_flat ? lg_ratio : lg_bkK)) - 16'd1; + alloc_x.smem_base = alloc_params.initial_smem_base; + end + + // The contexts live in RAM: a context is written once, when its transfer + // starts, and is not reallocated while any of its lines is in the writer, + // so a read never races a write to the same entry. + VX_dp_ram #( + .DATAW ($bits(dxa_xfer_t)), + .SIZE (NUM_XFERS), + .OUT_REG (1), + .RDW_MODE ("W") + ) ctx_store ( + .clk (clk), + .reset (reset), + .read (1'b1), + .write (alloc_en), + .wren (1'b1), + .waddr (free_idx), + .wdata (alloc_x), + .raddr (pend_raddr), + .rdata (pend_rdata) + ); + + localparam CAP_W = 32 + 1 + 1 + 4; + + VX_dp_ram #( + .DATAW (CAP_W), + .SIZE (NUM_XFERS), + .OUT_REG (0), + .LUTRAM (1) + ) cap_store ( + .clk (clk), + .reset (reset), + .read (1'b1), + .write (alloc_en), + .wren (1'b1), + .waddr (free_idx), + .wdata ({alloc_x.cfill, alloc_x.scatter, alloc_x.tiled, alloc_x.lg_tcN}), + .raddr (cap_raddr), + .rdata ({cap_cfill, cap_scatter, cap_tiled, cap_lg_tcN}) + ); + +`ifdef DBG_TRACE_DXA + reg [NC_WIDTH-1:0] trace_core_id_r [NUM_XFERS]; + reg [BAR_ADDR_W-1:0] trace_bar_addr_r [NUM_XFERS]; + always @(posedge clk) begin + if (alloc_en) begin + trace_core_id_r[free_idx] <= alloc_core_id; + trace_bar_addr_r[free_idx] <= alloc_bar_addr; + end + end + assign done_core_id = trace_core_id_r[done_xfer]; + assign done_bar_addr = trace_bar_addr_r[done_xfer]; +`endif + + always @(posedge clk) begin + if (reset) begin + valid_r <= '0; + issued_r <= '0; + pending_r <= '0; + issue_xfer_r <= '0; + end else begin + if (alloc_en) begin + issue_xfer_r <= free_idx; + end + for (integer i = 0; i < NUM_XFERS; ++i) begin + if (alloc_en && free_idx == XFER_W'(i)) begin + valid_r[i] <= 1'b1; + issued_r[i] <= 1'b0; + end else begin + if (done_en && done_xfer == XFER_W'(i)) begin + valid_r[i] <= 1'b0; + end + if (issue_en && issue_last && issue_xfer_r == XFER_W'(i)) begin + issued_r[i] <= 1'b1; + end + end + case ({issue_en && (issue_xfer_r == XFER_W'(i)), + release_en && (release_xfer == XFER_W'(i))}) + 2'b10: pending_r[i] <= pending_r[i] + SEQ_W'(1); + 2'b01: pending_r[i] <= pending_r[i] - SEQ_W'(1); + default: ; + endcase + end + end + end + + assign issue_xfer = issue_xfer_r; + assign xfer_issued = issued_r; + assign xfer_pending = pending_r; + assign busy = (| valid_r); + +`ifdef PERF_ENABLE + reg [31:0] cycles_r; + reg [31:0] start_r [NUM_XFERS]; + always @(posedge clk) begin + if (reset) begin + cycles_r <= '0; + end else begin + cycles_r <= cycles_r + 32'd1; + end + if (alloc_en) begin + start_r[free_idx] <= cycles_r; + end + end + assign done_latency = cycles_r - start_r[done_xfer]; +`endif + + `UNUSED_VAR (alloc_smem_stride) + `UNUSED_VAR (alloc_params) + +endmodule diff --git a/hw/rtl/interfaces/VX_tcu_bar_if.sv b/hw/rtl/interfaces/VX_tcu_bar_if.sv new file mode 100644 index 0000000000..06a4fe0523 --- /dev/null +++ b/hw/rtl/interfaces/VX_tcu_bar_if.sv @@ -0,0 +1,37 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +`include "VX_define.vh" + +// TCU -> barrier unit: tc.commit arrivals. +interface VX_tcu_bar_if import VX_gpu_pkg::*; (); + +`ifdef VX_CFG_TCU_TMEM_ENABLE + logic req_valid; + tcu_bar_t req_data; + logic req_ready; + + modport master ( + output req_valid, + output req_data, + input req_ready + ); + + modport slave ( + input req_valid, + input req_data, + output req_ready + ); +`endif + +endinterface diff --git a/hw/rtl/interfaces/VX_tcu_job_if.sv b/hw/rtl/interfaces/VX_tcu_job_if.sv new file mode 100644 index 0000000000..1a68cf8d4b --- /dev/null +++ b/hw/rtl/interfaces/VX_tcu_job_if.sv @@ -0,0 +1,99 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +`include "VX_define.vh" + +// A TCU block <-> the core's tensor memory: the block's TMEM and tc ops and +// their responses, and the tensor-op MMA steps the block's core executes. +interface VX_tcu_job_if (); + +`ifdef VX_CFG_TCU_TMEM_ENABLE + import VX_gpu_pkg::*; + import VX_tcu_pkg::*; + + logic op_valid; + tcu_execute_t op_data; + logic op_ready; + + logic rsp_valid; + tcu_result_t rsp_data; + logic rsp_ready; + + // MMA steps, issued to every block in the same cycle + logic job_valid; + logic job_fire; + tcu_execute_t job_data; + logic core_ready; + + logic jres_valid; + logic [`VX_CFG_NUM_THREADS-1:0][31:0] jres_data; + +`ifdef VX_CFG_TCU_SPARSE_ENABLE + logic [TCU_MAX_META_BLOCK_WIDTH-1:0] job_meta; + logic [TCU_MAX_META_BLOCK_WIDTH-1:0] job_meta_hi; +`endif +`ifdef VX_CFG_TCU_MX_ENABLE + // MX scales of the presented step: TC_M A rows, then TC_N B columns. + logic [TCU_TC_M+TCU_TC_N-1:0][TCU_MX_MAX_SF-1:0][7:0] job_sf; +`endif + + modport block ( + output op_valid, + output op_data, + input op_ready, + input rsp_valid, + input rsp_data, + output rsp_ready, + input job_valid, + input job_fire, + input job_data, + output core_ready, + output jres_valid, + output jres_data + `ifdef VX_CFG_TCU_SPARSE_ENABLE + , + input job_meta, + input job_meta_hi + `endif + `ifdef VX_CFG_TCU_MX_ENABLE + , + input job_sf + `endif + ); + + modport tmem ( + input op_valid, + input op_data, + output op_ready, + output rsp_valid, + output rsp_data, + input rsp_ready, + output job_valid, + output job_fire, + output job_data, + input core_ready, + input jres_valid, + input jres_data + `ifdef VX_CFG_TCU_SPARSE_ENABLE + , + output job_meta, + output job_meta_hi + `endif + `ifdef VX_CFG_TCU_MX_ENABLE + , + output job_sf + `endif + ); +`endif + +endinterface diff --git a/hw/rtl/tcu/VX_tcu_abuf.sv b/hw/rtl/tcu/VX_tcu_abuf.sv index 8eed2496f5..dadc832436 100644 --- a/hw/rtl/tcu/VX_tcu_abuf.sv +++ b/hw/rtl/tcu/VX_tcu_abuf.sv @@ -64,13 +64,21 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( input wire req_valid, input wire req_setup, input wire [3:0] req_step_m, - input wire [3:0] req_step_n, + input wire [TCU_TBUF_N_W-1:0] req_step_n, input wire [3:0] req_step_k, input wire [`VX_CFG_XLEN-1:0] req_desc_a, input wire req_a_is_smem, - input wire req_is_sparse, + input wire req_is_sparse_in, input wire [UUID_WIDTH-1:0] req_uuid, +`ifdef VX_CFG_TCU_TMEM_ENABLE + // One TMEM read of a tensor op's A: K words [a_fill_idx * TC_N, +TC_N) of + // every M row of the block. + input wire a_fill_valid, + input wire [3:0] a_fill_idx, + input wire [TCU_WG_TILE_M-1:0][TCU_TC_N-1:0][31:0] a_fill_data, +`endif + // LMEM bank-parallel read port VX_mem_bus_if.master tcu_lmem_if, @@ -79,6 +87,9 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( output wire [TCU_WG_A_DATA_SIZE-1:0][`VX_CFG_XLEN-1:0] abuf_rs1_data ); `UNUSED_SPARAM (INSTANCE_ID) + + // A full-K sparse tensor-op step's compressed A has the dense shape (fedpK words). + wire req_is_sparse = req_is_sparse_in && (TCU_WG_SP_FULLK == 0); `UNUSED_VAR (req_wid) // ----------------------------------------------------------------------- @@ -92,6 +103,9 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( localparam A_BLOCK_BANK_ROWS = (A_BLOCK_WORDS + NUM_BANKS - 1) / NUM_BANKS; localparam A_BLOCK_BANK_ROWS_SP = (A_BLOCK_WORDS_SP + NUM_BANKS - 1) / NUM_BANKS; localparam BLOCK_WORDS_PADDED = A_BLOCK_BANK_ROWS * NUM_BANKS; +`ifdef VX_CFG_TCU_TMEM_ENABLE + `STATIC_ASSERT (BLOCK_WORDS_PADDED == A_BLOCK_WORDS, ("A from TMEM assumes unpadded A blocks")) +`endif localparam BLOCK_WORDS_PADDED_SP = A_BLOCK_BANK_ROWS_SP * NUM_BANKS; localparam A_STRIPE_BANK_ROWS = TCU_WG_M_STEPS * A_BLOCK_BANK_ROWS; localparam A_STRIPE_BANK_ROWS_SP = TCU_WG_M_STEPS * A_BLOCK_BANK_ROWS_SP; @@ -128,6 +142,13 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // the fetch FSM falls through to the existing path. Latched at alloc_en // alongside fetch_base_r and slot_step_k_r. logic slot_row_major_r; +`ifdef VX_CFG_TCU_TMEM_ENABLE + // Tensor ops take row-major A only. + wire slot_rm = 1'b1; + `UNUSED_VAR (slot_row_major_r) +`else + wire slot_rm = slot_row_major_r; +`endif logic [LDM_W-1:0] slot_ldm_words_r; logic [BANK_ROW_WORDS_LOG2-1:0] slot_desc_a_inrow_r; logic slot_is_sparse_r; @@ -191,9 +212,13 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // k-stripe-transition refills mid-WGMMA would compute the wrong fetch_base. wire [BANK_ADDR_WIDTH-1:0] effective_desc_a_row_base = is_first_compute_uop ? desc_a_row_base : slot_desc_a_row_base_r; +`ifdef VX_CFG_TCU_TMEM_ENABLE + wire effective_row_major = 1'b1; +`else wire [LDM_W-1:0] effective_ldm_words = is_first_compute_uop ? desc_a_ldm_words : slot_ldm_words_r; wire effective_row_major = (effective_ldm_words != '0); +`endif wire [BANK_ROW_WORDS_LOG2-1:0] effective_inrow = is_first_compute_uop ? desc_a_inrow : slot_desc_a_inrow_r; @@ -225,7 +250,7 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // Total fetches differs by mode: // block-major: A_STRIPE_LMEM_ROWS adjacent bank-row reads // row-major: A_TOTAL_ROWS per-row reads (one per logical row) - wire [FETCH_CTR_W-1:0] target_fetches = slot_row_major_r + wire [FETCH_CTR_W-1:0] target_fetches = slot_rm ? FETCH_CTR_W'(A_TOTAL_ROWS) : (slot_is_sparse_r ? FETCH_CTR_W'(A_STRIPE_LMEM_ROWS_SP) : FETCH_CTR_W'(A_STRIPE_LMEM_ROWS)); @@ -258,7 +283,7 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // LMEM master driver assign tcu_lmem_if.req_valid = can_issue; assign tcu_lmem_if.req_data.rw = 1'b0; - assign tcu_lmem_if.req_data.addr = slot_row_major_r + assign tcu_lmem_if.req_data.addr = slot_rm ? row_lmem_addr : (fetch_base_r + BANK_ADDR_WIDTH'(req_ctr_r)); assign tcu_lmem_if.req_data.data = '0; @@ -400,12 +425,23 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire sp_wren = (int'(rsp_ctr_r) == SP_ROW) && (int'(row_lane_rsp) + SP_K < BANK_ROW_WORDS); wire bm_wren = (int'(rsp_ctr_r) == BM_ROW); - assign storage_wren[w] = storage_write - && (slot_row_major_r ? (slot_is_sparse_r ? sp_wren : dn_wren) - : bm_wren); - assign storage_wdata[w] = slot_row_major_r + wire fetch_wren = storage_write + && (slot_rm ? (slot_is_sparse_r ? sp_wren : dn_wren) + : bm_wren); + wire [31:0] fetch_wdata = slot_rm ? (slot_is_sparse_r ? row_src_words[SP_K] : row_src_words[DN_K]) : rsp_words[BM_B]; + `ifdef VX_CFG_TCU_TMEM_ENABLE + // A from TMEM: word (row, k) comes from read k / TC_N, word k % TC_N + // of the row, with fixed wiring. + wire fill_wren = (int'(a_fill_idx) == DN_K / TCU_TC_N); + wire [31:0] fill_wdata = a_fill_data[DN_ROW][DN_K % TCU_TC_N]; + assign storage_wren[w] = a_fill_valid ? fill_wren : fetch_wren; + assign storage_wdata[w] = a_fill_valid ? fill_wdata : fetch_wdata; + `else + assign storage_wren[w] = fetch_wren; + assign storage_wdata[w] = fetch_wdata; + `endif end wire [A_STRIPE_WORDS-1:0][31:0] storage_rdata; @@ -421,7 +457,11 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .clk (clk), .reset (reset), .read (1'b1), + `ifdef VX_CFG_TCU_TMEM_ENABLE + .write (storage_write || a_fill_valid), + `else .write (storage_write), + `endif .wren (storage_wren), .waddr (1'b0), .wdata (storage_wdata), @@ -434,25 +474,31 @@ module VX_tcu_abuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // then expanded into FEDP_K row stride with the unavailable tail lanes zero. // ----------------------------------------------------------------------- + // The stripe holds A_M_BLOCKS M blocks; a lane's word of block m is at a + // fixed index, so the read is an A_M_BLOCKS-way select on step_m (a step + // past the stripe reads zero). + localparam A_M_BLOCKS = (A_STRIPE_WORDS + BLOCK_WORDS_PADDED - 1) / BLOCK_WORDS_PADDED; + localparam A_M_BLOCKS_SP = (A_STRIPE_WORDS + BLOCK_WORDS_PADDED_SP - 1) / BLOCK_WORDS_PADDED_SP; logic [TCU_WG_A_DATA_SIZE-1:0][`VX_CFG_XLEN-1:0] rs1_mux; always_comb begin rs1_mux = '0; for (int lane = 0; lane < TCU_WG_A_DATA_SIZE; ++lane) begin - int src_idx; if (req_is_sparse) begin automatic int row = lane / int'(TCU_WG_FEDP_K); automatic int k = lane % int'(TCU_WG_FEDP_K); if (row < int'(TCU_TC_M) && k < int'(TCU_TC_K)) begin - src_idx = int'(req_step_m) * int'(BLOCK_WORDS_PADDED_SP) - + row * int'(TCU_TC_K) - + k; - if (src_idx < int'(A_STRIPE_WORDS)) - rs1_mux[lane] = `VX_CFG_XLEN'(storage_rdata[src_idx]); + for (int m = 0; m < A_M_BLOCKS_SP; ++m) begin + automatic int src = m * int'(BLOCK_WORDS_PADDED_SP) + row * int'(TCU_TC_K) + k; + if (src < int'(A_STRIPE_WORDS) && int'(req_step_m) == m) + rs1_mux[lane] = `VX_CFG_XLEN'(storage_rdata[src]); + end end end else if (lane < int'(A_BLOCK_WORDS)) begin - src_idx = int'(req_step_m) * int'(BLOCK_WORDS_PADDED) + lane; - if (src_idx < int'(A_STRIPE_WORDS)) - rs1_mux[lane] = `VX_CFG_XLEN'(storage_rdata[src_idx]); + for (int m = 0; m < A_M_BLOCKS; ++m) begin + automatic int src = m * int'(BLOCK_WORDS_PADDED) + lane; + if (src < int'(A_STRIPE_WORDS) && int'(req_step_m) == m) + rs1_mux[lane] = `VX_CFG_XLEN'(storage_rdata[src]); + end end end end diff --git a/hw/rtl/tcu/VX_tcu_bbuf.sv b/hw/rtl/tcu/VX_tcu_bbuf.sv index 9b43879ca6..e45bc19a0d 100644 --- a/hw/rtl/tcu/VX_tcu_bbuf.sv +++ b/hw/rtl/tcu/VX_tcu_bbuf.sv @@ -58,7 +58,7 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( input wire req_is_sparse, input wire [3:0] req_step_m, input wire [3:0] req_step_k, - input wire [3:0] req_step_n, + input wire [TCU_TBUF_N_W-1:0] req_step_n, input wire [1:0] req_cd_nregs, input wire [NCTA_WIDTH-1:0] req_cta_id, input wire [`VX_CFG_XLEN-1:0] req_desc_b, @@ -80,7 +80,9 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( localparam BANK_SEL_BITS = $clog2(NUM_BANKS); localparam WORD_SIZE_LOG2 = $clog2(`VX_CFG_XLEN / 8); localparam B_BLOCK_WORDS = TCU_WG_FEDP_K * TCU_TC_N; - localparam B_BLOCK_WORDS_SP = TCU_TC_K * TCU_TC_N; + // K-major sparse: the two storage slots split at a K-word group boundary, + // which a full-K sparse tensor-op step moves to fedpK words. + localparam B_KMAJ_SPLIT_SP = TCU_WG_SP_K_WORDS * TCU_TC_N; localparam B_BUF_WORDS = NUM_BANKS; // storage per slot // (= 1 logical 32-bit bank-row) localparam LG_B_SUB_BLOCKS = $clog2(TCU_WG_B_SUB_BLOCKS); @@ -113,22 +115,33 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( localparam LG_B_BLOCK_WORDS = $clog2(B_BLOCK_WORDS); localparam KM_CTR_W = $clog2(TCU_TC_N + 1); // 32-bit-word offset width for K-major address arithmetic. - // step_n × TCU_TC_N + j has ≤ 4+4 bits; × ldm_words adds LDM_W. - localparam KM_OFF_W = LDM_W + 4 + 4; + // step_n × TCU_TC_N + j has ≤ N_W+4 bits; × ldm_words adds LDM_W. + localparam KM_OFF_W = LDM_W + TCU_TBUF_N_W + 4; + // Tensor ops reuse slots across descriptors. + localparam bit TMEM_EN = (`VX_CFG_TCU_TMEM_ENABLED != 0); // ----------------------------------------------------------------------- // Block-index compute (variable N_STEPS via cd_nregs). // K_STEPS=2 always; N_STEPS=4/8/16 for cd_nregs=0/1/2 (NRC=8/16/32). // ----------------------------------------------------------------------- - logic [4:0] block_index; + // A tensor op is one K step (step_k = 0) over up to 2^N_W N blocks, so + // its block index is step_n itself. + localparam BI_W = 1 + TCU_TBUF_N_W; + logic [BI_W-1:0] block_index; always_comb begin - case (req_cd_nregs) - 2'd0: block_index = {2'b0, req_step_k[0], req_step_n[1:0]}; // N_STEPS=4 - 2'd1: block_index = {1'b0, req_step_k[0], req_step_n[2:0]}; // N_STEPS=8 - default: block_index = {req_step_k[0], req_step_n[3:0]}; // N_STEPS=16 - endcase + if (TMEM_EN) begin + block_index = BI_W'(req_step_n); + end else begin + case (req_cd_nregs) + 2'd0: block_index = BI_W'({req_step_k[0], req_step_n[1:0]}); // N_STEPS=4 + 2'd1: block_index = BI_W'({req_step_k[0], req_step_n[2:0]}); // N_STEPS=8 + default: block_index = BI_W'({req_step_k[0], req_step_n[3:0]}); // N_STEPS=16 + endcase + end end + `RUNTIME_ASSERT (~(TMEM_EN && req_valid && (req_step_k != 4'd0)), + ("%s tensor-op tile-buffer request with step_k %0d", INSTANCE_ID, req_step_k)) if (4 > 1) begin : g_step_k_upper_unused `UNUSED_VAR (req_step_k[3:1]) end @@ -142,9 +155,7 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // Sparse blocks use the flat producer layout and can span one or two // logical 32-bit bank rows. localparam TOTAL_SHIFT = LG_B_SUB_BLOCKS + LG_XLEN_RATIO; - wire [4:0] dense_offset = (TOTAL_SHIFT == 0) - ? block_index - : 5'(block_index >> TOTAL_SHIFT); + wire [BANK_ADDR_WIDTH-1:0] dense_offset = BANK_ADDR_WIDTH'(block_index >> TOTAL_SHIFT); // Dense within-physical-bank-row selector (XLEN>32 only). Picks which // of the XLEN_RATIO logical 32-bit bank-rows to copy into slot A. @@ -152,9 +163,9 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire [SUB_HALF_W-1:0] dense_sub_half = (LG_XLEN_RATIO == 0) ? '0 - : SUB_HALF_W'(({27'b0, block_index} >> LG_B_SUB_BLOCKS) & ((1 << LG_XLEN_RATIO) - 1)); + : SUB_HALF_W'((32'(block_index) >> LG_B_SUB_BLOCKS) & ((1 << LG_XLEN_RATIO) - 1)); - localparam SP_LOGROW_W = 6; + localparam SP_LOGROW_W = BI_W + 1; wire [SP_LOGROW_W-1:0] sp_logrow_a = SP_LOGROW_W'(block_index) * SP_LOGROW_W'(LOGICAL_ROWS_PER_BLK); wire [SP_LOGROW_W-1:0] sp_logrow_b = sp_logrow_a + SP_LOGROW_W'(1); @@ -186,12 +197,13 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // ----------------------------------------------------------------------- // Resident slots // slot A: holds k_blk=0 bank-row (dense uses this exclusively) - // slot B: holds k_blk=1 bank-row (sparse only) + // slot B: holds k_blk=1 bank-row (sparse) // ----------------------------------------------------------------------- logic slot_a_valid_r; logic [BANK_ADDR_WIDTH-1:0] slot_a_addr_r; logic [BANK_ADDR_WIDTH-1:0] slot_desc_b_row_base_r; + logic [BANK_ROW_WORDS_LOG2-1:0] slot_desc_b_inrow_r; logic slot_fetching_r; // Dense within-physical-bank-row half (XLEN>32 only). logic [SUB_HALF_W-1:0] slot_a_sub_half_r; @@ -205,9 +217,11 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // K-major mode, descriptor and step fields of the block the slot holds, // latched when its fetch is allocated. logic slot_row_major_r; + // Tensor ops take K-major B only. + wire slot_rm = TMEM_EN || slot_row_major_r; logic [LDM_W-1:0] slot_ldm_words_r; logic [3:0] slot_step_k_r; - logic [3:0] slot_step_n_r; + logic [TCU_TBUF_N_W-1:0] slot_step_n_r; logic [NCTA_WIDTH-1:0] slot_cta_id_r; // K-major descriptors can point to storage rewritten between WGMMA instructions. logic refetched_for_first_uop_r; @@ -216,15 +230,15 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( logic [KM_CTR_W-1:0] km_req_ctr_r; logic [KM_CTR_W-1:0] km_rsp_ctr_r; - // Every compute uop carries its WGMMA's descriptor (the WGMMA wrapper - // supplies the setup-latched one after the first uop). The representative - // request can change while a fetch is in flight, so a fetch reads only the - // slot fields latched at its allocation. `UNUSED_VAR (req_step_m) + // K-major slot fields (slot_row_major_r / slot_ldm_words_r / + // slot_step_k_r / slot_step_n_r) are latched at alloc_en — see the + // always_ff below. The K-major addressing arithmetic reads them + // directly. desc_b_ldm_words on the bus is used only for setup. // Per-mode fetch addresses. wire [BANK_ADDR_WIDTH-1:0] fetch_addr_dense = - desc_b_row_base + BANK_ADDR_WIDTH'(dense_offset); + desc_b_row_base + dense_offset; wire [BANK_ADDR_WIDTH-1:0] fetch_addr_a_sparse = desc_b_row_base + BANK_ADDR_WIDTH'(sp_logrow_a >> LG_XLEN_RATIO); wire [BANK_ADDR_WIDTH-1:0] fetch_addr_b_sparse = @@ -233,8 +247,11 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire [BANK_ADDR_WIDTH-1:0] fetch_addr_a = req_is_sparse ? fetch_addr_a_sparse : fetch_addr_dense; + // A K-tile's first step refetches: a tensor op reloads a stage at the + // same address without a setup uop to invalidate the slot. wire bank_row_resident_dense = slot_a_valid_r && !slot_is_sparse_r + && (!TMEM_EN || !req_is_first_uop || refetched_for_first_uop_r) && (slot_a_addr_r == fetch_addr_dense) && (slot_a_sub_half_r == dense_sub_half); @@ -250,16 +267,20 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // the slot pair. For sparse, both slots must be filled because sparse B // is split across the two dense candidate streams. wire bank_row_resident_kmajor = - slot_a_valid_r && slot_row_major_r + slot_a_valid_r && slot_rm && (!slot_is_sparse_r || slot_b_valid_r) && (!req_is_first_uop || refetched_for_first_uop_r) && (slot_cta_id_r == req_cta_id) && (slot_step_k_r == req_step_k) - && (slot_step_n_r == req_step_n); + && (slot_step_n_r == req_step_n) + && (!TMEM_EN || ((slot_desc_b_row_base_r == desc_b_row_base) + && (slot_desc_b_inrow_r == desc_b_inrow) + && (slot_ldm_words_r == desc_b_ldm_words))); // Block-major residency is the existing dense/sparse branch; K-major - // overrides it when the request's descriptor selects K-major. - wire req_wants_kmajor = (desc_b_ldm_words != '0); + // overrides it when the first compute descriptor or latched slot mode + // selects K-major. + wire req_wants_kmajor = TMEM_EN || (desc_b_ldm_words != '0); wire bank_row_resident = req_wants_kmajor ? bank_row_resident_kmajor @@ -284,10 +305,11 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // the values being latched into the slot) and each request/response // accumulates the row stride, keeping the multiplier chain off the LMEM // request-address and response-lane paths. + wire [LDM_W-1:0] km_ldm_words_alloc = desc_b_ldm_words; wire [3:0] km_k_words_alloc = req_is_sparse ? 4'(TCU_TC_K) : 4'(TCU_WG_FEDP_K); wire [KM_OFF_W-1:0] km_word_off_init = - KM_OFF_W'(req_step_n) * KM_OFF_W'(TCU_TC_N) * KM_OFF_W'(desc_b_ldm_words) + KM_OFF_W'(req_step_n) * KM_OFF_W'(TCU_TC_N) * KM_OFF_W'(km_ldm_words_alloc) + KM_OFF_W'(req_step_k) * KM_OFF_W'(km_k_words_alloc) + KM_OFF_W'(desc_b_inrow); @@ -297,8 +319,52 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire [BANK_ADDR_WIDTH-1:0] km_lmem_addr = slot_desc_b_row_base_r + BANK_ADDR_WIDTH'(km_word_off_req_r >> BANK_ROW_WORDS_LOG2); - wire [BANK_ROW_WORDS_LOG2:0] km_lane_rsp = (BANK_ROW_WORDS_LOG2+1)'( - km_word_off_rsp_r & KM_OFF_W'(BANK_ROW_WORDS - 1)); + logic [KM_OFF_W-1:0] km_word_off_row0_r; + wire [KM_OFF_W-1:0] km_row_off [TCU_TC_N]; + logic [TCU_TC_N-1:0] km_row_in_req; + logic [TCU_TC_N-1:0] km_row_in_rsp; + logic [KM_CTR_W-1:0] km_req_ctr_next, km_rsp_ctr_next; + logic [KM_OFF_W-1:0] km_word_off_req_next, km_word_off_rsp_next; + if (TMEM_EN) begin : g_km_merge + // One read serves every remaining row that shares its bank row. + wire [KM_OFF_W-1:0] km_br_req = km_word_off_req_r >> BANK_ROW_WORDS_LOG2; + wire [KM_OFF_W-1:0] km_br_rsp = km_word_off_rsp_r >> BANK_ROW_WORDS_LOG2; + for (genvar jj = 0; jj < TCU_TC_N; ++jj) begin : g_km_rows + assign km_row_off[jj] = km_word_off_row0_r + + KM_OFF_W'(jj) * KM_OFF_W'(slot_ldm_words_r); + assign km_row_in_req[jj] = (KM_CTR_W'(jj) >= km_req_ctr_r) + && ((km_row_off[jj] >> BANK_ROW_WORDS_LOG2) == km_br_req); + assign km_row_in_rsp[jj] = (KM_CTR_W'(jj) >= km_rsp_ctr_r) + && ((km_row_off[jj] >> BANK_ROW_WORDS_LOG2) == km_br_rsp); + end + always_comb begin + km_req_ctr_next = km_req_ctr_r; + km_rsp_ctr_next = km_rsp_ctr_r; + for (int jj = 0; jj < TCU_TC_N; ++jj) begin + if (km_row_in_req[jj]) km_req_ctr_next = km_req_ctr_next + KM_CTR_W'(1); + if (km_row_in_rsp[jj]) km_rsp_ctr_next = km_rsp_ctr_next + KM_CTR_W'(1); + end + km_word_off_req_next = km_word_off_req_r; + km_word_off_rsp_next = km_word_off_rsp_r; + for (int jj = 0; jj < TCU_TC_N; ++jj) begin + if (KM_CTR_W'(jj) == km_req_ctr_next) km_word_off_req_next = km_row_off[jj]; + if (KM_CTR_W'(jj) == km_rsp_ctr_next) km_word_off_rsp_next = km_row_off[jj]; + end + end + end else begin : g_km_single + // One read per row. + for (genvar jj = 0; jj < TCU_TC_N; ++jj) begin : g_km_rows + assign km_row_off[jj] = km_word_off_rsp_r; + assign km_row_in_req[jj] = (km_req_ctr_r == KM_CTR_W'(jj)); + assign km_row_in_rsp[jj] = (km_rsp_ctr_r == KM_CTR_W'(jj)); + end + assign km_req_ctr_next = km_req_ctr_r + KM_CTR_W'(1); + assign km_rsp_ctr_next = km_rsp_ctr_r + KM_CTR_W'(1); + assign km_word_off_req_next = km_word_off_req_r + KM_OFF_W'(slot_ldm_words_r); + assign km_word_off_rsp_next = km_word_off_rsp_r + KM_OFF_W'(slot_ldm_words_r); + `UNUSED_VAR (km_word_off_row0_r) + `UNUSED_VAR (km_row_in_req) + end // Storage offset where this K-major block lands (matches tcu_core's // b_off = (step_n & (B_SUB_BLOCKS-1)) << LG_B_BLOCK_WORDS so the @@ -325,6 +391,24 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( } state_e; state_e fsm_state_r; + // Row merging and descriptor-exact residency (tensor ops) latch the + // block's first row offset and in-row offset with the slot. + if (TMEM_EN) begin : g_km_row0 + always_ff @(posedge clk) begin + if (reset) begin + km_word_off_row0_r <= '0; + slot_desc_b_inrow_r <= '0; + end else if (!req_setup && (fsm_state_r == S_IDLE) && alloc_en) begin + km_word_off_row0_r <= km_word_off_init; + slot_desc_b_inrow_r <= desc_b_inrow; + end + end + end else begin : g_km_row0_off + assign km_word_off_row0_r = '0; + assign slot_desc_b_inrow_r = '0; + end + + wire in_fetch_a = (fsm_state_r == S_FETCH_A); wire in_fetch_b = (fsm_state_r == S_FETCH_B); wire in_fetch = in_fetch_a || in_fetch_b; @@ -334,19 +418,26 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // outstanding). Block-major: original single-fire-per-state behavior // (km_req_ctr_r is reset on alloc; goes 0 → 1 for one block-major fire). wire km_more_to_request = - slot_row_major_r ? (km_req_ctr_r < KM_CTR_W'(TCU_TC_N)) + slot_rm ? (km_req_ctr_r < KM_CTR_W'(TCU_TC_N)) : (km_req_ctr_r == '0); - wire can_issue = in_fetch && !req_inflight_r && km_more_to_request; - wire km_final_rsp = slot_row_major_r + // A tensor op's dense K-major block keeps its row reads in flight together + // (LMEM responses return in order); other fetches keep one outstanding. +`ifdef VX_CFG_TCU_TMEM_ENABLE + wire km_pipelined = slot_rm && !slot_is_sparse_r; +`else + wire km_pipelined = 1'b0; +`endif + wire can_issue = in_fetch && (!req_inflight_r || km_pipelined) && km_more_to_request; + wire km_final_rsp = slot_rm && tcu_lmem_if.rsp_valid - && (km_rsp_ctr_r == KM_CTR_W'(TCU_TC_N - 1)); - wire bm_final_rsp = !slot_row_major_r && tcu_lmem_if.rsp_valid; + && km_row_in_rsp[TCU_TC_N - 1]; + wire bm_final_rsp = !slot_rm && tcu_lmem_if.rsp_valid; wire last_rsp = in_fetch && (km_final_rsp || bm_final_rsp); // Issue address: K-major path uses km_lmem_addr (re-derived per // km_req_ctr_r); block-major path uses the original slot_a/b addr. wire [BANK_ADDR_WIDTH-1:0] active_lmem_addr = - slot_row_major_r ? km_lmem_addr + slot_rm ? km_lmem_addr : (in_fetch_b ? slot_b_addr_r : slot_a_addr_r); assign tcu_lmem_if.req_valid = can_issue; @@ -405,14 +496,14 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( refetched_for_first_uop_r <= 1'b0; // K-major req/rsp counters advance independently of FSM state - // (single-outstanding still enforced via req_inflight_r). - if (slot_row_major_r && tcu_lmem_if.req_valid && tcu_lmem_if.req_ready) begin - km_req_ctr_r <= km_req_ctr_r + KM_CTR_W'(1); - km_word_off_req_r <= km_word_off_req_r + KM_OFF_W'(slot_ldm_words_r); + // (one outstanding via req_inflight_r unless km_pipelined). + if (slot_rm && tcu_lmem_if.req_valid && tcu_lmem_if.req_ready) begin + km_req_ctr_r <= km_req_ctr_next; + km_word_off_req_r <= km_word_off_req_next; end - if (slot_row_major_r && tcu_lmem_if.rsp_valid && !km_final_rsp) begin - km_rsp_ctr_r <= km_rsp_ctr_r + KM_CTR_W'(1); - km_word_off_rsp_r <= km_word_off_rsp_r + KM_OFF_W'(slot_ldm_words_r); + if (slot_rm && tcu_lmem_if.rsp_valid && !km_final_rsp) begin + km_rsp_ctr_r <= km_rsp_ctr_next; + km_word_off_rsp_r <= km_word_off_rsp_next; end case (fsm_state_r) @@ -427,9 +518,6 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( slot_b_addr_r <= fetch_addr_b_sparse; slot_b_sub_half_r <= sp_sub_b; slot_is_sparse_r <= req_is_sparse; - slot_desc_b_row_base_r <= desc_b_row_base; - slot_ldm_words_r <= desc_b_ldm_words; - slot_row_major_r <= req_wants_kmajor; // K-major per-compute slot state for this // (step_k, step_n) block. slot_step_k_r <= req_step_k; @@ -439,6 +527,9 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( km_rsp_ctr_r <= '0; km_word_off_req_r <= km_word_off_init; km_word_off_rsp_r <= km_word_off_init; + slot_desc_b_row_base_r <= desc_b_row_base; + slot_ldm_words_r <= desc_b_ldm_words; + slot_row_major_r <= (desc_b_ldm_words != '0); req_inflight_r <= 1'b0; end end @@ -446,7 +537,7 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( if (last_rsp) begin slot_a_valid_r <= 1'b1; req_inflight_r <= 1'b0; - if (slot_is_sparse_r && slot_row_major_r) begin + if (slot_is_sparse_r && slot_rm) begin slot_b_valid_r <= 1'b1; fsm_state_r <= S_IDLE; slot_fetching_r <= 1'b0; @@ -488,15 +579,50 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // dense B blocks and stores them in the compact rs2 order. // ----------------------------------------------------------------------- + wire [B_BUF_WORDS-1:0][31:0] storage_a_rdata, storage_b_rdata; logic [B_BUF_WORDS*32-1:0] storage_a_wdata, storage_b_wdata; logic [B_BUF_WORDS-1:0] storage_a_wren, storage_b_wren; - // Per-slot logical-row offsets within a physical LMEM response. - localparam OFF_W = $clog2(NUM_BANKS * XLEN_RATIO) + 1; - wire [OFF_W-1:0] a_off_words = OFF_W'(slot_a_sub_half_r) * OFF_W'(NUM_BANKS); - wire [OFF_W-1:0] b_off_words = OFF_W'(slot_b_sub_half_r) * OFF_W'(NUM_BANKS); + // The logical 32-bit bank row a slot copies: an XLEN_RATIO-way select of + // the response (a plain wire at XLEN=32). + wire [XLEN_RATIO-1:0][NUM_BANKS-1:0][31:0] rsp_halves = tcu_lmem_if.rsp_data.data; + wire [NUM_BANKS-1:0][31:0] rsp_half_a, rsp_half_b; + if (XLEN_RATIO > 1) begin : g_halves + assign rsp_half_a = rsp_halves[slot_a_sub_half_r]; + assign rsp_half_b = rsp_halves[slot_b_sub_half_r]; + end else begin : g_half + assign rsp_half_a = rsp_halves[0]; + assign rsp_half_b = rsp_halves[0]; + `UNUSED_VAR ({slot_a_sub_half_r, slot_b_sub_half_r}) + end wire sparse_b_from_a = SPARSE_TWO_SLOT && !SPARSE_TWO_FETCH - && slot_is_sparse_r && !slot_row_major_r; + && slot_is_sparse_r && !slot_rm; + + // K-major rows: one shifter per row a response carries (KM_NROT), + // rot[r][x] = response word (row r's lane) + x, shared by the dense + // (x < fedpK) and sparse (x < 2*SP_K_WORDS) writes. Without row merging a + // response carries one row. + localparam KM_ROT_SP = `VX_CFG_TCU_SPARSE_ENABLED ? (2 * TCU_WG_SP_K_WORDS) : 0; + localparam KM_ROT = (KM_ROT_SP > TCU_WG_FEDP_K) ? KM_ROT_SP : TCU_WG_FEDP_K; + localparam KM_NROT = TMEM_EN ? TCU_TC_N : 1; + logic [KM_NROT-1:0][KM_ROT-1:0][31:0] km_rot; + logic [KM_NROT-1:0][KM_ROT-1:0] km_rot_ok; + wire [KM_NROT-1:0][BANK_ROW_WORDS_LOG2:0] km_lane; + for (genvar jj = 0; jj < KM_NROT; ++jj) begin : g_km_lane + assign km_lane[jj] = (BANK_ROW_WORDS_LOG2+1)'(km_row_off[jj] & KM_OFF_W'(BANK_ROW_WORDS - 1)); + end + always_comb begin + for (int jj = 0; jj < KM_NROT; ++jj) begin + for (int x = 0; x < KM_ROT; ++x) begin + km_rot_ok[jj][x] = (int'(km_lane[jj]) + x < BANK_ROW_WORDS); + km_rot[jj][x] = '0; + for (int i = x; i < BANK_ROW_WORDS; ++i) begin + if (int'(km_lane[jj]) == i - x) + km_rot[jj][x] = tcu_lmem_if.rsp_data.data[i * 32 +: 32]; + end + end + end + end always_comb begin storage_a_wdata = '0; @@ -504,75 +630,62 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( storage_b_wdata = '0; storage_b_wren = '0; if (tcu_lmem_if.rsp_valid) begin - if (slot_row_major_r && slot_is_sparse_r) begin - // K-major sparse: per N-row r (= km_rsp_ctr_r = column j) the - // response carries this column's K dimension z-major with the - // two sparse candidates adjacent — word (z*2 + cand) holds the - // FEDP's bword{cand} for K-step z. - // The FEDP reads rs2[k_idx*(TC_N*2) + j*2 + cand] with k_idx=z; - // slot_a||slot_b splits at B_BLOCK_WORDS_SP (= TC_K*TC_N). - // Drive each (z,cand) word to its exact flat target and route by slot. - for (int z = 0; z < TCU_TC_K; ++z) begin - for (int c = 0; c < 2; ++c) begin - automatic int src = int'(km_lane_rsp) + z * 2 + c; - automatic int tgt = z * (TCU_TC_N * 2) + int'(km_rsp_ctr_r) * 2 + c; - if (src < (NUM_BANKS * XLEN_RATIO) && in_fetch_a) begin - if (tgt < int'(B_BLOCK_WORDS_SP)) begin - if (tgt < B_BUF_WORDS) begin - storage_a_wren[tgt] = 1'b1; - storage_a_wdata[tgt * 32 +: 32] = - tcu_lmem_if.rsp_data.data[src * 32 +: 32]; - end - end else begin - automatic int tgt_b = tgt - int'(B_BLOCK_WORDS_SP); - if (tgt_b < B_BUF_WORDS) begin - storage_b_wren[tgt_b] = 1'b1; - storage_b_wdata[tgt_b * 32 +: 32] = - tcu_lmem_if.rsp_data.data[src * 32 +: 32]; - end - end + if (slot_rm && slot_is_sparse_r) begin + // K-major sparse: row jj's K dimension is z-major with the two + // candidates adjacent, word (z*2 + cand) from its lane. Flat + // target z*(TC_N*2) + jj*2 + cand splits across slot A || slot B + // at B_KMAJ_SPLIT_SP. Each storage word has one (z, jj, cand): + // its data is a fixed shifter output, its enable the row's. + for (int w = 0; w < 2 * B_BUF_WORDS; ++w) begin + if (w < 2 * int'(B_KMAJ_SPLIT_SP)) begin + automatic int z = w / (TCU_TC_N * 2); + automatic int jj = (w % (TCU_TC_N * 2)) / 2; + automatic int x = z * 2 + (w % 2); + automatic bit en = in_fetch_a && km_row_in_rsp[jj] && km_rot_ok[jj % KM_NROT][x]; + if (w < int'(B_KMAJ_SPLIT_SP)) begin + storage_a_wren[w] = en; + storage_a_wdata[w * 32 +: 32] = km_rot[jj % KM_NROT][x]; + end else begin + automatic int wb = w - int'(B_KMAJ_SPLIT_SP); + storage_b_wren[wb] = en; + storage_b_wdata[wb * 32 +: 32] = km_rot[jj % KM_NROT][x]; end end end - end else if (slot_row_major_r) begin - // K-major dense: write fedpK words for this row (km_rsp_ctr_r) - // into storage[km_b_off + km_rsp_ctr_r * fedpK .. + fedpK), - // sourced from the response at lane km_lane_rsp. - for (int k = 0; k < TCU_WG_FEDP_K; ++k) begin - automatic int dst = int'(km_b_off) - + int'(km_rsp_ctr_r) * TCU_WG_FEDP_K - + k; - automatic int src = int'(km_lane_rsp) + k; - if (dst < B_BUF_WORDS && src < (NUM_BANKS * XLEN_RATIO) && in_fetch_a) begin - storage_a_wren[dst] = 1'b1; - storage_a_wdata[dst * 32 +: 32] = - tcu_lmem_if.rsp_data.data[src * 32 +: 32]; - end + end else if (slot_rm) begin + // K-major dense: row jj's fedpK words land at + // km_b_off + jj*fedpK + k; storage word w is (sub-block, jj, k). + for (int w = 0; w < B_BUF_WORDS; ++w) begin + automatic int sb = w / B_BLOCK_WORDS; + automatic int jj = (w % B_BLOCK_WORDS) / TCU_WG_FEDP_K; + automatic int k = w % TCU_WG_FEDP_K; + storage_a_wren[w] = in_fetch_a && km_rot_ok[jj % KM_NROT][k] + && (int'(km_b_off) == sb * B_BLOCK_WORDS) + && km_row_in_rsp[jj]; + storage_a_wdata[w * 32 +: 32] = km_rot[jj % KM_NROT][k]; end end else begin for (int b = 0; b < B_BUF_WORDS; ++b) begin if (in_fetch_a) begin storage_a_wren[b] = 1'b1; storage_a_wdata[b * 32 +: 32] = - tcu_lmem_if.rsp_data.data[(int'(a_off_words) + b) * 32 +: 32]; + rsp_half_a[b]; if (sparse_b_from_a) begin storage_b_wren[b] = 1'b1; storage_b_wdata[b * 32 +: 32] = - tcu_lmem_if.rsp_data.data[(int'(b_off_words) + b) * 32 +: 32]; + rsp_half_b[b]; end end if (in_fetch_b) begin storage_b_wren[b] = 1'b1; storage_b_wdata[b * 32 +: 32] = - tcu_lmem_if.rsp_data.data[(int'(b_off_words) + b) * 32 +: 32]; + rsp_half_b[b]; end end end end end - wire [B_BUF_WORDS-1:0][31:0] storage_a_rdata, storage_b_rdata; - VX_dp_ram #( .DATAW (B_BUF_WORDS * 32), .SIZE (1), @@ -605,7 +718,7 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .read (1'b1), .write ((in_fetch_b && tcu_lmem_if.rsp_valid) || (in_fetch_a && tcu_lmem_if.rsp_valid && slot_is_sparse_r - && (slot_row_major_r || sparse_b_from_a))), + && (slot_rm || sparse_b_from_a))), .wren (storage_b_wren), .waddr (1'b0), .wdata (storage_b_wdata), @@ -626,12 +739,12 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( rs2_mux = '0; for (int lane = 0; lane < TCU_WG_RS2_WIDTH; ++lane) begin if (slot_is_sparse_r) begin - if (slot_row_major_r) begin - if (lane < int'(B_BLOCK_WORDS_SP)) begin + if (slot_rm) begin + if (lane < int'(B_KMAJ_SPLIT_SP)) begin rs2_mux[lane] = `VX_CFG_XLEN'(storage_a_rdata[lane]); - end else if (lane < int'(2 * B_BLOCK_WORDS_SP)) begin + end else if (lane < int'(2 * B_KMAJ_SPLIT_SP)) begin rs2_mux[lane] = `VX_CFG_XLEN'( - storage_b_rdata[lane - int'(B_BLOCK_WORDS_SP)]); + storage_b_rdata[lane - int'(B_KMAJ_SPLIT_SP)]); end end else begin automatic int unsigned k_idx_l = lane / (TCU_TC_N * 2); @@ -654,6 +767,24 @@ module VX_tcu_bbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( end assign bbuf_rs2_data = rs2_mux; + `STATIC_ASSERT (B_KMAJ_SPLIT_SP <= B_BUF_WORDS, + ("K-major sparse candidate lanes exceed the two B storage slots")) +`ifndef SYNTHESIS + logic km_sp_row_spill; + always_comb begin + km_sp_row_spill = 1'b0; + for (int jj = 0; jj < TCU_TC_N; ++jj) begin + if (tcu_lmem_if.rsp_valid && in_fetch_a && slot_rm && slot_is_sparse_r + && km_row_in_rsp[jj] + && (int'(32'(km_row_off[jj] & KM_OFF_W'(BANK_ROW_WORDS - 1))) + 2 * TCU_WG_SP_K_WORDS + > (NUM_BANKS * XLEN_RATIO))) + km_sp_row_spill = 1'b1; + end + end + `RUNTIME_ASSERT (~km_sp_row_spill, + ("%s K-major sparse B row straddles an LMEM bank row (misaligned descriptor)", INSTANCE_ID)) +`endif + // ----------------------------------------------------------------------- // Performance counters // ----------------------------------------------------------------------- diff --git a/hw/rtl/tcu/VX_tcu_block.sv b/hw/rtl/tcu/VX_tcu_block.sv index 09874fb555..813b42cb8d 100644 --- a/hw/rtl/tcu/VX_tcu_block.sv +++ b/hw/rtl/tcu/VX_tcu_block.sv @@ -40,6 +40,10 @@ module VX_tcu_block import VX_gpu_pkg::*, VX_tcu_pkg::*; #( VX_lsu_sched_if.master tcu_mem_if, `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_job_if.block job_if, +`endif + VX_execute_if.slave execute_if, VX_result_if.master result_if ); @@ -83,20 +87,146 @@ module VX_tcu_block import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .result_ready (agu_result_ready) ); - // TCU_LD goes to the AGU, every MMA op to the core - wire is_tcu_ld = (execute_if.data.op_type == INST_TCU_LD); +`endif - assign agu_ld_valid = execute_if.valid && is_tcu_ld; - assign core_execute_if.valid = execute_if.valid && !is_tcu_ld; + // TCU_LD goes to the AGU, TMEM and tc ops to the tensor memory, every MMA + // op to the core. + wire [INST_OP_BITS-1:0] op_type = execute_if.data.op_type; + `UNUSED_VAR (op_type) +`ifdef TCU_META_ENABLE + wire is_tcu_ld = (op_type == INST_TCU_LD); +`else + wire is_tcu_ld = 1'b0; +`endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + wire is_tj_op = (op_type == INST_OP_BITS'(INST_TCU_TMEM_LD)) + || (op_type == INST_OP_BITS'(INST_TCU_TMEM_ST)) + || (op_type == INST_OP_BITS'(INST_TCU_TC_CP)) + || (op_type == INST_OP_BITS'(INST_TCU_TMEM_ALLOC)) + || (op_type == INST_OP_BITS'(INST_TCU_TMEM_DEALLOC)) + || (op_type == INST_OP_BITS'(INST_TCU_TC_MMA)) + || (op_type == INST_OP_BITS'(INST_TCU_TC_COMMIT)); +`else + wire is_tj_op = 1'b0; +`endif +`ifdef VX_CFG_TCU_WMMA_ENABLE + wire warp_core_valid = execute_if.valid && !is_tcu_ld && !is_tj_op; +`else + wire warp_core_valid = 1'b0; +`endif + +`ifdef VX_CFG_TCU_TMEM_ENABLE + // Tensor-op MMA steps take the core ahead of warp MMAs. + assign job_if.op_valid = execute_if.valid && is_tj_op; + assign job_if.op_data = execute_if.data; + assign core_execute_if.valid = job_if.job_valid ? job_if.job_fire : warp_core_valid; + // A step's A and B come from the tile buffers, so only the header, op + // fields and C (rs3) switch to the step; rs1/rs2 stay the warp's. +`ifdef VX_CFG_TCU_WMMA_ENABLE + wire step = job_if.job_valid; +`else + wire step = 1'b1; +`endif + assign core_execute_if.data = {step ? job_if.job_data.header : execute_if.data.header, + step ? job_if.job_data.op_type : execute_if.data.op_type, + step ? job_if.job_data.op_args : execute_if.data.op_args, + execute_if.data.rs1_data, + execute_if.data.rs2_data, + step ? job_if.job_data.rs3_data : execute_if.data.rs3_data}; + `UNUSED_VAR ({job_if.job_data.rs1_data, job_if.job_data.rs2_data}) + assign job_if.core_ready = core_execute_if.ready; + wire warp_core_ready = core_execute_if.ready && !job_if.job_valid; + wire tj_ready = job_if.op_ready; + `RUNTIME_ASSERT (~(warp_core_valid && (op_type == INST_OP_BITS'(INST_TCU_WGMMA) + `ifdef VX_CFG_TCU_SPARSE_ENABLE + || op_type == INST_OP_BITS'(INST_TCU_WGMMA_SP) + `endif + )), ("%t: %s: WGMMA is not supported with tensor memory", $time, INSTANCE_ID)) +`else + assign core_execute_if.valid = warp_core_valid; assign core_execute_if.data = execute_if.data; - assign execute_if.ready = is_tcu_ld ? agu_ld_ready : core_execute_if.ready; + wire warp_core_ready = core_execute_if.ready; + wire tj_ready = 1'b0; +`endif +`ifdef TCU_META_ENABLE + assign agu_ld_valid = execute_if.valid && is_tcu_ld; + wire agu_ready = agu_ld_ready; +`else + wire agu_ready = 1'b0; +`endif + assign execute_if.ready = is_tcu_ld ? agu_ready + : is_tj_op ? tj_ready + : warp_core_ready; - // AGU wins same-cycle conflicts; the core stalls and retries next cycle. - assign result_if.valid = agu_result_valid || core_result_if.valid; - assign result_if.data = agu_result_valid ? agu_result_data : core_result_if.data; - assign agu_result_ready = result_if.ready; - assign core_result_if.ready = result_if.ready && !agu_result_valid; + // Results: the AGU, then the tensor memory, then the core. A tensor-op + // MMA step's result goes back to the tensor memory, in issue order. +`ifdef TCU_META_ENABLE + wire a_valid = agu_result_valid; + tcu_result_t a_data; + assign a_data = agu_result_data; + assign agu_result_ready = result_if.ready; +`else + wire a_valid = 1'b0; + tcu_result_t a_data; + assign a_data = 'x; +`endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + wire t_valid = job_if.rsp_valid; + tcu_result_t t_data; + assign t_data = job_if.rsp_data; + assign job_if.rsp_ready = result_if.ready && !a_valid; + +`ifdef VX_CFG_TCU_WMMA_ENABLE + wire is_job_head, order_empty, order_full; + wire core_in_fire = core_execute_if.valid && core_execute_if.ready; + wire core_out_fire = core_result_if.valid && core_result_if.ready; + VX_fifo_queue #( + .DATAW (1), + .DEPTH (32), + .LUTRAM (1) + ) order_q ( + .clk (clk), + .reset (reset), + .push (core_in_fire), + .pop (core_out_fire), + .data_in (job_if.job_valid), + .data_out(is_job_head), + .empty (order_empty), + `UNUSED_PIN (alm_empty), + .full (order_full), + `UNUSED_PIN (alm_full), + `UNUSED_PIN (size) + ); + `UNUSED_VAR (order_empty) + `RUNTIME_ASSERT (~(core_in_fire && order_full), ("%t: %s: tcu order queue overflow", $time, INSTANCE_ID)) + assign job_if.jres_valid = core_result_if.valid && is_job_head; + for (genvar t = 0; t < `VX_CFG_NUM_THREADS; ++t) begin : g_jres + assign job_if.jres_data[t] = core_result_if.data.data[t][31:0]; + end + wire c_valid = core_result_if.valid && !is_job_head; + assign core_result_if.ready = is_job_head || (result_if.ready && !a_valid && !t_valid); +`else + // Every core result is a tensor-op step's, written back to tensor memory. + assign job_if.jres_valid = core_result_if.valid; + for (genvar t = 0; t < `VX_CFG_NUM_THREADS; ++t) begin : g_jres + assign job_if.jres_data[t] = core_result_if.data.data[t][31:0]; + end + wire c_valid = 1'b0; + assign core_result_if.ready = 1'b1; +`endif +`else + wire t_valid = 1'b0; + tcu_result_t t_data; + assign t_data = 'x; + wire c_valid = core_result_if.valid; + assign core_result_if.ready = result_if.ready && !a_valid; +`endif + assign result_if.valid = a_valid || t_valid || c_valid; + assign result_if.data = a_valid ? a_data + : t_valid ? t_data + : core_result_if.data; +`ifdef TCU_META_ENABLE // A TCU_LD writes its response fragments straight into the metadata RAM, // which an MMA reads while it is presented to the core. That is safe only // if no MMA of the loading warp that reads the region being loaded is @@ -117,22 +247,20 @@ module VX_tcu_block import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire mma_reads_mx = tcu_fmt_is_mx(execute_if.data.op_args.tcu.fmt_s); `else wire mma_reads_mx = 1'b0; +`endif + // the warp's own MMA is presented (not a tensor-op step) +`ifdef VX_CFG_TCU_TMEM_ENABLE + wire warp_mma_presented = warp_core_valid && !job_if.job_valid; +`else + wire warp_mma_presented = warp_core_valid; `endif // ~ld_ready: the AGU holds a TCU_LD, so its wid and slot are registered wire mma_reads_ld_region = meta_wr_idx[4] ? mma_reads_mx : mma_reads_sp; - `RUNTIME_ASSERT(~(core_execute_if.valid && ~agu_ld_ready + `RUNTIME_ASSERT(~(warp_mma_presented && ~agu_ld_ready && (execute_if.data.header.wid == meta_wr_wid) && mma_reads_ld_region), ("%t: *** %s MMA reads metadata a TCU_LD is loading: wid=%0d, slot=%0d, op_type=%0d (#%0d)", $time, INSTANCE_ID, meta_wr_wid, meta_wr_idx, execute_if.data.op_type, execute_if.data.header.uuid)) `endif -`else - assign core_execute_if.valid = execute_if.valid; - assign core_execute_if.data = execute_if.data; - assign execute_if.ready = core_execute_if.ready; - - assign result_if.valid = core_result_if.valid; - assign result_if.data = core_result_if.data; - assign core_result_if.ready = result_if.ready; `endif `ifdef VX_CFG_TCU_WGMMA_ENABLE @@ -162,6 +290,15 @@ module VX_tcu_block import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .ext_meta_wr_idx (meta_wr_idx), .ext_meta_wr_mask (meta_wr_mask), .ext_meta_wr_data (meta_wr_data), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + `ifdef VX_CFG_TCU_SPARSE_ENABLE + .job_meta (job_if.job_meta), + .job_meta_hi (job_if.job_meta_hi), + `endif + `ifdef VX_CFG_TCU_MX_ENABLE + .job_sf (job_if.job_sf), + `endif `endif .execute_if (core_execute_if), .result_if (core_result_if) diff --git a/hw/rtl/tcu/VX_tcu_core.sv b/hw/rtl/tcu/VX_tcu_core.sv index 7256ccdf4f..2f2bcf4215 100644 --- a/hw/rtl/tcu/VX_tcu_core.sv +++ b/hw/rtl/tcu/VX_tcu_core.sv @@ -36,6 +36,18 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( input wire [TCU_BLOCK_CAP-1:0][31:0] ext_meta_wr_data, `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE +`ifdef VX_CFG_TCU_SPARSE_ENABLE + // A tensor job's K-tile metadata; warps do not issue WGMMA_SP with TMEM. + input wire [TCU_MAX_META_BLOCK_WIDTH-1:0] job_meta, + input wire [TCU_MAX_META_BLOCK_WIDTH-1:0] job_meta_hi, +`endif +`ifdef VX_CFG_TCU_MX_ENABLE + // A tensor job's MX scales: TC_M A rows, then TC_N B columns. + input wire [TCU_TC_M+TCU_TC_N-1:0][TCU_MX_MAX_SF-1:0][7:0] job_sf, +`endif +`endif + // Inputs VX_execute_if.slave execute_if, @@ -51,6 +63,8 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // FEDP dot-product width in 32-bit words (doubles under FEDP2K). localparam FEDP_K = TCU_WG_FEDP_K; + `STATIC_ASSERT (TCU_WG_SP_FULLK == 0 || TCU_WG_FEDP_K == 2 * TCU_TC_K, + ("a full-K sparse tensor-op step requires VX_CFG_TCU_FEDP2K")) // Total FEDP latency of the configured TCU type; each FEDP variant // asserts it against its internal stage structure. @@ -131,12 +145,24 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( `endif `ifdef VX_CFG_TCU_WGMMA_ENABLE +`ifdef VX_CFG_TCU_WMMA_ENABLE wire is_wgmma = (execute_if.data.op_type == INST_TCU_WGMMA) `ifdef VX_CFG_TCU_SPARSE_ENABLE || (execute_if.data.op_type == INST_TCU_WGMMA_SP) `endif ; +`else + // Without per-warp MMAs every op is a tensor op's step. + wire is_wgmma = 1'b1; +`endif +`ifdef TCU_WARP_WGMMA wire wg_a_smem = execute_if.data.op_args.tcu.a_from_smem; +`else + // A tensor job's step reads A from the tile buffer (shared memory or TMEM). + wire wg_a_smem = 1'b1; + `RUNTIME_ASSERT (~execute_if.valid || ~is_wgmma || execute_if.data.op_args.tcu.a_from_smem, + ("%t: *** %s WGMMA step with A from registers in a TMEM build", $time, INSTANCE_ID)) +`endif // A/B operand mux: tile buffer (smem) or register file. The // RF-side rs2_data is NUM_THREADS lanes wide; the WGMMA bbuf can be @@ -151,7 +177,13 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( `ifdef VX_CFG_TCU_SPARSE_ENABLE // Sparse metadata lives in VX_tcu_sp_meta SRAM, preloaded via TCU_LD. - wire [TCU_MAX_META_BLOCK_WIDTH-1:0] vld_meta_block = wmma_sp_meta; + `ifdef VX_CFG_TCU_TMEM_ENABLE + wire [TCU_MAX_META_BLOCK_WIDTH-1:0] vld_meta_block = is_wgmma ? job_meta : wmma_sp_meta; + wire [TCU_MAX_META_BLOCK_WIDTH-1:0] vld_meta_block_hi = job_meta_hi; + `else + wire [TCU_MAX_META_BLOCK_WIDTH-1:0] vld_meta_block = wmma_sp_meta; + wire [TCU_MAX_META_BLOCK_WIDTH-1:0] vld_meta_block_hi = '0; + `endif `endif assign exe_ready_extra = ~is_wgmma || tbuf_ready; @@ -159,7 +191,8 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( assign rs1_data = execute_if.data.rs1_data; assign rs2_data = execute_if.data.rs2_data; `ifdef VX_CFG_TCU_SPARSE_ENABLE - wire [TCU_MAX_META_BLOCK_WIDTH-1:0] vld_meta_block = wmma_sp_meta; + wire [TCU_MAX_META_BLOCK_WIDTH-1:0] vld_meta_block = wmma_sp_meta; + wire [TCU_MAX_META_BLOCK_WIDTH-1:0] vld_meta_block_hi = '0; `endif assign exe_ready_extra = 1'b1; `endif @@ -172,7 +205,7 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire [4:0] fmt_d = execute_if.data.op_args.tcu.fmt_d; wire execute_fire = execute_if.valid && execute_if.ready; -`ifdef VX_CFG_TCU_WGMMA_ENABLE +`ifdef TCU_WARP_WGMMA wire is_wgmma_setup = is_wgmma && !execute_if.data.header.wb; `else wire is_wgmma_setup = 1'b0; @@ -222,9 +255,11 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // in the result landing queue, so a completing result always has a place // to land and no per-register enable network spans the grid. +`ifdef VX_CFG_TCU_WMMA_ENABLE // Landing capacity matches the header FIFO: credits bound the results // outstanding, so both queues share one occupancy invariant. localparam LANDQ_SIZE = MDATA_QUEUE_DEPTH; +`endif wire mdata_queue_full; @@ -266,6 +301,7 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire fedp_done = fedp_delay_pipe[0]; wire landq_credits_full; +`ifdef VX_CFG_TCU_WMMA_ENABLE VX_pending_size #( .SIZE (LANDQ_SIZE) ) landq_credits ( @@ -279,6 +315,10 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( `UNUSED_PIN (alm_full), `UNUSED_PIN (size) ); +`else + // Tensor memory takes every result as it completes: nothing lands. + assign landq_credits_full = 1'b0; +`endif // Admission stalls while a completed result waits on the consumer: this // keeps the landing queue shallow so a chained MMA never sees queueing @@ -361,6 +401,14 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( , .meta_b (mx_meta_b) `endif ); +`else +`ifdef VX_CFG_TCU_SPARSE_ENABLE + assign wmma_sp_meta = '0; +`endif +`ifdef VX_CFG_TCU_MX_ENABLE + assign mx_meta_a = '0; + assign mx_meta_b = '0; +`endif `endif `ifdef VX_CFG_TCU_MX_ENABLE @@ -394,7 +442,8 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( logic [`LOG2UP(TCU_BLOCK_CAP)-1:0] word_idx; logic [1:0] byte_idx; begin - scale_k = MX_SCALE_IDX_W'(k_base_idx / mx_scale_block_size(fmt)); + // Block sizes are 1, 16 or 32 elements: a shift, not a divider. + scale_k = MX_SCALE_IDX_W'(k_base_idx >> mx_scale_block_lg2(fmt)); scale_row = scale_blocks_k_nz ? (MX_SCALE_IDX_W'(mn_idx) << scale_blocks_k_lg2) : '0; scale_idx = scale_row + scale_k; word_idx = `LOG2UP(TCU_BLOCK_CAP)'(scale_idx >> 2); @@ -405,17 +454,40 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire [TCU_TC_M-1:0][FEDP_SF-1:0][7:0] mx_sf_a; wire [TCU_TC_N-1:0][FEDP_SF-1:0][7:0] mx_sf_b; - wire [3:0] mx_elems_per_word = 4'(32 / tcu_fmt_width(fmt_s)); + // Per-format constants are tabulated: computed from fmt_s at run time they + // build dividers (a 187-level path in an every-format build). + localparam MX_NFMT = 1 << TCU_FMT_WIDTH; + function automatic logic [MX_NFMT-1:0][MX_SCALE_LG2_W-1:0] mx_lg2_table(input int unsigned tile_k_words); + logic [MX_NFMT-1:0][MX_SCALE_LG2_W-1:0] t; + for (int f = 0; f < MX_NFMT; ++f) begin + t[f] = MX_SCALE_LG2_W'(mx_scale_blocks_k_lg2(TCU_FMT_WIDTH'(f), tile_k_words)); + end + return t; + endfunction + function automatic logic [MX_NFMT-1:0][3:0] mx_epw_table(); + logic [MX_NFMT-1:0][3:0] t; + for (int f = 0; f < MX_NFMT; ++f) begin + automatic int unsigned w = tcu_fmt_width(TCU_FMT_WIDTH'(f)); + t[f] = (w != 0) ? 4'(32 / w) : 4'd0; + end + return t; + endfunction + localparam logic [MX_NFMT-1:0][3:0] MX_EPW = mx_epw_table(); + localparam logic [MX_NFMT-1:0][MX_SCALE_LG2_W-1:0] MX_LG2_TILE = mx_lg2_table(TCU_TILE_K); +`ifdef VX_CFG_TCU_WGMMA_ENABLE + localparam logic [MX_NFMT-1:0][MX_SCALE_LG2_W-1:0] MX_LG2_WG = mx_lg2_table(TCU_WG_K_STEPS * TCU_WG_FEDP_K); +`endif + + wire [3:0] mx_elems_per_word = MX_EPW[fmt_s]; `STATIC_ASSERT ((TCU_TILE_K & (TCU_TILE_K - 1)) == 0, ("the MX scale row shift needs a power-of-two TCU_TILE_K")) `ifdef VX_CFG_TCU_WGMMA_ENABLE `STATIC_ASSERT ((TCU_WG_K_STEPS * TCU_WG_FEDP_K & (TCU_WG_K_STEPS * TCU_WG_FEDP_K - 1)) == 0, ("the MX scale row shift needs a power-of-two WGMMA K")) `endif wire [MX_SCALE_LG2_W-1:0] mx_blocks_k_lg2 = `ifdef VX_CFG_TCU_WGMMA_ENABLE - is_wgmma ? MX_SCALE_LG2_W'(mx_scale_blocks_k_lg2(fmt_s, TCU_WG_K_STEPS * TCU_WG_FEDP_K)) - : MX_SCALE_LG2_W'(mx_scale_blocks_k_lg2(fmt_s, TCU_TILE_K)); + is_wgmma ? MX_LG2_WG[fmt_s] : MX_LG2_TILE[fmt_s]; `else - MX_SCALE_LG2_W'(mx_scale_blocks_k_lg2(fmt_s, TCU_TILE_K)); + MX_LG2_TILE[fmt_s]; `endif wire mx_blocks_k_nz = (tcu_fmt_width(fmt_s) != 0); wire [MX_K_IDX_W:0] mx_uop_k_words = @@ -436,7 +508,13 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire [MX_IDX_W-1:0] mx_a_idx = MX_IDX_W'(step_m) * MX_IDX_W'(TCU_TC_M) + MX_IDX_W'(i); for (genvar s = 0; s < FEDP_SF; ++s) begin : g_s wire [MX_K_IDX_W-1:0] mx_k_idx = mx_k_base_idx + MX_K_IDX_W'((s * mx_fedp_k_elems) / FEDP_SF); + `ifdef VX_CFG_TCU_TMEM_ENABLE + // Warps issue no WGMMA with TMEM: a WGMMA step is a tensor job's. + assign mx_sf_a[i][s] = is_wgmma ? job_sf[i][s] + : mx_scale_at(mx_meta_a, fmt_s, mx_blocks_k_lg2, mx_blocks_k_nz, mx_a_idx, mx_k_idx); + `else assign mx_sf_a[i][s] = mx_scale_at(mx_meta_a, fmt_s, mx_blocks_k_lg2, mx_blocks_k_nz, mx_a_idx, mx_k_idx); + `endif end end @@ -444,7 +522,12 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire [MX_IDX_W-1:0] mx_b_idx = MX_IDX_W'(step_n) * MX_IDX_W'(TCU_TC_N) + MX_IDX_W'(j); for (genvar s = 0; s < FEDP_SF; ++s) begin : g_s wire [MX_K_IDX_W-1:0] mx_k_idx = mx_k_base_idx + MX_K_IDX_W'((s * mx_fedp_k_elems) / FEDP_SF); + `ifdef VX_CFG_TCU_TMEM_ENABLE + assign mx_sf_b[j][s] = is_wgmma ? job_sf[TCU_TC_M + j][s] + : mx_scale_at(mx_meta_b, fmt_s, mx_blocks_k_lg2, mx_blocks_k_nz, mx_b_idx, mx_k_idx); + `else assign mx_sf_b[j][s] = mx_scale_at(mx_meta_b, fmt_s, mx_blocks_k_lg2, mx_blocks_k_nz, mx_b_idx, mx_k_idx); + `endif end end `endif @@ -459,7 +542,7 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( for (genvar i = 0; i < PE_M; ++i) begin : g_i `ifdef VX_CFG_TCU_SPARSE_ENABLE // The row's candidate selects, shared by its FEDPs (all columns). - wire [TCU_TC_K-1:0][7:0][5:0] sp_sel; + wire [TCU_TC_K-1:0][7:0][5:0] sp_sel, sp_sel_hi; VX_tcu_sp_sel #( .ROW_IDX (i), .ROW_STRIDE (PE_M), @@ -470,6 +553,25 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .vld_mask (vld_meta_block), .sel (sp_sel) ); + `ifdef VX_CFG_TCU_WGMMA_ENABLE + if (TCU_WG_SP_FULLK != 0) begin : g_sp_sel_hi + VX_tcu_sp_sel #( + .ROW_IDX (i), + .ROW_STRIDE (PE_M), + .ROW_SELS (PE_RATIO_M) + ) tcu_sp_sel_hi ( + .row_sel (slice_m), + .fmt_s (fmt_s), + .vld_mask (vld_meta_block_hi), + .sel (sp_sel_hi) + ); + end else + `endif + begin : g_sp_sel_hi_off + assign sp_sel_hi = '0; + `UNUSED_VAR (sp_sel_hi) + `UNUSED_VAR (vld_meta_block_hi) + end `endif for (genvar j = 0; j < PE_N; ++j) begin : g_j // the output element (row_i, col_j) this PE computes this cycle @@ -479,6 +581,7 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( `ifdef VX_CFG_TCU_SPARSE_ENABLE wire [FEDP_K-1:0][31:0] a_row, b_col, b_col_dense; wire [TCU_TC_K-1:0][31:0] b_col_sparse, b_col_1, b_col_2; + wire [TCU_TC_K-1:0][31:0] b_col_sparse_hi; `else wire [FEDP_K-1:0][31:0] a_row, b_col; `endif @@ -527,7 +630,7 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( `endif assign a_row[k_idx] = (is_wgmma `ifdef VX_CFG_TCU_SPARSE_ENABLE - && !is_sparse + && (!is_sparse || (TCU_WG_SP_FULLK != 0)) `endif ) ? (wg_a_smem ? a_wgmma_smem : a_wgmma_reg) : 32'b0; `else @@ -588,7 +691,36 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( if (k_idx < TCU_TC_K) begin : g_lo assign b_col[k_idx] = is_sparse ? b_col_sparse[k_idx] : b_col_dense[k_idx]; end else begin : g_hi - assign b_col[k_idx] = is_sparse ? 32'b0 : b_col_dense[k_idx]; + assign b_col[k_idx] = is_sparse ? b_col_sparse_hi[k_idx - TCU_TC_K] + : b_col_dense[k_idx]; + end + end + + // A full-K sparse step: the upper FEDP half selects its B candidates from + // the second K-word group with the upper half-K metadata. + `ifdef VX_CFG_TCU_WGMMA_ENABLE + if (TCU_WG_SP_FULLK != 0) begin : g_sp_hi + wire [TCU_TC_K-1:0][31:0] b_col_1_hi, b_col_2_hi, b_col_sel_hi; + for (genvar k_idx = 0; k_idx < TCU_TC_K; ++k_idx) begin : g_hi_slice + assign b_col_1_hi[k_idx] = 32'(rs2_data[(TCU_TC_K + k_idx) * TCU_TC_N * 2 + col_j * 2]); + assign b_col_2_hi[k_idx] = 32'(rs2_data[(TCU_TC_K + k_idx) * TCU_TC_N * 2 + col_j * 2 + 1]); + end + VX_tcu_sp_mux #( + .INSTANCE_ID (INSTANCE_ID) + ) tcu_sp_mux_hi ( + .sel (sp_sel_hi), + .b_col_in1 (b_col_1_hi), + .b_col_in2 (b_col_2_hi), + .b_col_out (b_col_sel_hi) + ); + assign b_col_sparse_hi = is_wgmma ? b_col_sel_hi : '0; + end else + `endif + begin : g_sp_hi_off + assign b_col_sparse_hi = '0; + // Without FEDP2K there are no upper FEDP lanes to consume it. + if (FEDP_K == TCU_TC_K) begin : g_sp_hi_unused + `UNUSED_VAR (b_col_sparse_hi) end end @@ -892,6 +1024,7 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( localparam RESULT_DATAW = TCU_TC_M * TCU_TC_N * 32; +`ifdef VX_CFG_TCU_WMMA_ENABLE wire [RESULT_DATAW-1:0] landq_data; wire landq_empty, landq_full; @@ -925,6 +1058,11 @@ module VX_tcu_core import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire [RESULT_DATAW-1:0] result_data = landq_empty ? RESULT_DATAW'(d_val) : landq_data; `RUNTIME_ASSERT (~(landq_push && landq_full), ("%t: %s: result landing queue overflow", $time, INSTANCE_ID)) +`else + assign result_if.valid = setup_valid_r || fedp_done; + wire [RESULT_DATAW-1:0] result_data = RESULT_DATAW'(d_val); + `RUNTIME_ASSERT (~fedp_done || result_if.ready, ("%t: %s: a result stalled with no landing queue", $time, INSTANCE_ID)) +`endif // NaN-box the fp32 results for XLEN=64: upper 32 bits must be all-1s per RVF spec. for (genvar e = 0; e < TCU_TC_M * TCU_TC_N; ++e) begin : g_result diff --git a/hw/rtl/tcu/VX_tcu_pkg.sv b/hw/rtl/tcu/VX_tcu_pkg.sv index fa507eac0c..33b8d71566 100644 --- a/hw/rtl/tcu/VX_tcu_pkg.sv +++ b/hw/rtl/tcu/VX_tcu_pkg.sv @@ -115,10 +115,22 @@ package VX_tcu_pkg; localparam TCU_B_SUB_BLOCKS_SP = TCU_BLOCK_CAP / TCU_B_BLOCK_SIZE_SP; // WGMMA_SP always needs the full candidate lane set, regardless of SYM_SPARSE. localparam TCU_WG_B_BLOCK_SIZE_SP = TCU_TC_K * TCU_TC_N * 2; + // A tensor op's sparse step (TMEM builds, FEDP2K) fills the doubled-K FEDP + // with compressed A, as Blackwell's sparse tcgen05.mma: it needs two half-K + // metadata banks per m-step. +`ifdef TCU_SP_FULLK + localparam TCU_WG_SP_FULLK = (TCU_K_STEPS / 2 >= 2) ? 1 : 0; +`else + localparam TCU_WG_SP_FULLK = 0; +`endif + localparam TCU_WG_SP_K_WORDS = (TCU_WG_SP_FULLK != 0) ? TCU_WG_FEDP_K : TCU_TC_K; + localparam TCU_WG_B_KMAJ_SIZE_SP = TCU_WG_SP_K_WORDS * TCU_TC_N * 2; localparam TCU_WG_RS2_WIDTH_DENSE = (TCU_WG_B_BLOCK_SIZE > TCU_BLOCK_CAP) ? TCU_WG_B_BLOCK_SIZE : TCU_BLOCK_CAP; + localparam TCU_WG_RS2_WIDTH_SP = + (TCU_WG_B_KMAJ_SIZE_SP > TCU_WG_B_BLOCK_SIZE_SP) ? TCU_WG_B_KMAJ_SIZE_SP : TCU_WG_B_BLOCK_SIZE_SP; localparam TCU_WG_RS2_WIDTH = `VX_CFG_TCU_SPARSE_ENABLED - ? ((TCU_WG_B_BLOCK_SIZE_SP > TCU_WG_RS2_WIDTH_DENSE) ? TCU_WG_B_BLOCK_SIZE_SP : TCU_WG_RS2_WIDTH_DENSE) + ? ((TCU_WG_RS2_WIDTH_SP > TCU_WG_RS2_WIDTH_DENSE) ? TCU_WG_RS2_WIDTH_SP : TCU_WG_RS2_WIDTH_DENSE) : TCU_WG_RS2_WIDTH_DENSE; localparam TCU_MIN_FMT_WIDTH = 4; //int4 @@ -314,14 +326,20 @@ package VX_tcu_pkg; endcase endfunction - function automatic int unsigned mx_scale_block_size(input logic [TCU_FMT_WIDTH-1:0] fmt); + // MX scale block: 32 elements (MXFP8/MXBF8/MXFP4) or 16 (NVFP4), as a log2 + // so the scale index is a shift. + function automatic logic [2:0] mx_scale_block_lg2(input logic [TCU_FMT_WIDTH-1:0] fmt); case (fmt) - TCU_MXFP8_ID, TCU_MXBF8_ID, TCU_MXFP4_ID: return 32; - TCU_NVFP4_ID: return 16; - default: return 1; + TCU_MXFP8_ID, TCU_MXBF8_ID, TCU_MXFP4_ID: return 3'd5; + TCU_NVFP4_ID: return 3'd4; + default: return 3'd0; endcase endfunction + function automatic int unsigned mx_scale_block_size(input logic [TCU_FMT_WIDTH-1:0] fmt); + return 1 << mx_scale_block_lg2(fmt); + endfunction + function automatic int unsigned mx_scale_blocks_k_words( input logic [TCU_FMT_WIDTH-1:0] fmt, input int unsigned tile_k_words @@ -421,6 +439,15 @@ package VX_tcu_pkg; trace_fmt(level, op_args.tcu.fmt_s); end `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + INST_TCU_TMEM_LD: begin `TRACE(level, ("TMEM_LD%s.%0d", op_args.tcu.a_from_smem ? ".R" : "", op_args.tcu.fmt_d)); end + INST_TCU_TMEM_ST: begin `TRACE(level, ("TMEM_ST%s.%0d", op_args.tcu.a_from_smem ? ".R" : "", op_args.tcu.fmt_d)); end + INST_TCU_TC_CP: begin `TRACE(level, ("TC_CP")); end + INST_TCU_TMEM_ALLOC: begin `TRACE(level, ("TMEM_ALLOC")); end + INST_TCU_TMEM_DEALLOC: begin `TRACE(level, ("TMEM_DEALLOC")); end + INST_TCU_TC_MMA: begin `TRACE(level, ("TC_MMA.%0d", op_args.tcu.fmt_d)); end + INST_TCU_TC_COMMIT: begin `TRACE(level, ("TC_COMMIT")); end + `endif `ifdef VX_CFG_TCU_SPARSE_ENABLE INST_TCU_WMMA_SP: begin `TRACE(level, ("WMMA.SP.")); @@ -449,6 +476,10 @@ package VX_tcu_pkg; `DECL_EXECUTE_T (tcu, `VX_CFG_NUM_TCU_LANES); + // N step width of a tile-buffer request: a tensor op walks up to 128 + // fragments; a WGMMA at most 16 N steps. + localparam TCU_TBUF_N_W = `VX_CFG_TCU_TMEM_ENABLED ? 8 : 4; + // tcu_tbuf_req_t — per-block uop request packed for VX_tcu_tbuf. // `valid` is pre-gated to WGMMA and masked by `cta_conflict`. typedef struct packed { @@ -457,7 +488,7 @@ package VX_tcu_pkg; logic [NW_WIDTH-1:0] wid; logic [NCTA_WIDTH-1:0] cta_id; logic [3:0] step_m; - logic [3:0] step_n; + logic [TCU_TBUF_N_W-1:0] step_n; logic [3:0] step_k; logic [1:0] cd_nregs; logic [`VX_CFG_XLEN-1:0] desc_a; diff --git a/hw/rtl/tcu/VX_tcu_shared.sv b/hw/rtl/tcu/VX_tcu_shared.sv index 0b232fa3f4..8af9c1feac 100644 --- a/hw/rtl/tcu/VX_tcu_shared.sv +++ b/hw/rtl/tcu/VX_tcu_shared.sv @@ -14,7 +14,7 @@ `include "VX_define.vh" // TCU state shared by every TCU block: the WGMMA tile buffers (a warpgroup's -// B operand is common to its blocks). +// B operand is common to its blocks) and the tensor memory. module VX_tcu_shared import VX_gpu_pkg::*, VX_tcu_pkg::*; #( parameter `STRING INSTANCE_ID = "", parameter BLOCK_SIZE = `VX_CFG_NUM_TCU_BLOCKS @@ -34,6 +34,15 @@ module VX_tcu_shared import VX_gpu_pkg::*, VX_tcu_pkg::*; #( VX_mem_bus_if.master tcu_lmem_if, `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_job_if.tmem job_if [BLOCK_SIZE], + // tc.commit arrivals + VX_tcu_bar_if.master tcu_bar_if, + // a CTA's last warp retired: its TMEM columns are freed + input wire cta_exit_valid, + input wire [NCTA_WIDTH-1:0] cta_exit_id, +`endif + input wire clk, input wire reset ); @@ -43,7 +52,117 @@ module VX_tcu_shared import VX_gpu_pkg::*, VX_tcu_pkg::*; #( `UNUSED_VAR ({clk, reset}) `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + wire [BLOCK_SIZE-1:0] tj_op_valid, tj_op_ready; + tcu_execute_t tj_op_data [BLOCK_SIZE]; + wire [BLOCK_SIZE-1:0] tj_rsp_valid, tj_rsp_ready; + tcu_result_t tj_rsp_data [BLOCK_SIZE]; + wire job_valid, job_fire; + tcu_execute_t job_data [BLOCK_SIZE]; + wire [BLOCK_SIZE-1:0] job_core_ready; + wire [BLOCK_SIZE-1:0] jres_valid; + wire [BLOCK_SIZE-1:0][`VX_CFG_NUM_THREADS-1:0][31:0] jres_data; + tcu_tbuf_req_t [BLOCK_SIZE-1:0] job_tbuf_req; + wire job_a_fill_valid; + wire [3:0] job_a_fill_idx; + wire [BLOCK_SIZE-1:0][TCU_WG_TILE_M-1:0][TCU_TC_N-1:0][31:0] job_a_fill_data; +`ifdef VX_CFG_TCU_SPARSE_ENABLE + wire [BLOCK_SIZE-1:0][TCU_MAX_META_BLOCK_WIDTH-1:0] job_meta, job_meta_hi; +`endif +`ifdef VX_CFG_TCU_MX_ENABLE + wire [BLOCK_SIZE-1:0][TCU_TC_M+TCU_TC_N-1:0][TCU_MX_MAX_SF-1:0][7:0] job_sf; +`endif + VX_mem_bus_if #( + .DATA_SIZE (`VX_CFG_LMEM_NUM_BANKS * (`VX_CFG_XLEN / 8)), + .TAG_WIDTH (TCU_LMEM_BLK_TAG_W), + .ATTR_WIDTH (LMEM_DMA_ATTR_W), + .ADDR_WIDTH (`VX_CFG_LMEM_LOG_SIZE - $clog2(`VX_CFG_XLEN / 8) - $clog2(`VX_CFG_LMEM_NUM_BANKS)) + ) job_cp_lmem_if(); + + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_job_if + assign tj_op_valid[b] = job_if[b].op_valid; + assign tj_op_data[b] = job_if[b].op_data; + assign job_if[b].op_ready = tj_op_ready[b]; + assign job_if[b].rsp_valid = tj_rsp_valid[b]; + assign job_if[b].rsp_data = tj_rsp_data[b]; + assign tj_rsp_ready[b] = job_if[b].rsp_ready; + assign job_if[b].job_valid = job_valid; + assign job_if[b].job_fire = job_fire; + assign job_if[b].job_data = job_data[b]; + assign job_core_ready[b] = job_if[b].core_ready; + assign jres_valid[b] = job_if[b].jres_valid; + assign jres_data[b] = job_if[b].jres_data; + `ifdef VX_CFG_TCU_SPARSE_ENABLE + assign job_if[b].job_meta = job_meta[b]; + assign job_if[b].job_meta_hi = job_meta_hi[b]; + `endif + `ifdef VX_CFG_TCU_MX_ENABLE + assign job_if[b].job_sf = job_sf[b]; + `endif + end + +`ifdef PERF_ENABLE + wire [PERF_CTR_BITS-1:0] tj_perf_busy, tj_perf_opnd, tj_perf_other, tj_perf_idle, tj_perf_xfers; +`endif + + VX_tcu_tmem #( + .INSTANCE_ID (`SFORMATF(("%s-tmem", INSTANCE_ID))), + .BLOCK_SIZE (BLOCK_SIZE) + ) tmem ( + .clk (clk), + .reset (reset), + `ifdef PERF_ENABLE + .perf_busy (tj_perf_busy), + .perf_opnd (tj_perf_opnd), + .perf_other (tj_perf_other), + .perf_idle (tj_perf_idle), + .perf_xfers (tj_perf_xfers), + `endif + .op_valid (tj_op_valid), + .op_data (tj_op_data), + .op_ready (tj_op_ready), + .rsp_valid (tj_rsp_valid), + .rsp_data (tj_rsp_data), + .rsp_ready (tj_rsp_ready), + .job_valid (job_valid), + .job_data (job_data), + .core_ready (job_core_ready), + .job_fire (job_fire), + .tbuf_req (job_tbuf_req), + .a_fill_valid (job_a_fill_valid), + .a_fill_idx (job_a_fill_idx), + .a_fill_data (job_a_fill_data), + `ifdef VX_CFG_TCU_SPARSE_ENABLE + .job_meta (job_meta), + .job_meta_hi (job_meta_hi), + `endif + `ifdef VX_CFG_TCU_MX_ENABLE + .job_sf (job_sf), + `endif + .jres_valid (jres_valid), + .jres_data (jres_data), + .cta_exit_valid (cta_exit_valid), + .cta_exit_id (cta_exit_id), + .tcu_bar_if (tcu_bar_if), + .cp_lmem_if (job_cp_lmem_if) + ); +`endif + `ifdef VX_CFG_TCU_WGMMA_ENABLE +`ifdef PERF_ENABLE + tcu_perf_t wgmma_perf; + always_comb begin + tcu_perf = wgmma_perf; + `ifdef VX_CFG_TCU_TMEM_ENABLE + tcu_perf.mma_busy = tj_perf_busy; + tcu_perf.opnd_waits = tj_perf_opnd; + tcu_perf.job_other = tj_perf_other; + tcu_perf.idle = tj_perf_idle; + tcu_perf.tmem_xfers = tj_perf_xfers; + `endif + end +`endif + VX_tcu_wgmma #( .INSTANCE_ID (`SFORMATF(("%s-wgmma", INSTANCE_ID))), .BLOCK_SIZE (BLOCK_SIZE) @@ -51,12 +170,19 @@ module VX_tcu_shared import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .clk (clk), .reset (reset), `ifdef PERF_ENABLE - .tcu_perf (tcu_perf), + .tcu_perf (wgmma_perf), `endif .exec_valid (exec_valid), .exec_ready (exec_ready), .exec_data (exec_data), .tcu_lmem_if (tcu_lmem_if), + `ifdef VX_CFG_TCU_TMEM_ENABLE + .job_req (job_tbuf_req), + .job_a_fill_valid (job_a_fill_valid), + .job_a_fill_idx (job_a_fill_idx), + .job_a_fill_data (job_a_fill_data), + .job_cp_lmem_if (job_cp_lmem_if), + `endif .tbuf_rs1_data (tbuf_rs1_data), .tbuf_rs2_data (tbuf_rs2_data), .tbuf_ready_eff (tbuf_ready_eff) @@ -68,6 +194,11 @@ module VX_tcu_shared import VX_gpu_pkg::*, VX_tcu_pkg::*; #( assign tcu_perf.lmem_reads = '0; assign tcu_perf.wgmma_instrs = '0; assign tcu_perf.wgmma_stalls = '0; + assign tcu_perf.mma_busy = '0; + assign tcu_perf.opnd_waits = '0; + assign tcu_perf.job_other = '0; + assign tcu_perf.idle = '0; + assign tcu_perf.tmem_xfers = '0; `endif `endif diff --git a/hw/rtl/tcu/VX_tcu_tbuf.sv b/hw/rtl/tcu/VX_tcu_tbuf.sv index 606a4f23f6..80eb2e68ec 100644 --- a/hw/rtl/tcu/VX_tcu_tbuf.sv +++ b/hw/rtl/tcu/VX_tcu_tbuf.sv @@ -23,7 +23,8 @@ // - 1 × VX_tcu_bbuf (TB-shared B buffer, 2-slot for sparse) // - 1 × VX_mem_bus_arb (LMEM masters → 1 LMEM port) // -// LMEM master count: BLOCK_SIZE (abufs) + 1 (bbuf). +// LMEM master count: BLOCK_SIZE (abufs) + 1 (bbuf), + 1 (tensor-job copy, +// lowest priority) in TMEM builds. // // Sparse-metadata note: WGMMA sparse — both RS and SS — preloads metadata // into VX_tcu_sp_meta SRAM via TCU_LD ahead of the MMA dispatch; no buffer @@ -56,6 +57,13 @@ module VX_tcu_tbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // Per-block uop observation (sized BLOCK_SIZE; req.valid pre-gated to WGMMA) input tcu_tbuf_req_t [BLOCK_SIZE-1:0] req, +`ifdef VX_CFG_TCU_TMEM_ENABLE + input wire a_fill_valid, + input wire [3:0] a_fill_idx, + input wire [BLOCK_SIZE-1:0][TCU_WG_TILE_M-1:0][TCU_TC_N-1:0][31:0] a_fill_data, + VX_mem_bus_if.slave tcu_cp_lmem_if, +`endif + // Single LMEM master out (post-arb) VX_mem_bus_if.master tcu_lmem_if, @@ -67,7 +75,8 @@ module VX_tcu_tbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( `UNUSED_SPARAM (INSTANCE_ID) localparam BBUF_IDX = BLOCK_SIZE; - localparam NUM_LMEM_MASTERS = BLOCK_SIZE + 1; + localparam CBUF_IDX = BLOCK_SIZE + 1; + localparam NUM_LMEM_MASTERS = BLOCK_SIZE + 1 + `VX_CFG_TCU_TMEM_ENABLED; // ----------------------------------------------------------------------- // LMEM master fan-in interface array (BLOCK_SIZE abufs + 1 bbuf) @@ -113,11 +122,16 @@ module VX_tcu_tbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .req_desc_a (req[b].desc_a), .req_a_is_smem (req[b].a_is_smem), `ifdef VX_CFG_TCU_SPARSE_ENABLE - .req_is_sparse (req[b].is_sparse), + .req_is_sparse_in (req[b].is_sparse), `else - .req_is_sparse (1'b0), + .req_is_sparse_in (1'b0), `endif .req_uuid (req[b].uuid), + `ifdef VX_CFG_TCU_TMEM_ENABLE + .a_fill_valid (a_fill_valid), + .a_fill_idx (a_fill_idx), + .a_fill_data (a_fill_data[b]), + `endif .tcu_lmem_if (lmem_masters[b]), .abuf_ready (abuf_ready_w[b]), .abuf_rs1_data (abuf_rs1_data_w[b]) @@ -147,7 +161,7 @@ module VX_tcu_tbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( wire bbuf_req_is_sparse; wire [3:0] bbuf_req_step_m; wire [3:0] bbuf_req_step_k; - wire [3:0] bbuf_req_step_n; + wire [TCU_TBUF_N_W-1:0] bbuf_req_step_n; wire [1:0] bbuf_req_cd_nregs; wire [NCTA_WIDTH-1:0] bbuf_req_cta_id; wire [`VX_CFG_XLEN-1:0] bbuf_req_desc_b; @@ -194,7 +208,7 @@ module VX_tcu_tbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( logic sel_is_sparse; logic [3:0] sel_step_m; logic [3:0] sel_step_k; - logic [3:0] sel_step_n; + logic [TCU_TBUF_N_W-1:0] sel_step_n; logic [1:0] sel_cd_nregs; logic [NCTA_WIDTH-1:0] sel_cta_id; logic [`VX_CFG_XLEN-1:0] sel_desc_b; @@ -267,6 +281,12 @@ module VX_tcu_tbuf import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .bbuf_rs2_data (bbuf_rs2_data_w) ); +`ifdef VX_CFG_TCU_TMEM_ENABLE + `ASSIGN_VX_MEM_BUS_IF (lmem_masters[CBUF_IDX], tcu_cp_lmem_if); +`else + `UNUSED_PARAM (CBUF_IDX) +`endif + // ----------------------------------------------------------------------- // LMEM port arbitration (NUM_LMEM_MASTERS → 1) // ----------------------------------------------------------------------- diff --git a/hw/rtl/tcu/VX_tcu_tmem.sv b/hw/rtl/tcu/VX_tcu_tmem.sv new file mode 100644 index 0000000000..a8001bc247 --- /dev/null +++ b/hw/rtl/tcu/VX_tcu_tmem.sv @@ -0,0 +1,1339 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +`include "VX_define.vh" + +`ifdef VX_CFG_TCU_TMEM_ENABLE + +// Tensor memory and its MMA engine. +// +// TMEM is BLOCK_SIZE * XM lanes by TMEM_COLS 32-bit columns. Block b owns +// lanes [b*XM, (b+1)*XM), the M rows it computes, stored fragment-major: a +// storage row is one C/D fragment (TC_M lanes by TC_N columns, word +// i*TC_N + j = lane m*TC_M + i, column g*TC_N + j), and the two M steps of a +// column group g sit at row g of two RAMs. An MMA step reads and writes one +// row of one RAM with identity wiring; the transfer shapes are built on the +// tmem.ld/st path only. +// +// tmem.ld/st go to the issuing warp's own block, each block through its own +// port. tc.mma, tc.cp, tc.commit and the allocation ops pass a scalar-only +// port; tc.mma/tc.cp enter one in-order queue, and a tc.commit rides on the +// youngest op still queued or running. The engine runs the head op: a tc.mma +// is one K step, walked (m, n) on all blocks in lockstep over the WGMMA tile +// buffers and the blocks' FEDP arrays; a tc.cp copies pre-packed fragment +// rows, one LMEM bank row per read, through the tile buffers' LMEM port. An +// op leaving the engine posts its commits with the count of steps issued so +// far; a commit arrives on its barrier once that many have been written back. +// Ordering between tmem.ld/st and the MMAs is the software's (commit, barrier +// wait, tmem::wait_st), checked by the SimX contract checker; the only +// hazard checked here is a step whose C fragment is still being written. + +module VX_tcu_tmem import VX_gpu_pkg::*, VX_tcu_pkg::*; #( + parameter `STRING INSTANCE_ID = "", + parameter BLOCK_SIZE = `VX_CFG_NUM_TCU_BLOCKS +) ( + input wire clk, + input wire reset, + +`ifdef PERF_ENABLE + output wire [PERF_CTR_BITS-1:0] perf_busy, + output wire [PERF_CTR_BITS-1:0] perf_opnd, + output wire [PERF_CTR_BITS-1:0] perf_other, + output wire [PERF_CTR_BITS-1:0] perf_idle, + output wire [PERF_CTR_BITS-1:0] perf_xfers, +`endif + + // TMEM ops and tc ops from each block's dispatch + input wire [BLOCK_SIZE-1:0] op_valid, + input tcu_execute_t op_data [BLOCK_SIZE], + output wire [BLOCK_SIZE-1:0] op_ready, + + output wire [BLOCK_SIZE-1:0] rsp_valid, + output tcu_result_t rsp_data [BLOCK_SIZE], + input wire [BLOCK_SIZE-1:0] rsp_ready, + + // MMA steps to the blocks' tcu_cores (presented on all blocks at once) + output wire job_valid, + output tcu_execute_t job_data [BLOCK_SIZE], + input wire [BLOCK_SIZE-1:0] core_ready, + output wire job_fire, + + // Tile-buffer requests of the presented step + output tcu_tbuf_req_t [BLOCK_SIZE-1:0] tbuf_req, + + // A K step's A from TMEM, one fragment group of every lane per read + output wire a_fill_valid, + output wire [3:0] a_fill_idx, + output wire [BLOCK_SIZE-1:0][TCU_WG_TILE_M-1:0][TCU_TC_N-1:0][31:0] a_fill_data, + +`ifdef VX_CFG_TCU_SPARSE_ENABLE + // Metadata of the presented step: its two TC_K halves + output wire [BLOCK_SIZE-1:0][TCU_MAX_META_BLOCK_WIDTH-1:0] job_meta, + output wire [BLOCK_SIZE-1:0][TCU_MAX_META_BLOCK_WIDTH-1:0] job_meta_hi, +`endif +`ifdef VX_CFG_TCU_MX_ENABLE + // MX scales of the presented step: TC_M A rows, then TC_N B columns + output wire [BLOCK_SIZE-1:0][TCU_TC_M+TCU_TC_N-1:0][TCU_MX_MAX_SF-1:0][7:0] job_sf, +`endif + + // Step results from the blocks' tcu_cores, in issue order per block + input wire [BLOCK_SIZE-1:0] jres_valid, + input wire [BLOCK_SIZE-1:0][`VX_CFG_NUM_THREADS-1:0][31:0] jres_data, + + // A CTA's last warp retired: its columns are freed + input wire cta_exit_valid, + input wire [NCTA_WIDTH-1:0] cta_exit_id, + + VX_tcu_bar_if.master tcu_bar_if, + VX_mem_bus_if.master cp_lmem_if +); + `UNUSED_SPARAM (INSTANCE_ID) + + localparam NT = `VX_CFG_NUM_THREADS; + localparam TC_M = TCU_TC_M; + localparam TC_N = TCU_TC_N; + localparam M_STEPS = TCU_WG_M_STEPS; + localparam XM = TCU_WG_TILE_M; + localparam TPL = NT / XM; // threads per lane (lane per thread) + localparam RG = TC_N / TPL; // lane-per-thread registers per group + localparam COLS = `VX_CFG_TCU_TMEM_COLS; + localparam LANES = BLOCK_SIZE * XM; + localparam GROUPS = COLS / TC_N; + localparam GW = `LOG2UP(GROUPS); + localparam BLKW = `LOG2UP(BLOCK_SIZE); + localparam COLW = 16; + localparam OPQ = 4; // tc.mma / tc.cp queue + localparam OPQW = `LOG2UP(OPQ); + localparam CMQ = 4; // posted commits + localparam CMQW = `LOG2UP(CMQ); + localparam WQ_DEPTH = 16; // steps in flight + localparam SCNTW = 16; // step counters + localparam A_READS = TCU_WG_FEDP_K / TC_N; + localparam CP_ROW_WORDS = `VX_CFG_LMEM_NUM_BANKS * (`VX_CFG_XLEN / 32); + localparam CP_FRAGS = CP_ROW_WORDS / NT; // fragment rows per LMEM bank row + localparam CP_ADDRW = `VX_CFG_LMEM_LOG_SIZE - `CLOG2(CP_ROW_WORDS * 4); + localparam ACOLS = 32; + localparam ACHUNKS = COLS / ACOLS; + localparam ACW = `UP(`CLOG2(ACHUNKS)); + + `STATIC_ASSERT (TC_M * TC_N == NT, ("C fragment must span the warp")) + `STATIC_ASSERT (M_STEPS == 2, ("TMEM stores the two M steps of a group in two RAMs")) + `STATIC_ASSERT (NT % XM == 0, ("TMEM needs NUM_THREADS to be a multiple of WGMMA M")) + `STATIC_ASSERT (TCU_WG_FEDP_K % TC_N == 0, ("a K step of A from TMEM is whole fragment groups")) + `STATIC_ASSERT (CP_ROW_WORDS % NT == 0, ("an LMEM bank row holds whole fragment rows")) + `STATIC_ASSERT ((2 * BLOCK_SIZE) % CP_FRAGS == 0, ("a bank row's fragment rows are in one column group")) + // MMA steps issue to every block's core in one cycle; a time-multiplexed + // FEDP array takes a micro-op over several. + `STATIC_ASSERT (`VX_CFG_TCU_PE_RATIO == 1, ("TMEM requires VX_CFG_TCU_PE_RATIO=1")) + + `IGNORE_UNUSED_BEGIN + // WGMMA shared-memory descriptor: byte offset below, row stride in words above. + function automatic logic [31:0] smem_desc(input logic [17:0] off, input logic [15:0] stride_bytes); + smem_desc = {(32 - TCU_SMEM_DESC_OFF_BITS)'(stride_bytes[15:2]), TCU_SMEM_DESC_OFF_BITS'(off)}; + endfunction + + function automatic logic [BAR_ADDR_W-1:0] bar_addr(input logic [31:0] raw); + logic [NB_WIDTH-1:0] id; + logic [BAR_ADDR_W-1:0] addr; + id = NB_WIDTH'(raw[BAR_ID_SHIFT +: NB_WIDTH]); + addr = BAR_ADDR_W'(id); + if (NW_BITS != 0) begin + addr = BAR_ADDR_W'({raw[`UP(NW_BITS)-1:0], NB_BITS'(id)}); + end + return addr; + endfunction + `IGNORE_UNUSED_END + + // Metadata rows per K step: one per TC_K words of compressed A. + localparam SP_ROWS = TCU_WG_FEDP_K / TCU_TC_K; +`ifndef VX_CFG_TCU_SPARSE_ENABLE + `UNUSED_PARAM (SP_ROWS) +`endif + function automatic logic [15:0] meta_row_bits(input logic [4:0] fmt); + return 16'(TCU_TC_K * 2 * (32 / tcu_fmt_width(fmt))); + endfunction + + // ----------------------------------------------------------------------- + // Storage: per block and M step one RAM of GROUPS fragment rows + // ----------------------------------------------------------------------- + + logic [BLOCK_SIZE-1:0][M_STEPS-1:0] ram_read; + logic [BLOCK_SIZE-1:0][M_STEPS-1:0][GW-1:0] ram_raddr; + logic [BLOCK_SIZE-1:0][M_STEPS-1:0] ram_write; + logic [BLOCK_SIZE-1:0][M_STEPS-1:0][NT-1:0] ram_wren; + logic [BLOCK_SIZE-1:0][M_STEPS-1:0][GW-1:0] ram_waddr; + wire [BLOCK_SIZE-1:0][M_STEPS-1:0][NT-1:0][31:0] ram_wdata; + wire [BLOCK_SIZE-1:0][M_STEPS-1:0][NT-1:0][31:0] ram_rdata; + + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_bank + for (genvar m = 0; m < M_STEPS; ++m) begin : g_m + VX_dp_ram #( + .DATAW (NT * 32), + .SIZE (GROUPS), + .WRENW (NT), + .OUT_REG (1), + .RDW_MODE ("R") + ) mem ( + .clk (clk), + .reset (reset), + .read (ram_read[b][m]), + .write (ram_write[b][m]), + .wren (ram_wren[b][m]), + .waddr (ram_waddr[b][m]), + .wdata (ram_wdata[b][m]), + .raddr (ram_raddr[b][m]), + .rdata (ram_rdata[b][m]) + ); + end + end + + // An allocation is a power-of-two run of ACOLS-column chunks: its size + // class and chunk mask, decoded as the op is registered. + localparam NCLS = `CLOG2(ACHUNKS) + 1; + localparam CLSW = `UP(`CLOG2(NCLS)); + + // ----------------------------------------------------------------------- + // Op select: each block's op is registered, then either served by the + // block's transfer unit or presented to the scalar port. + // ----------------------------------------------------------------------- + + // Only what the ops read is kept: thread 0's rs1, rs2 and rs3 (the tc.* + // operands and the transfer address). A tmem.st does not enter the slot: + // it writes from the input, whose data the sender holds until op_ready, + // in a cycle the slot is empty, so it never passes an earlier op. + typedef struct packed { + tcu_header_t header; + logic [INST_OP_BITS-1:0] op_type; + logic [4:0] fmt_d; // transfer register index + logic frag; // transfer shape + logic [31:0] s1; + logic [31:0] s2; + logic [31:0] s3; + } q_op_t; + + logic [BLOCK_SIZE-1:0] q_valid_r; + q_op_t q_op_r [BLOCK_SIZE]; + logic [BLOCK_SIZE-1:0][CLSW-1:0] q_cls_r; + logic [BLOCK_SIZE-1:0][ACHUNKS-1:0] q_amask_r; + wire [BLOCK_SIZE-1:0] q_fire; // the registered op is done with + wire [BLOCK_SIZE-1:0] st_valid; // a tmem.st at the input, the slot empty + wire [BLOCK_SIZE-1:0] st_take; // it writes this cycle + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_q + q_op_t q_in; + assign q_in = {op_data[b].header, op_data[b].op_type, + op_data[b].op_args.tcu.fmt_d, op_data[b].op_args.tcu.a_from_smem, + op_data[b].rs1_data[0][31:0], op_data[b].rs2_data[0][31:0], + op_data[b].rs3_data[0][31:0]}; + wire in_st = (op_data[b].op_type == INST_OP_BITS'(INST_TCU_TMEM_ST)); + wire q_load = op_valid[b] && ~in_st && (~q_valid_r[b] || q_fire[b]); + assign st_valid[b] = op_valid[b] && in_st && ~q_valid_r[b]; + assign op_ready[b] = q_load || st_take[b]; + wire [31:0] in_nck = ((op_data[b].op_type == INST_OP_BITS'(INST_TCU_TMEM_ALLOC)) + ? op_data[b].rs1_data[0][31:0] : op_data[b].rs2_data[0][31:0]) / ACOLS; + always_ff @(posedge clk) begin + if (reset) begin + q_valid_r[b] <= 1'b0; + end else if (q_load) begin + q_valid_r[b] <= 1'b1; + end else if (q_fire[b]) begin + q_valid_r[b] <= 1'b0; + end + if (q_load) begin + q_op_r[b] <= q_in; + q_cls_r[b] <= size_class(in_nck); + q_amask_r[b] <= ACHUNKS'((33'(1) << in_nck) - 1); + end + end + end + + // Transfer-unit write requests, central-port responses and engine reads + // meet at the per-block ports below. + wire job_writing; // D write-backs this cycle (all blocks) + wire [BLOCK_SIZE-1:0] cp_wr_blk; // a tc.cp row write this cycle + wire [BLOCK_SIZE-1:0] xf_rd; // the transfer unit reads both RAMs + wire [BLOCK_SIZE-1:0] xf_hold; // a load's response holds the RAM outputs + wire e_cwait; // a presented step's C holds the RAM outputs + wire [BLOCK_SIZE-1:0][M_STEPS-1:0] xf_rd_m; + wire [BLOCK_SIZE-1:0][GW-1:0] xf_rd_g; + wire [BLOCK_SIZE-1:0] xf_wr; // the transfer unit writes + wire [BLOCK_SIZE-1:0][M_STEPS-1:0] xf_wr_m; + wire [BLOCK_SIZE-1:0][GW-1:0] xf_wr_g; + wire [BLOCK_SIZE-1:0][M_STEPS-1:0][NT-1:0] xf_wr_en; + wire [BLOCK_SIZE-1:0] xf_wr_frag; // the transfer is fragment shaped + wire [BLOCK_SIZE-1:0][M_STEPS-1:0][NT-1:0][31:0] xf_wd_frag; // a store's word, fragment + wire [BLOCK_SIZE-1:0][M_STEPS-1:0][NT-1:0][31:0] xf_wd_lpt; // a store's word, lane per thread + + // Central-port response, delivered through the issuing block's response slot. + logic c_rsp_valid_r; + logic [BLKW-1:0] c_rsp_blk_r; + tcu_header_t c_rsp_header_r; + logic [31:0] c_rsp_value_r; + wire [BLOCK_SIZE-1:0] c_rsp_take; + + // ----------------------------------------------------------------------- + // Per-block transfer unit (tmem.ld/st) + // ----------------------------------------------------------------------- + + wire [BLOCK_SIZE-1:0] is_xfer; + wire [BLOCK_SIZE-1:0] xfer_fire; + + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_xf + q_op_t op; + assign op = q_op_r[b]; + `UNUSED_VAR (op) + // the transfer: a tmem.ld in the slot, or a tmem.st at the input + // (the slot then empty) + wire op_ld = q_valid_r[b] && (op.op_type == INST_OP_BITS'(INST_TCU_TMEM_LD)); + wire op_st = st_valid[b]; + assign is_xfer[b] = op_ld; + wire x_in = ~q_valid_r[b]; + tcu_header_t x_header; + assign x_header = x_in ? op_data[b].header : op.header; + wire [31:0] x_s1 = x_in ? op_data[b].rs1_data[0][31:0] : op.s1; + + // taddr = {lane [31:16], column [15:0]}: the block's first lane. + wire [15:0] lane = x_s1[31:16]; + wire [COLW-1:0] col0 = x_s1[15:0]; + wire [4:0] r = x_in ? op_data[b].op_args.tcu.fmt_d : op.fmt_d; + wire frag = x_in ? op_data[b].op_args.tcu.a_from_smem : op.frag; // fragment shape + `RUNTIME_ASSERT (~(op_ld || op_st) || (32'(lane) == b * XM && (32'(col0) % TC_N) == 0), + ("%t: %s: tmem transfer of lane %0d column %0d from a warp of block %0d", $time, INSTANCE_ID, lane, col0, b)) + // A transfer is warp-wide, as tcgen05.ld/st are .sync.aligned: its + // address is thread 0's, and a store writes every thread's register. + `RUNTIME_ASSERT (~(op_ld || op_st) || (x_header.tmask == '1), + ("%t: %s: tmem transfer with inactive threads (tmask=0x%0h)", $time, INSTANCE_ID, x_header.tmask)) + + // Lane per thread: register r is group (col0 + r*TPL) / TC_N of both + // RAMs; thread t takes lane t % XM, word ((r*TPL + t/XM) % TC_N). + wire [GW-1:0] tp_g = GW'((32'(col0) + 32'(r) * TPL) / TC_N); + wire [`UP(`CLOG2(RG))-1:0] tp_sel = `UP(`CLOG2(RG))'(32'(r) % RG); + // Fragment: register r is the row of M step r % M_STEPS, group + // col0 / TC_N + r / M_STEPS, thread t its word t (the layout of the + // WGMMA accumulator registers). + wire [`UP(`CLOG2(M_STEPS))-1:0] fm = `UP(`CLOG2(M_STEPS))'(32'(r) % M_STEPS); + wire [GW-1:0] fg = GW'(32'(col0) / TC_N + 32'(r) / M_STEPS); + + // response slot + logic rsp_valid_r; + tcu_header_t rsp_header_r; + logic rsp_ld_r; // the response is a load's: its data is + // the RAM outputs, held by no other read + // a load's word source, encoded once: RAM m for a fragment + // (0..M_STEPS-1), else M_STEPS + the lane-per-thread select + localparam RSRC = M_STEPS + RG; + localparam RSRCW = `UP(`CLOG2(RSRC)); + logic [RSRCW-1:0] rd_src_r; + wire rsp_fire = rsp_valid_r && rsp_ready[b]; + assign xf_hold[b] = rsp_valid_r && rsp_ld_r && ~rsp_ready[b]; + wire rsp_free = (~rsp_valid_r || rsp_fire) && ~(c_rsp_valid_r && c_rsp_blk_r == BLKW'(b)); + + // A step's D write-back and a tc.cp row have the write port first. + wire wr_blocked = job_writing || cp_wr_blk[b]; + + // one read or write per register, then the response + wire rd_go = op_ld && rsp_free && ~e_cwait; + wire wr_go = op_st && rsp_free && ~wr_blocked; + assign xfer_fire[b] = rd_go || wr_go; + assign st_take[b] = wr_go; + + assign xf_rd[b] = rd_go; + assign xf_rd_m[b] = frag ? (2'b01 << fm) : 2'b11; + assign xf_rd_g[b] = frag ? fg : tp_g; + assign xf_wr[b] = wr_go; + assign xf_wr_m[b] = frag ? (2'b01 << fm) : 2'b11; + assign xf_wr_g[b] = frag ? fg : tp_g; + assign xf_wr_frag[b] = frag; + + // write data and enables + for (genvar m = 0; m < M_STEPS; ++m) begin : g_wm + for (genvar i = 0; i < TC_M; ++i) begin : g_wi + for (genvar j = 0; j < TC_N; ++j) begin : g_wj + localparam W = i * TC_N + j; + localparam L = m * TC_M + i; // lane in the block + // lane per thread: the thread holding (L, j) for register r + // is L + XM * d, d = (j - r*TPL) mod TC_N, if d < TPL. The + // data is not gated by the enable: with one candidate + // thread per word (NT=32) it is plain wiring. + logic tp_en; + logic [31:0] tp_data; + always_comb begin + tp_en = 1'b0; + tp_data = '0; + for (int s = 0; s < RG; ++s) begin + automatic int d = (j - s * TPL + TC_N) % TC_N; + if (d < TPL) begin + if (~tp_en || int'(tp_sel) == s) tp_data = op_data[b].rs2_data[L + XM * d][31:0]; + if (int'(tp_sel) == s) tp_en = 1'b1; + end + end + end + assign xf_wr_en[b][m][W] = frag ? 1'b1 : tp_en; + assign xf_wd_frag[b][m][W] = op_data[b].rs2_data[W][31:0]; + assign xf_wd_lpt[b][m][W] = tp_data; + end + end + end + + // read data at the RAM outputs: thread t's word is one of RSRC + // candidates, picked by one encoded select (with M_STEPS = RG = 2, a + // 4-way select: one 6-input LUT per bit) + logic [NT-1:0][31:0] rd_value; + always_comb begin + for (int t = 0; t < NT; ++t) begin + rd_value[t] = ram_rdata[b][0][t]; + for (int mm = 1; mm < M_STEPS; ++mm) begin + if (int'(rd_src_r) == mm) rd_value[t] = ram_rdata[b][mm][t]; + end + for (int s = 0; s < RG; ++s) begin + if (int'(rd_src_r) == M_STEPS + s) begin + rd_value[t] = ram_rdata[b][(t % XM) / TC_M][((t % XM) % TC_M) * TC_N + (s * TPL + t / XM) % TC_N]; + end + end + end + end + + always_ff @(posedge clk) begin + if (reset) begin + rsp_valid_r <= 1'b0; + end else begin + if (rsp_fire) rsp_valid_r <= 1'b0; + if (xfer_fire[b]) rsp_valid_r <= 1'b1; + end + if (xfer_fire[b]) begin + rsp_header_r <= x_header; + rsp_ld_r <= op_ld; + end + if (rd_go) begin + rd_src_r <= frag ? RSRCW'(fm) : RSRCW'(32'(M_STEPS) + 32'(tp_sel)); + end + end + + // a load answers from the RAM outputs, which hold until it is taken + wire [NT-1:0][31:0] payload = rd_value; + // the response: this unit's, else a central-port one for this block + wire c_here = c_rsp_valid_r && (c_rsp_blk_r == BLKW'(b)) && ~rsp_valid_r; + assign c_rsp_take[b] = c_here && rsp_ready[b]; + assign rsp_valid[b] = rsp_valid_r || c_here; + tcu_result_t rd; + always_comb begin + rd = '0; + rd.header = rsp_valid_r ? rsp_header_r : c_rsp_header_r; + // A central-port result (tmem.alloc's column) goes to thread 0 + // only; the other threads' words are undefined then. + for (int t = 0; t < NT; ++t) begin + if (t == 0 && ~rsp_valid_r) begin + rd.data[t] = `VX_CFG_XLEN'(c_rsp_value_r); + end else if (`VX_CFG_XLEN > 32) begin + rd.data[t] = `VX_CFG_XLEN'({32'hffffffff, payload[t]}); + end else begin + rd.data[t] = `VX_CFG_XLEN'(payload[t]); + end + end + end + assign rsp_data[b] = rd; + end + + // ----------------------------------------------------------------------- + // Scalar port: tc.mma, tc.cp, tc.commit, tmem.alloc/dealloc (from thread 0) + // ----------------------------------------------------------------------- + + // Allocation: one bit per ACOLS-column chunk and its owner CTA; per size + // class, whether a free aligned run exists and where the lowest starts. + logic [ACHUNKS-1:0] amap_r; + logic [ACHUNKS-1:0][NCTA_WIDTH-1:0] aown_r; + wire [NCLS-1:0] cls_avail; + wire [NCLS-1:0][ACW-1:0] cls_first; + for (genvar c = 0; c < NCLS; ++c) begin : g_cls + localparam SZ = 1 << c; + localparam NR = ACHUNKS / SZ; + wire [NR-1:0] run_free; + for (genvar k = 0; k < NR; ++k) begin : g_run + assign run_free[k] = (amap_r[k * SZ +: SZ] == '0); + end + wire [`LOG2UP(NR)-1:0] run_idx; + VX_priority_encoder #( + .N (NR) + ) run_pe ( + .data_in (run_free), + `UNUSED_PIN (onehot_out), + .index_out (run_idx), + .valid_out (cls_avail[c]) + ); + assign cls_first[c] = ACW'(32'(run_idx) * SZ); + end + function automatic logic [CLSW-1:0] size_class(input logic [31:0] nck); + size_class = '0; + for (int c = 0; c < NCLS; ++c) begin + if (nck == (32'(1) << c)) size_class = CLSW'(c); + end + endfunction + + // op queue: the payload, written once at push, sits in a LUTRAM FIFO; the + // commits (the low fields), which a later tc.commit can add to the + // youngest entry, are registers alongside it. + typedef struct packed { + logic [1:0] ncommit; + logic [1:0][BAR_ADDR_W-1:0] bar; + logic [1:0][BAR_SIZE_W-1:0] cnt; + } tc_cm_t; + typedef struct packed { + logic is_cp; + logic is_marker; // commits only + logic [NCTA_WIDTH-1:0] cta; + logic [NW_WIDTH-1:0] wid; + logic [UUID_WIDTH-1:0] uuid; + logic [31:0] w1; // tc.mma idesc / tc.cp {cols, taddr} + logic [31:0] w2; // A / tc.cp source + logic [31:0] w3; // B + logic [1:0] ncommit; + logic [1:0][BAR_ADDR_W-1:0] bar; + logic [1:0][BAR_SIZE_W-1:0] cnt; // arrival count - 1 + } tc_op_t; + + localparam CMW = $bits(tc_cm_t); + localparam PAYW = $bits(tc_op_t) - CMW; + tc_cm_t opq_cm_r [OPQ]; + logic [OPQW-1:0] opq_head_r, opq_tail_r; + logic [OPQW:0] opq_count_r; + wire opq_pop; + tc_op_t run_op_r; + logic run_valid_r; + wire [OPQW-1:0] opq_last = opq_tail_r - OPQW'(1); + + // The youngest op not out of the engine, which a commit rides on: queued, + // or a running tc.mma short of its last step (one that may leave this + // cycle has its commits already being posted). + wire run_leaves; + wire run_open; + wire young_in_q = (opq_count_r != 0); + wire young_v = young_in_q || run_open; + wire [1:0] young_ncommit = young_in_q ? opq_cm_r[opq_last].ncommit : run_op_r.ncommit; + + // A commit waits while the only queued entry leaves (starts, or posts as + // a marker): that entry is read out with the commits it had, so one + // attached in the same cycle would be lost. + wire q_sole_leaves = opq_pop && (opq_count_r == (OPQW+1)'(1)); + + logic [BLOCK_SIZE-1:0] c_elig; + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_celig + q_op_t op; + assign op = q_op_r[b]; + `UNUSED_VAR (op) + wire is_mma = (op.op_type == INST_OP_BITS'(INST_TCU_TC_MMA)); + wire is_cp = (op.op_type == INST_OP_BITS'(INST_TCU_TC_CP)); + wire is_cmt = (op.op_type == INST_OP_BITS'(INST_TCU_TC_COMMIT)); + wire is_alloc = (op.op_type == INST_OP_BITS'(INST_TCU_TMEM_ALLOC)); + wire is_free = (op.op_type == INST_OP_BITS'(INST_TCU_TMEM_DEALLOC)); + // an allocation waits, off the port, until a run of its size is free + wire fits = cls_avail[q_cls_r[b]]; + wire q_ok = ((is_mma || is_cp) && (opq_count_r < OPQ)) + || (is_cmt && ~q_sole_leaves && ((young_v && young_ncommit != 2'd2) || (opq_count_r < OPQ))) + || (is_alloc && fits) + || is_free; + assign c_elig[b] = q_valid_r[b] && ~is_xfer[b] && q_ok && (~c_rsp_valid_r || (|c_rsp_take)); + end + + wire [BLKW-1:0] c_sel; + wire c_go; + VX_priority_encoder #( + .N (BLOCK_SIZE) + ) c_pe ( + .data_in (c_elig), + `UNUSED_PIN (onehot_out), + .index_out (c_sel), + .valid_out (c_go) + ); + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_qfire + assign q_fire[b] = xfer_fire[b] || (c_go && c_sel == BLKW'(b)); + end + + q_op_t cop; + assign cop = q_op_r[c_sel]; + `UNUSED_VAR (cop) + wire c_mma = (cop.op_type == INST_OP_BITS'(INST_TCU_TC_MMA)); + wire c_cp = (cop.op_type == INST_OP_BITS'(INST_TCU_TC_CP)); + wire c_cmt = (cop.op_type == INST_OP_BITS'(INST_TCU_TC_COMMIT)); + wire c_alloc = (cop.op_type == INST_OP_BITS'(INST_TCU_TMEM_ALLOC)); + wire c_free = (cop.op_type == INST_OP_BITS'(INST_TCU_TMEM_DEALLOC)); + wire [31:0] cs1 = cop.s1; + wire [31:0] cs2 = cop.s2; + wire [31:0] cs3 = cop.s3; + `RUNTIME_ASSERT (~c_go || cop.header.tmask[0], ("%t: %s: tensor-memory op without thread 0", $time, INSTANCE_ID)) + + // allocation: the lowest free run aligned to its size + wire [31:0] c_nck = (c_alloc ? cs1 : cs2) / ACOLS; + wire [ACHUNKS-1:0] c_amask = q_amask_r[c_sel]; + wire [ACW-1:0] afit_idx = cls_first[q_cls_r[c_sel]]; + wire [ACW-1:0] free_idx = ACW'(cs1 / ACOLS); + logic free_owned; + always_comb begin + free_owned = ((cs1 % (c_nck * ACOLS)) == 0) && ((amap_r & (c_amask << free_idx)) == (c_amask << free_idx)); + for (int i = 0; i < ACHUNKS; ++i) begin + if (1'(((c_amask << free_idx) >> i) & ACHUNKS'(1))) begin + free_owned &= (aown_r[i] == cop.header.cta_id); + end + end + end + `RUNTIME_ASSERT (~(c_go && (c_alloc || c_free)) || (c_nck != 0 && c_nck <= ACHUNKS && (c_nck & (c_nck - 1)) == 0), + ("%t: %s: TMEM allocation of %0d columns", $time, INSTANCE_ID, c_alloc ? cs1 : cs2)) + `RUNTIME_ASSERT (~(c_go && c_free) || free_owned, + ("%t: %s: TMEM dealloc of columns the CTA does not own", $time, INSTANCE_ID)) + + wire c_attach = c_go && c_cmt && young_v && (young_ncommit != 2'd2); + wire c_push = c_go && (c_mma || c_cp || (c_cmt && ~c_attach)); + + tc_op_t c_entry; + always_comb begin + c_entry = '0; + c_entry.is_cp = c_cp; + c_entry.is_marker = c_cmt; + c_entry.cta = cop.header.cta_id; + c_entry.wid = cop.header.wid; + c_entry.uuid = cop.header.uuid; + c_entry.w1 = cs1; + c_entry.w2 = cs2; + c_entry.w3 = cs3; + c_entry.ncommit = c_cmt ? 2'd1 : 2'd0; + c_entry.bar[0] = bar_addr(cs1); + c_entry.cnt[0] = BAR_SIZE_W'(cs2 - 32'd1); + end + + // ----------------------------------------------------------------------- + // Engine + // ----------------------------------------------------------------------- + + // step counters and posted commits + logic [SCNTW-1:0] steps_issued_r, steps_done_r; + logic [BAR_ADDR_W-1:0] cmq_bar_r [CMQ]; + logic [BAR_SIZE_W-1:0] cmq_cnt_r [CMQ]; + logic [SCNTW-1:0] cmq_tgt_r [CMQ]; + logic [CMQW-1:0] cmq_head_r, cmq_tail_r; + logic [CMQW:0] cmq_count_r; + + // decoded running op + tc_op_t rj; + assign rj = run_op_r; + wire [4:0] r_fmt_s = rj.w1[4:0]; + wire r_sparse = rj.w1[5]; +`ifdef VX_CFG_TCU_MX_ENABLE + wire r_mx = tcu_fmt_is_mx(TCU_FMT_WIDTH'(rj.w1[4:0])); +`else + wire r_mx = 1'b0; +`endif + wire r_a_tmem = rj.w1[6]; + wire r_acc_init= rj.w1[7]; + wire [7:0] r_n_last = {1'b0, rj.w1[14:8]}; // n_frag - 1 + wire [GW-1:0] r_d_g = GW'(rj.w1[22:15]); + wire [GW-1:0] r_side_g = GW'(rj.w1[31:23] / TC_N); + wire [GW-1:0] r_a_g = GW'(rj.w2 / TC_N); + wire [17:0] r_a_off = 18'(rj.w2[TCU_SMEM_DESC_OFF_BITS-1:0]); + wire [15:0] r_lda = 16'({rj.w2[31:TCU_SMEM_DESC_OFF_BITS], 2'b00}); + wire [17:0] r_b_off = 18'(rj.w3[TCU_SMEM_DESC_OFF_BITS-1:0]); + wire [15:0] r_ldb = 16'({rj.w3[31:TCU_SMEM_DESC_OFF_BITS], 2'b00}); + // tc.cp + wire [GW-1:0] cp_g0 = GW'(rj.w1[15:0] / TC_N); + wire [15:0] cp_rows = 16'((32'(rj.w1[31:16]) * LANES) / CP_ROW_WORDS); + wire [17:0] cp_src = 18'(rj.w2); + + // walk state + logic run_go_r; // the descriptors are set; prologue and steps follow + logic run_m_r; + logic [7:0] run_n_r; + logic [3:0] pro_idx_r; + + // step register E + logic e_valid_r; + logic e_m_r; + logic [7:0] e_sn_r; + logic e_first_r; + logic e_zero_r; + logic [GW-1:0] e_g_r; + logic [UUID_WIDTH-1:0] e_uuid_r; + logic [NW_WIDTH-1:0] e_wid_r; + logic [NCTA_WIDTH-1:0] e_cta_r; + logic [4:0] e_fmt_s_r; + logic [15:0] e_lda_r, e_ldb_r; + logic e_a_tmem_r, e_sparse_r; + logic [BLOCK_SIZE-1:0][17:0] e_a_off_r; + logic [17:0] e_b_off_r; + + assign job_fire = e_valid_r && (&core_ready); + // a presented step's C is at the RAM outputs until it is taken + assign e_cwait = e_valid_r && ~e_zero_r && ~(&core_ready); + wire e_advance = ~e_valid_r || job_fire; + + // A transfer read on any block, or a load response waiting at a block's + // RAM outputs, takes the cycle from the engine's reads. + wire xf_rd_any = (|xf_rd) || (|xf_hold); + + wire is_mma_run = run_valid_r && ~rj.is_cp; + wire is_cp_run = run_valid_r && rj.is_cp; + + // prologue: metadata, then A, each a read of both RAMs on all blocks + wire r_side = r_sparse || r_mx; + wire [3:0] pro_total = (r_side ? 4'd1 : 4'd0) + (r_a_tmem ? 4'(A_READS) : 4'd0); + wire pro_pending = is_mma_run && run_go_r && (pro_idx_r < pro_total); + wire pro_go = pro_pending && ~xf_rd_any && ~e_cwait; + wire pro_meta = r_side && (pro_idx_r == 4'd0); + wire [3:0] pro_a_idx = pro_idx_r - (r_side ? 4'd1 : 4'd0); + wire [GW-1:0] pro_g = pro_meta ? r_side_g : (r_a_g + GW'(pro_a_idx)); + + // MX B-scale read of a step (below) + wire sfb_rd; + wire [`UP(`CLOG2(BLOCK_SIZE))-1:0] sfb_blk; + wire [GW-1:0] sfb_g; + + // in-flight write-backs, for the row hazard: (m, group) per step + logic [WQ_DEPTH-1:0] wb_v_r; + logic [WQ_DEPTH-1:0][GW:0] wb_key_r; + logic [`LOG2UP(WQ_DEPTH)-1:0] wb_head_r, wb_tail_r; + wire [GW-1:0] load_g = r_d_g + GW'(run_n_r); + logic row_hazard; + always_comb begin + row_hazard = 1'b0; + for (int i = 0; i < WQ_DEPTH; ++i) begin + if (wb_v_r[i] && wb_key_r[i] == {run_m_r, load_g}) row_hazard = 1'b1; + end + end + + wire load_m_last = (run_m_r == 1'(M_STEPS - 1)); + wire load_last = load_m_last && (run_n_r == r_n_last); + assign run_open = is_mma_run && ~load_last; + // the op's commits go out with its last step + wire cmq_room2 = (cmq_count_r + (CMQW+1)'(rj.ncommit)) <= CMQ; + wire load = e_advance && is_mma_run && run_go_r && ~pro_pending && ~xf_rd_any + && (r_acc_init || ~row_hazard) && (~load_last || cmq_room2); + + // tc.cp: drain the write-backs, then one bank-row read at a time + logic [15:0] cp_req_r, cp_rsp_r; + logic cp_inflight_r; + wire cp_drained = (steps_issued_r == steps_done_r); + wire cp_issue = is_cp_run && run_go_r && cp_drained && (cp_req_r < cp_rows) && ~cp_inflight_r; + wire cp_fire = cp_issue && cp_lmem_if.req_ready; + wire cp_rsp = cp_lmem_if.rsp_valid; + wire cp_done = is_cp_run && run_go_r && (cp_rsp_r == cp_rows) && cmq_room2; + + assign cp_lmem_if.req_valid = cp_issue; + assign cp_lmem_if.req_data.rw = 1'b0; + assign cp_lmem_if.req_data.addr = CP_ADDRW'((cp_src + 18'(cp_req_r) * 18'(CP_ROW_WORDS * 4)) >> `CLOG2(CP_ROW_WORDS * 4)); + assign cp_lmem_if.req_data.data = '0; + assign cp_lmem_if.req_data.byteen = '0; + assign cp_lmem_if.req_data.attr = '0; + assign cp_lmem_if.req_data.tag.uuid = rj.uuid; + assign cp_lmem_if.req_data.tag.value = '0; + assign cp_lmem_if.rsp_ready = 1'b1; + `UNUSED_VAR (cp_lmem_if.rsp_data.tag) + + // a response's fragment rows: blob fragment f = row * CP_FRAGS + q is + // M step f % 2 of block (f / 2) % BLOCK_SIZE in group f / (2 * BLOCK_SIZE) + wire [31:0] cp_f0 = 32'(cp_rsp_r) * CP_FRAGS; + wire [GW-1:0] cp_g = cp_g0 + GW'(cp_f0 / (2 * BLOCK_SIZE)); + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_cpw + logic hit; + always_comb begin + hit = 1'b0; + for (int q = 0; q < CP_FRAGS; ++q) begin + if (((cp_f0 + 32'(q)) / 2) % BLOCK_SIZE == b) hit = 1'b1; + end + end + assign cp_wr_blk[b] = cp_rsp && hit; + end + + // the next op: when the engine is free, or its op leaves this cycle + assign run_leaves = (load && load_last) || cp_done; + wire eng_free = ~run_valid_r || run_leaves; + wire [PAYW-1:0] head_pay; + VX_fifo_queue #( + .DATAW (PAYW), + .DEPTH (OPQ), + .LUTRAM (1) + ) opq_pay ( + .clk (clk), + .reset (reset), + .push (c_push), + .pop (opq_pop), + .data_in (c_entry[CMW +: PAYW]), + .data_out(head_pay), + `UNUSED_PIN (empty), + `UNUSED_PIN (alm_empty), + `UNUSED_PIN (full), + `UNUSED_PIN (alm_full), + `UNUSED_PIN (size) + ); + tc_op_t head; + assign head = {head_pay, opq_cm_r[opq_head_r]}; + wire head_v = (opq_count_r != 0); + wire head_marker = head_v && head.is_marker; + wire marker_post = eng_free && head_marker && ((cmq_count_r + (CMQW+1)'(head.ncommit)) <= CMQ) && ~run_leaves; + wire start = eng_free && head_v && ~head.is_marker; + assign opq_pop = start || marker_post; + + assign job_valid = e_valid_r; + `UNUSED_VAR (e_sparse_r) + + // C cells of the presented step: identity from the RAM of its M step, + // whose outputs hold them until the step is taken (e_cwait keeps transfer + // and prologue reads off the RAMs meanwhile). + logic [BLOCK_SIZE-1:0][NT-1:0][31:0] e_c; + always_comb begin + for (int b = 0; b < BLOCK_SIZE; ++b) begin + for (int t = 0; t < NT; ++t) begin + e_c[b][t] = e_zero_r ? 32'd0 : ram_rdata[b][e_m_r][t]; + end + end + end + + // prologue responses + logic pro_rsp_valid_r, pro_rsp_meta_r; + logic [3:0] pro_rsp_idx_r; + assign a_fill_valid = pro_rsp_valid_r && ~pro_rsp_meta_r; + assign a_fill_idx = pro_rsp_idx_r; + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_afill + for (genvar l = 0; l < XM; ++l) begin : g_l + for (genvar j = 0; j < TC_N; ++j) begin : g_j + assign a_fill_data[b][l][j] = ram_rdata[b][l / TC_M][(l % TC_M) * TC_N + j]; + end + end + end + +`ifdef VX_CFG_TCU_SPARSE_ENABLE + // Metadata, latched once per op: a lane's group words hold, from bit 0, + // the VX_tcu_sp_mux rows of the step's lower then upper TC_K words. + logic [BLOCK_SIZE-1:0][XM-1:0][TC_N*32-1:0] meta_r; + always_ff @(posedge clk) begin + if (pro_rsp_valid_r && pro_rsp_meta_r) begin + for (int b = 0; b < BLOCK_SIZE; ++b) begin + for (int l = 0; l < XM; ++l) begin + meta_r[b][l] <= ram_rdata[b][l / TC_M][(l % TC_M) * TC_N +: TC_N]; + end + end + end + end + + // Rows of M step e_m_r, packed as VX_tcu_sp_mux expects for the format. + logic [BLOCK_SIZE-1:0][TCU_MAX_META_BLOCK_WIDTH-1:0] job_meta_lo_c, job_meta_hi_c; + always_comb begin + job_meta_lo_c = '0; + job_meta_hi_c = '0; + for (int lw = 0; lw <= $clog2(TCU_MAX_ELT_RATIO); ++lw) begin + int w; + w = (TCU_TC_K * 2) << lw; + if (meta_row_bits(e_fmt_s_r) == 16'(w)) begin + for (int b = 0; b < BLOCK_SIZE; ++b) begin + for (int i = 0; i < TC_M; ++i) begin + for (int j = 0; j < w; ++j) begin + job_meta_lo_c[b][i * w + j] = meta_r[b][32'(e_m_r) * TC_M + i][j]; + if (SP_ROWS > 1) begin + job_meta_hi_c[b][i * w + j] = meta_r[b][32'(e_m_r) * TC_M + i][w + j]; + end + end + end + end + end + end + end + assign job_meta = job_meta_lo_c; + assign job_meta_hi = job_meta_hi_c; +`endif + +`ifdef VX_CFG_TCU_MX_ENABLE + // MX scales, SF = TCU_MX_MAX_SF bytes per A row and B column of a step + // (scale s covers the step's K elements from s * fedpK_elems / SF). + // A: lane l, columns side + s/4, byte s%4; latched by the prologue. + // B: byte q = col * SF + s of a dense stream of NT*4-byte rows; row r is + // M step 1 of block r % BLOCK_SIZE at group side/TC_N + 1 + r / BLOCK_SIZE. + // A step (m = 0, n) whose n starts a row reads it on the RAM the step + // leaves free, and every block takes it. + localparam SF = TCU_MX_MAX_SF; + localparam SF_WORDS = (SF + 3) / 4; + localparam SFB_NPR = (NT * 4) / (TC_N * SF); // n groups per B-scale row + `STATIC_ASSERT (SFB_NPR >= 1 && (SFB_NPR & (SFB_NPR - 1)) == 0, ("a B-scale row holds whole n groups")) + `STATIC_ASSERT (SF_WORDS <= TC_N, ("a row's A scales fit one fragment group")) + localparam NPOSW = `UP(`CLOG2(SFB_NPR)); + localparam BLKW_SF = `UP(`CLOG2(BLOCK_SIZE)); + + wire [7:0] sfb_row = run_n_r / 8'(SFB_NPR); + assign sfb_rd = r_mx && (run_m_r == 1'b0) && ((run_n_r % 8'(SFB_NPR)) == 8'd0); + assign sfb_blk = BLKW_SF'(32'(sfb_row) % BLOCK_SIZE); + assign sfb_g = r_side_g + GW'(1) + GW'(32'(sfb_row) / BLOCK_SIZE); + + logic [BLOCK_SIZE-1:0][XM-1:0][SF_WORDS-1:0][31:0] sfa_r; + logic [NT-1:0][31:0] sfb_r; + logic sfb_rd_r; + logic [BLKW_SF-1:0] sfb_blk_r; + logic [NPOSW-1:0] e_npos_r; + always_ff @(posedge clk) begin + if (pro_rsp_valid_r && pro_rsp_meta_r) begin + for (int b = 0; b < BLOCK_SIZE; ++b) begin + for (int l = 0; l < XM; ++l) begin + for (int w = 0; w < SF_WORDS; ++w) begin + sfa_r[b][l][w] <= ram_rdata[b][l / TC_M][(l % TC_M) * TC_N + w]; + end + end + end + end + sfb_rd_r <= load && sfb_rd; + if (load) begin + sfb_blk_r <= sfb_blk; + e_npos_r <= NPOSW'(run_n_r % 8'(SFB_NPR)); + end + if (sfb_rd_r) begin + sfb_r <= ram_rdata[sfb_blk_r][1]; + end + end + wire [NT-1:0][31:0] sfb_cur = sfb_rd_r ? ram_rdata[sfb_blk_r][1] : sfb_r; + wire [NT*4-1:0][7:0] sfb_bytes = sfb_cur; + + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_sf + for (genvar i = 0; i < TC_M; ++i) begin : g_a + for (genvar sx = 0; sx < SF; ++sx) begin : g_s + wire [SF_WORDS-1:0][3:0][7:0] row0 = sfa_r[b][i]; + wire [SF_WORDS-1:0][3:0][7:0] row1 = sfa_r[b][TC_M + i]; + assign job_sf[b][i][sx] = e_m_r ? row1[sx / 4][sx % 4] : row0[sx / 4][sx % 4]; + end + end + for (genvar j = 0; j < TC_N; ++j) begin : g_b + for (genvar sx = 0; sx < SF; ++sx) begin : g_s + assign job_sf[b][TC_M + j][sx] = sfb_bytes[(32'(e_npos_r) * TC_N + j) * SF + sx]; + end + end + end +`else + assign sfb_rd = 1'b0; + assign sfb_blk = '0; + assign sfb_g = '0; +`endif + + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_job + tcu_execute_t jd; + tcu_tbuf_req_t tr; + always_comb begin + jd = '0; + jd.header.uuid = e_uuid_r; + jd.header.wid = e_wid_r; + jd.header.cta_id = e_cta_r; + jd.header.tmask = '1; + jd.header.sop = 1'b1; + jd.header.eop = 1'b1; + jd.header.wb = 1'b1; + `ifdef VX_CFG_TCU_SPARSE_ENABLE + jd.op_type = e_sparse_r ? INST_OP_BITS'(INST_TCU_WGMMA_SP) : INST_OP_BITS'(INST_TCU_WGMMA); + `else + jd.op_type = INST_OP_BITS'(INST_TCU_WGMMA); + `endif + jd.op_args.tcu.a_from_smem = 1'b1; + jd.op_args.tcu.cd_nregs = 2'd2; + jd.op_args.tcu.fmt_s = e_fmt_s_r; + jd.op_args.tcu.fmt_d = (e_fmt_s_r >= 5'(TCU_I32_ID)) ? 5'(TCU_I32_ID) : 5'(TCU_FP32_ID); + jd.op_args.tcu.step_m = 4'(e_m_r); + jd.op_args.tcu.step_n = 4'(e_sn_r); // the core takes its low bits + jd.op_args.tcu.is_first_uop = e_first_r; + for (int t = 0; t < NT; ++t) begin + jd.rs3_data[t] = `VX_CFG_XLEN'(e_c[b][t]); + end + + tr = '0; + tr.valid = e_valid_r; + tr.uuid = e_uuid_r; + tr.wid = e_wid_r; + tr.cta_id = e_cta_r; + tr.step_m = 4'(e_m_r); + tr.step_n = TCU_TBUF_N_W'(e_sn_r); + tr.cd_nregs = 2'd2; + tr.desc_a = `VX_CFG_XLEN'(smem_desc(e_a_off_r[b], e_lda_r)); + tr.desc_b = `VX_CFG_XLEN'(smem_desc(e_b_off_r, e_ldb_r)); + tr.a_is_smem = ~e_a_tmem_r; + `ifdef VX_CFG_TCU_SPARSE_ENABLE + tr.is_sparse = e_sparse_r; + `endif + tr.is_first_uop = e_first_r; + end + assign job_data[b] = jd; + assign tbuf_req[b] = tr; + end + + // D write-back queue per block: the fragment's M step and group + wire [BLOCK_SIZE-1:0][GW:0] wq_head; + wire [BLOCK_SIZE-1:0] wq_full; + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_wq + VX_fifo_queue #( + .DATAW (GW + 1), + .DEPTH (WQ_DEPTH), + .LUTRAM (1) + ) wq ( + .clk (clk), + .reset (reset), + .push (job_fire), + .pop (jres_valid[b]), + .data_in ({e_m_r, e_g_r}), + .data_out(wq_head[b]), + `UNUSED_PIN (empty), + `UNUSED_PIN (alm_empty), + .full (wq_full[b]), + `UNUSED_PIN (alm_full), + `UNUSED_PIN (size) + ); + `RUNTIME_ASSERT (~(job_fire && wq_full[b]), ("%t: %s: step write queue overflow", $time, INSTANCE_ID)) + end + // blocks run in lockstep: their write-backs land together + assign job_writing = jres_valid[0]; + `UNUSED_VAR (jres_valid) + + // ----------------------------------------------------------------------- + // Port control + // ----------------------------------------------------------------------- + + // The write data is a 4-way select per RAM, its select encoded once + // per RAM, so each data bit is one 6-input LUT: D write-back, a tc.cp + // row, or a store in either shape. + localparam WS_WB = 2'd0, WS_CP = 2'd1, WS_FRAG = 2'd2, WS_LPT = 2'd3; + logic [BLOCK_SIZE-1:0][M_STEPS-1:0][1:0] ram_wsel; + logic [BLOCK_SIZE-1:0][M_STEPS-1:0][NT-1:0][31:0] cp_wdata; + + always_comb begin + ram_read = '0; + ram_raddr = '0; + ram_write = '0; + ram_wren = '0; + ram_waddr = '0; + ram_wsel = '0; + cp_wdata = '0; + for (int b = 0; b < BLOCK_SIZE; ++b) begin + for (int m = 0; m < M_STEPS; ++m) begin + // read: a transfer, else the prologue, else the step's C + if (xf_rd[b]) begin + ram_read[b][m] = xf_rd_m[b][m]; + ram_raddr[b][m] = xf_rd_g[b]; + end else if (pro_go) begin + ram_read[b][m] = 1'b1; + ram_raddr[b][m] = pro_g; + end else if (load && ~r_acc_init && (32'(run_m_r) == m)) begin + ram_read[b][m] = 1'b1; + ram_raddr[b][m] = load_g; + end else if (load && sfb_rd && (32'(sfb_blk) == b) && (m == 1)) begin + // MX: a B-scale row, on the RAM the M-step-0 step leaves free + ram_read[b][m] = 1'b1; + ram_raddr[b][m] = sfb_g; + end + // tc.cp: the fragment row of the LMEM bank row bound for this + // RAM (with one fragment per bank row, plain wiring) + for (int q = 0; q < CP_FRAGS; ++q) begin + if (q == 0 || (((cp_f0 + 32'(q)) / 2) % BLOCK_SIZE == b && (cp_f0 + 32'(q)) % 2 == m)) begin + cp_wdata[b][m] = cp_lmem_if.rsp_data.data[q * NT * 32 +: NT * 32]; + end + end + // write: D write-back, else a tc.cp row, else a transfer; + // the data select is a store's when nothing writes + ram_wsel[b][m] = xf_wr_frag[b] ? WS_FRAG : WS_LPT; + if (jres_valid[b] && (32'(wq_head[b][GW]) == m)) begin + ram_write[b][m] = 1'b1; + ram_wren[b][m] = '1; + ram_waddr[b][m] = wq_head[b][GW-1:0]; + ram_wsel[b][m] = WS_WB; + end else if (cp_wr_blk[b]) begin + ram_wsel[b][m] = WS_CP; + for (int q = 0; q < CP_FRAGS; ++q) begin + if (((cp_f0 + 32'(q)) / 2) % BLOCK_SIZE == b && (cp_f0 + 32'(q)) % 2 == m) begin + ram_write[b][m] = 1'b1; + ram_wren[b][m] = '1; + ram_waddr[b][m] = cp_g; + end + end + end else if (xf_wr[b] && xf_wr_m[b][m]) begin + ram_write[b][m] = 1'b1; + ram_wren[b][m] = xf_wr_en[b][m]; + ram_waddr[b][m] = xf_wr_g[b]; + end + end + end + end + + for (genvar b = 0; b < BLOCK_SIZE; ++b) begin : g_wd + for (genvar m = 0; m < M_STEPS; ++m) begin : g_wdm + wire [1:0] ws = ram_wsel[b][m]; + for (genvar w = 0; w < NT; ++w) begin : g_wdw + assign ram_wdata[b][m][w] = ws[1] ? (ws[0] ? xf_wd_lpt[b][m][w] : xf_wd_frag[b][m][w]) + : (ws[0] ? cp_wdata[b][m][w] : jres_data[b][w]); + end + end + end + + // ----------------------------------------------------------------------- + // Commit arrivals + // ----------------------------------------------------------------------- + + wire [SCNTW-1:0] cmq_head_tgt = cmq_tgt_r[cmq_head_r]; + wire [SCNTW-1:0] cmq_slack = steps_done_r - cmq_head_tgt; // >= 0 once its steps are done + wire cm_ready = (cmq_count_r != 0) && ~cmq_slack[SCNTW-1]; + tcu_bar_t bar_req; + always_comb begin + bar_req = '0; + bar_req.addr = cmq_bar_r[cmq_head_r]; + bar_req.size_m1 = cmq_cnt_r[cmq_head_r]; + end + assign tcu_bar_if.req_valid = cm_ready; + assign tcu_bar_if.req_data = bar_req; + wire cm_fire = cm_ready && tcu_bar_if.req_ready; + + // the commits posted this cycle: by the op leaving the engine, or a marker + wire [1:0] post_n = run_leaves ? rj.ncommit : (marker_post ? head.ncommit : 2'd0); + tc_op_t post_src; + assign post_src = run_leaves ? rj : head; + `UNUSED_VAR (post_src) + // the step leaving with load_last counts toward its own commits + wire [SCNTW-1:0] post_tgt = steps_issued_r + SCNTW'(load && load_last); + + // ----------------------------------------------------------------------- + // State update + // ----------------------------------------------------------------------- + + always_ff @(posedge clk) begin + if (reset) begin + opq_head_r <= '0; + opq_tail_r <= '0; + opq_count_r <= '0; + run_valid_r <= 1'b0; + run_go_r <= 1'b0; + e_valid_r <= 1'b0; + pro_idx_r <= '0; + pro_rsp_valid_r<= 1'b0; + steps_issued_r <= '0; + steps_done_r <= '0; + cmq_head_r <= '0; + cmq_tail_r <= '0; + cmq_count_r <= '0; + wb_v_r <= '0; + wb_head_r <= '0; + wb_tail_r <= '0; + amap_r <= '0; + c_rsp_valid_r <= 1'b0; + cp_req_r <= '0; + cp_rsp_r <= '0; + cp_inflight_r <= 1'b0; + end else begin + // central port + if (c_go) begin + c_rsp_valid_r <= 1'b1; + end else if (|c_rsp_take) begin + c_rsp_valid_r <= 1'b0; + end + if (c_go && c_alloc) begin + amap_r <= amap_r | (c_amask << afit_idx); + for (int i = 0; i < ACHUNKS; ++i) begin + if (1'(((c_amask << afit_idx) >> i) & ACHUNKS'(1))) aown_r[i] <= cop.header.cta_id; + end + end else if (c_go && c_free) begin + amap_r <= amap_r & ~(c_amask << free_idx); + end else if (cta_exit_valid) begin + for (int i = 0; i < ACHUNKS; ++i) begin + if (aown_r[i] == cta_exit_id) amap_r[i] <= 1'b0; + end + end + + // op queue + if (c_push) begin + opq_cm_r[opq_tail_r] <= c_entry[CMW-1:0]; + opq_tail_r <= opq_tail_r + OPQW'(1); + end + if (c_attach) begin + if (young_in_q) begin + opq_cm_r[opq_last].bar[young_ncommit[0]] <= bar_addr(cs1); + opq_cm_r[opq_last].cnt[young_ncommit[0]] <= BAR_SIZE_W'(cs2 - 32'd1); + opq_cm_r[opq_last].ncommit <= young_ncommit + 2'd1; + end else begin + run_op_r.bar[young_ncommit[0]] <= bar_addr(cs1); + run_op_r.cnt[young_ncommit[0]] <= BAR_SIZE_W'(cs2 - 32'd1); + run_op_r.ncommit <= young_ncommit + 2'd1; + end + end + if (opq_pop) begin + opq_head_r <= opq_head_r + OPQW'(1); + end + opq_count_r <= opq_count_r + (OPQW+1)'(c_push) - (OPQW+1)'(opq_pop); + + // posted commits + if (post_n != 0) begin + for (int c = 0; c < 2; ++c) begin + if (c < int'(post_n)) begin + cmq_bar_r[cmq_tail_r + CMQW'(c)] <= post_src.bar[c]; + cmq_cnt_r[cmq_tail_r + CMQW'(c)] <= post_src.cnt[c]; + cmq_tgt_r[cmq_tail_r + CMQW'(c)] <= post_tgt; + end + end + cmq_tail_r <= cmq_tail_r + CMQW'(post_n); + end + if (cm_fire) begin + cmq_head_r <= cmq_head_r + CMQW'(1); + end + cmq_count_r <= cmq_count_r + (CMQW+1)'(post_n) - (CMQW+1)'(cm_fire); + + // steps and their write-backs + if (job_fire) begin + steps_issued_r <= steps_issued_r + SCNTW'(1); + wb_v_r[wb_tail_r] <= 1'b1; + wb_key_r[wb_tail_r] <= {e_m_r, e_g_r}; + wb_tail_r <= wb_tail_r + 1; + end + if (jres_valid[0]) begin + steps_done_r <= steps_done_r + SCNTW'(1); + wb_v_r[wb_head_r] <= 1'b0; + wb_head_r <= wb_head_r + 1; + end + + // prologue + pro_rsp_valid_r <= pro_go; + if (pro_go) begin + pro_idx_r <= pro_idx_r + 4'd1; + pro_rsp_meta_r <= pro_meta; + pro_rsp_idx_r <= pro_a_idx; + end + + // step register + if (load) begin + e_valid_r <= 1'b1; + e_m_r <= run_m_r; + e_sn_r <= run_n_r; + e_g_r <= load_g; + e_uuid_r <= rj.uuid; + e_wid_r <= rj.wid; + e_cta_r <= rj.cta; + e_fmt_s_r <= r_fmt_s; + e_lda_r <= r_lda; + e_ldb_r <= r_ldb; + e_a_tmem_r <= r_a_tmem; + e_sparse_r <= r_sparse; + for (int b = 0; b < BLOCK_SIZE; ++b) begin + e_a_off_r[b] <= r_a_off + 18'(32'(b) * XM * 32'(r_lda)); + end + e_b_off_r <= r_b_off; + e_first_r <= (run_m_r == 1'b0) && (run_n_r == 8'd0); + e_zero_r <= r_acc_init; + end else if (job_fire) begin + e_valid_r <= 1'b0; + end + + // walk m (inner), then n + if (load) begin + if (~load_m_last) begin + run_m_r <= 1'b1; + end else begin + run_m_r <= 1'b0; + if (~load_last) begin + run_n_r <= run_n_r + 8'd1; + end + end + end + + // tc.cp + if (cp_fire) begin + cp_req_r <= cp_req_r + 16'd1; + cp_inflight_r <= 1'b1; + end else if (cp_rsp) begin + cp_inflight_r <= 1'b0; + end + if (cp_rsp) begin + cp_rsp_r <= cp_rsp_r + 16'd1; + end + + // the engine + if (run_leaves) begin + run_valid_r <= 1'b0; + run_go_r <= 1'b0; + end + if (run_valid_r && ~run_go_r) begin + run_go_r <= 1'b1; // the descriptors take a cycle + end + if (start) begin + run_valid_r <= 1'b1; + run_go_r <= 1'b0; + run_op_r <= head; + run_m_r <= 1'b0; + run_n_r <= 8'd0; + pro_idx_r <= 4'd0; + cp_req_r <= '0; + cp_rsp_r <= '0; + end + end + if (c_go) begin + c_rsp_blk_r <= c_sel; + c_rsp_header_r <= cop.header; + c_rsp_value_r <= c_alloc ? (32'(afit_idx) * ACOLS) : 32'd0; + end + end + + // ----------------------------------------------------------------------- + // Descriptor checks + // ----------------------------------------------------------------------- + + wire [31:0] c_d_end = 32'(cs1[22:15]) * TC_N + (32'(cs1[14:8]) + 1) * TC_N; + wire mma_bad = 1'b0 + `ifndef VX_CFG_TCU_SPARSE_ENABLE + || cs1[5] + `endif + || (c_d_end > COLS) + || (cs1[5] && ((32'(cs1[31:23]) % TC_N) != 0 || 32'(cs1[31:23]) + TC_N > COLS)) + || (cs1[6] && ((cs2 % TC_N) != 0 || cs2 + TCU_WG_FEDP_K > COLS)) + || (~cs1[6] && cs2[31:TCU_SMEM_DESC_OFF_BITS] == 0) + || (cs3[31:TCU_SMEM_DESC_OFF_BITS] == 0); + wire cp_bad = (cs1[31:16] == 0) || (32'(cs1[31:16]) % TC_N != 0) || (32'(cs1[15:0]) % TC_N != 0) + || (cs2 % (CP_ROW_WORDS * 4) != 0) || ((32'(cs1[31:16]) * LANES) % CP_ROW_WORDS != 0) + || (32'(cs1[15:0]) + 32'(cs1[31:16]) > COLS); + `RUNTIME_ASSERT (~(c_push && (c_mma ? mma_bad : (c_cp ? cp_bad : 1'b0))), + ("%t: %s: unsupported tensor op (cta=%0d)", $time, INSTANCE_ID, cop.header.cta_id)) + +`ifdef PERF_ENABLE + // Each cycle counts once: an MMA step, else a running op's operand wait, + // else posted commits or a copy, else idle. + wire perf_is_opnd = ~job_fire && (is_mma_run || e_valid_r); + wire perf_is_other = ~job_fire && ~perf_is_opnd && ((cmq_count_r != 0) || is_cp_run); + logic [PERF_CTR_BITS-1:0] perf_busy_r, perf_opnd_r, perf_other_r, perf_idle_r, perf_xfers_r; + always_ff @(posedge clk) begin + if (reset) begin + perf_busy_r <= '0; + perf_opnd_r <= '0; + perf_other_r <= '0; + perf_idle_r <= '0; + perf_xfers_r <= '0; + end else begin + if (job_fire) perf_busy_r <= perf_busy_r + PERF_CTR_BITS'(BLOCK_SIZE); + else if (perf_is_opnd) perf_opnd_r <= perf_opnd_r + PERF_CTR_BITS'(1); + else if (perf_is_other) perf_other_r <= perf_other_r + PERF_CTR_BITS'(1); + else perf_idle_r <= perf_idle_r + PERF_CTR_BITS'(1); + perf_xfers_r <= perf_xfers_r + PERF_CTR_BITS'($countones(xfer_fire)); + end + end + assign perf_busy = perf_busy_r; + assign perf_opnd = perf_opnd_r; + assign perf_other = perf_other_r; + assign perf_idle = perf_idle_r; + assign perf_xfers = perf_xfers_r; +`endif + +`ifdef DBG_TRACE_TCU + always @(posedge clk) begin + if (c_push && c_mma) + `TRACE(3, ("%t: %s tc-mma: cta=%0d, idesc=0x%0h, a=0x%0h, b=0x%0h\n", + $time, INSTANCE_ID, cop.header.cta_id, cs1, cs2, cs3)) + if (c_push && c_cp) + `TRACE(3, ("%t: %s tc-cp: cta=%0d, cols=%0d, taddr=%0d\n", + $time, INSTANCE_ID, cop.header.cta_id, cs1[31:16], cs1[15:0])) + if (cm_fire) + `TRACE(3, ("%t: %s tc-commit: addr=%0d\n", $time, INSTANCE_ID, bar_req.addr)) + if (start) + `TRACE(3, ("%t: %s tc-run: cta=%0d\n", $time, INSTANCE_ID, head.cta)) + end +`endif + +endmodule + +`endif // VX_CFG_TCU_TMEM_ENABLE diff --git a/hw/rtl/tcu/VX_tcu_unit.sv b/hw/rtl/tcu/VX_tcu_unit.sv index b9547072a7..250976cb1c 100644 --- a/hw/rtl/tcu/VX_tcu_unit.sv +++ b/hw/rtl/tcu/VX_tcu_unit.sv @@ -36,6 +36,11 @@ module VX_tcu_unit import VX_gpu_pkg::*, VX_tcu_pkg::*; #( VX_lsu_sched_if.master tcu_mem_if [`VX_CFG_NUM_LSU_BLOCKS], `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + // per-block ports of the core's tensor memory (VX_tcu_shared) + VX_tcu_job_if.block job_if [`VX_CFG_NUM_TCU_BLOCKS], +`endif + // Inputs VX_dispatch_if.slave dispatch_if [`VX_CFG_ISSUE_WIDTH], @@ -168,6 +173,9 @@ module VX_tcu_unit import VX_gpu_pkg::*, VX_tcu_pkg::*; #( `endif `ifdef TCU_META_ENABLE .tcu_mem_if (block_mem_if[block_idx]), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .job_if (job_if[block_idx]), `endif .execute_if (per_block_execute_if[block_idx]), .result_if (per_block_result_if[block_idx]) diff --git a/hw/rtl/tcu/VX_tcu_uops.sv b/hw/rtl/tcu/VX_tcu_uops.sv index 996e1c7dc2..2a5b8bd4fd 100644 --- a/hw/rtl/tcu/VX_tcu_uops.sv +++ b/hw/rtl/tcu/VX_tcu_uops.sv @@ -47,7 +47,7 @@ module VX_tcu_uops import VX_tcu_pkg::*, VX_gpu_pkg::*; ( // The extra bit reads as zero (the counter never reaches it under the // sparse uop count). localparam IDX_BITS = LG_N + LG_M + LG_K; -`ifdef VX_CFG_TCU_WGMMA_ENABLE +`ifdef TCU_WARP_WGMMA `ifdef VX_CFG_TCU_SPARSE_ENABLE localparam TCU_WG_K_STEPS_SP = (TCU_WG_K_STEPS > 1) ? (TCU_WG_K_STEPS / 2) : 1; localparam MAX_WG_UOPS_SP = TCU_WG_M_STEPS * TCU_WG_N_STEPS * TCU_WG_K_STEPS_SP; @@ -81,7 +81,7 @@ module VX_tcu_uops import VX_tcu_pkg::*, VX_gpu_pkg::*; ( // Truncate the wide uop_idx to the bits this expander actually uses. wire [`UP(CTR_W)-1:0] ctr = `UP(CTR_W)'(uop_idx); -`ifdef VX_CFG_TCU_WGMMA_ENABLE +`ifdef TCU_WARP_WGMMA // is_sparse is derived from op_type (INST_TCU_*_SP variants). wire is_wgmma = (ibuf_in.op_type == INST_TCU_WGMMA) `ifdef VX_CFG_TCU_SPARSE_ENABLE @@ -213,16 +213,25 @@ module VX_tcu_uops import VX_tcu_pkg::*, VX_gpu_pkg::*; ( `ifdef VX_CFG_TCU_SPARSE_ENABLE // is_sparse covers WMMA_SP (and WGMMA_SP, since the WGMMA path branches earlier). wire is_sparse = (ibuf_in.op_type == INST_TCU_WMMA_SP) - `ifdef VX_CFG_TCU_WGMMA_ENABLE + `ifdef TCU_WARP_WGMMA || (ibuf_in.op_type == INST_TCU_WGMMA_SP) `endif ; `endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + wire is_tmem = (ibuf_in.op_type == INST_TCU_TMEM_LD) + || (ibuf_in.op_type == INST_TCU_TMEM_ST); + wire [4:0] tmem_idx = 5'(uop_idx); +`endif + // Dense FEDP2K RS adds one descriptor setup uop. Other WGMMA modes fuse // descriptor transport into their first compute uop. assign uop_count = -`ifdef VX_CFG_TCU_WGMMA_ENABLE +`ifdef VX_CFG_TCU_TMEM_ENABLE + is_tmem ? (UOP_CTR_W'(ibuf_in.op_args.tcu.fmt_s) + UOP_CTR_W'(1)) : +`endif +`ifdef TCU_WARP_WGMMA is_wgmma ? wg_uop_cnt : `endif `ifdef VX_CFG_TCU_SPARSE_ENABLE @@ -333,7 +342,18 @@ module VX_tcu_uops import VX_tcu_pkg::*, VX_gpu_pkg::*; ( n_sp_s = '0; m_sp_s = '0; `endif - `ifdef VX_CFG_TCU_WGMMA_ENABLE + `ifdef VX_CFG_TCU_TMEM_ENABLE + if (is_tmem) begin + // Uop i moves register (base + i); fmt_d carries i to the TMEM port. + ibuf_r.op_args.tcu.fmt_d = tmem_idx; + if (ibuf_in.op_type == INST_TCU_TMEM_LD) begin + ibuf_r.rd = ibuf_in.rd + NUM_REGS_BITS'(tmem_idx); + end else begin + ibuf_r.rs2 = ibuf_in.rs2 + NUM_REGS_BITS'(tmem_idx); + end + end else + `endif + `ifdef TCU_WARP_WGMMA if (is_wgmma) begin ibuf_r.op_args.tcu.step_m = is_wg_setup_uop ? 4'd0 : 4'(wg_m_index); ibuf_r.op_args.tcu.step_n = is_wg_setup_uop ? 4'd0 : 4'(wg_n_index); @@ -402,7 +422,7 @@ module VX_tcu_uops import VX_tcu_pkg::*, VX_gpu_pkg::*; ( ibuf_r.used_rs[2] = 1'b1; `endif end - `ifdef VX_CFG_TCU_WGMMA_ENABLE + `ifdef TCU_WARP_WGMMA if (is_wgmma) begin ibuf_r.fu_lock = (uop_idx == '0); ibuf_r.fu_unlock = (uop_idx == (uop_count - UOP_CTR_W'(1))); diff --git a/hw/rtl/tcu/VX_tcu_wgmma.sv b/hw/rtl/tcu/VX_tcu_wgmma.sv index 4df2e33579..18a0e2c67a 100644 --- a/hw/rtl/tcu/VX_tcu_wgmma.sv +++ b/hw/rtl/tcu/VX_tcu_wgmma.sv @@ -45,6 +45,15 @@ module VX_tcu_wgmma import VX_gpu_pkg::*, VX_tcu_pkg::*; #( // Bank-parallel LMEM read port. VX_mem_bus_if.master tcu_lmem_if, +`ifdef VX_CFG_TCU_TMEM_ENABLE + // Tensor-job steps own the tile buffers; warps do not issue WGMMA. + input tcu_tbuf_req_t [BLOCK_SIZE-1:0] job_req, + input wire job_a_fill_valid, + input wire [3:0] job_a_fill_idx, + input wire [BLOCK_SIZE-1:0][TCU_WG_TILE_M-1:0][TCU_TC_N-1:0][31:0] job_a_fill_data, + VX_mem_bus_if.slave job_cp_lmem_if, +`endif + // Outputs to tcu_core (consumed by the wrapper). output wire [BLOCK_SIZE-1:0][TCU_WG_A_DATA_SIZE-1:0][`VX_CFG_XLEN-1:0] tbuf_rs1_data, output wire [BLOCK_SIZE-1:0][TCU_WG_RS2_WIDTH-1:0][`VX_CFG_XLEN-1:0] tbuf_rs2_data, @@ -92,6 +101,7 @@ module VX_tcu_wgmma import VX_gpu_pkg::*, VX_tcu_pkg::*; #( assign is_last_uop_b_w[bi] = is_wgmma_op && exec_data[bi].op_args.tcu.is_last_uop; end +`ifdef TCU_WARP_WGMMA always_ff @(posedge clk) begin if (reset) begin desc_a_r <= '0; @@ -108,7 +118,15 @@ module VX_tcu_wgmma import VX_gpu_pkg::*, VX_tcu_pkg::*; #( end end end +`else + assign desc_a_r = '0; + assign desc_b_r = '0; +`endif +`ifdef VX_CFG_TCU_TMEM_ENABLE + assign cta_conflict = '0; + `UNUSED_VAR ({is_wgmma_b_w, new_cta_b_w, exec_fire_b_w, is_last_uop_b_w}) +`else VX_tcu_lockstep #( .INSTANCE_ID (`SFORMATF(("%s-lockstep", INSTANCE_ID))), .BLOCK_SIZE (BLOCK_SIZE) @@ -122,6 +140,7 @@ module VX_tcu_wgmma import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .is_last_uop_b (is_last_uop_b_w), .cta_conflict (cta_conflict) ); +`endif // ----------------------------------------------------------------------- // Per-block uop observation → VX_tcu_tbuf request. @@ -144,7 +163,7 @@ module VX_tcu_wgmma import VX_gpu_pkg::*, VX_tcu_pkg::*; #( assign req[bi].cta_id = exec_data[bi].header.cta_id; assign req[bi].step_m = exec_data[bi].op_args.tcu.step_m; assign req[bi].step_k = exec_data[bi].op_args.tcu.step_k; - assign req[bi].step_n = exec_data[bi].op_args.tcu.step_n; + assign req[bi].step_n = TCU_TBUF_N_W'(exec_data[bi].op_args.tcu.step_n); assign req[bi].cd_nregs = exec_data[bi].op_args.tcu.cd_nregs; wire use_live_desc = is_first_uop_b_w[bi] && !needs_setup_b_w[bi]; @@ -180,17 +199,31 @@ module VX_tcu_wgmma import VX_gpu_pkg::*, VX_tcu_pkg::*; #( .tbuf_cache_hits(tbuf_cache_hits_w), .lmem_reads (lmem_reads_w), `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .req (job_req), + .a_fill_valid (job_a_fill_valid), + .a_fill_idx (job_a_fill_idx), + .a_fill_data (job_a_fill_data), + .tcu_cp_lmem_if (job_cp_lmem_if), + `else .req (req), + `endif .tcu_lmem_if (tcu_lmem_if), .tbuf_rs1_data (tbuf_rs1_data), .tbuf_rs2_data (tbuf_rs2_data), .tbuf_ready (tbuf_ready) ); +`ifdef VX_CFG_TCU_TMEM_ENABLE + assign tbuf_ready_eff = tbuf_ready; + `UNUSED_VAR (req) + `UNUSED_VAR (cta_conflict) +`else for (genvar bi = 0; bi < BLOCK_SIZE; ++bi) begin : g_tbuf_eff assign tbuf_ready_eff[bi] = is_setup_uop_b_w[bi] ? 1'b1 : (tbuf_ready[bi] && !cta_conflict[bi]); end +`endif // ----------------------------------------------------------------------- // WGMMA perf counters (instrs / stalls). @@ -227,6 +260,11 @@ module VX_tcu_wgmma import VX_gpu_pkg::*, VX_tcu_pkg::*; #( end assign tcu_perf.wgmma_instrs = wgmma_instrs_ctr_r; assign tcu_perf.wgmma_stalls = wgmma_stalls_ctr_r; + assign tcu_perf.mma_busy = '0; + assign tcu_perf.opnd_waits = '0; + assign tcu_perf.job_other = '0; + assign tcu_perf.idle = '0; + assign tcu_perf.tmem_xfers = '0; `endif endmodule diff --git a/hw/syn/xilinx/dut/catalog.mk b/hw/syn/xilinx/dut/catalog.mk index 6eb5bc7d21..218e2cdef7 100644 --- a/hw/syn/xilinx/dut/catalog.mk +++ b/hw/syn/xilinx/dut/catalog.mk @@ -11,7 +11,7 @@ # directory, no dispatcher edit. DUTS := cache core cp dxa fpu gfx gfxvm issue lmem mem_unit tfu om raster rtu \ - scope tcu tensor tex top vm vortex + scope tcu tcuw tensor tex top vm vortex # --------------------------------------------------------------------------- # shared include fragments @@ -127,6 +127,13 @@ tcu_CFG := -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_F_DISABLE tcu_INC = $(BASE_INC) -I$(RTL_DIR)/core -I$(RTL_DIR)/mem -I$(RTL_DIR)/vm -I$(UNITTEST_DIR)/tcu_unit $(TCU_INC) tcu_PKG = $(TCU_PKG) +# The tensor-core unit at any issue width, with tensor memory when enabled. +tcuw_PRJ := VX_tcu_wide_top +tcuw_IP := 1 +tcuw_CFG := -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_F_DISABLE +tcuw_INC = $(BASE_INC) -I$(RTL_DIR)/core -I$(RTL_DIR)/mem -I$(RTL_DIR)/vm -I$(UNITTEST_DIR)/tcu_unit $(TCU_INC) +tcuw_PKG = $(TCU_PKG) + tensor_PRJ := VX_tensor_top tensor_IP := 1 tensor_CFG := -DVX_CFG_EXT_TCU_ENABLE -DVX_CFG_EXT_DXA_ENABLE -DVX_CFG_TCU_WGMMA_ENABLE \ diff --git a/hw/unittest/tcu_unit/VX_tcu_wide_top.sv b/hw/unittest/tcu_unit/VX_tcu_wide_top.sv new file mode 100644 index 0000000000..578288d244 --- /dev/null +++ b/hw/unittest/tcu_unit/VX_tcu_wide_top.sv @@ -0,0 +1,165 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +`include "VX_define.vh" + +// Synthesis wrapper of the tensor-core unit at any issue width: VX_tcu_unit +// plus VX_tcu_shared (tile buffers and, with VX_CFG_TCU_TMEM_ENABLE, tensor +// memory), every dispatch slot, commit slot and memory port at a top-level +// port so nothing is optimized away. +module VX_tcu_wide_top import VX_gpu_pkg::*, VX_tcu_pkg::*; ( + `SCOPE_IO_DECL + + input wire clk, + input wire reset, + +`ifdef VX_CFG_TCU_WGMMA_ENABLE + output wire tcu_lmem_req_valid, + input wire tcu_lmem_req_ready, + output wire [`VX_CFG_LMEM_LOG_SIZE-`CLOG2(LSU_WORD_SIZE)-`CLOG2(`VX_CFG_LMEM_NUM_BANKS)-1:0] tcu_lmem_req_addr, + input wire tcu_lmem_rsp_valid, + input wire [`VX_CFG_LMEM_NUM_BANKS*`VX_CFG_XLEN-1:0] tcu_lmem_rsp_data, +`endif + +`ifdef TCU_META_ENABLE + output wire [`VX_CFG_NUM_LSU_BLOCKS-1:0] tcu_mem_req_valid, + input wire [`VX_CFG_NUM_LSU_BLOCKS-1:0] tcu_mem_req_ready, + output wire [`VX_CFG_NUM_LSU_BLOCKS-1:0][$bits(lsu_req_data_t)-1:0] tcu_mem_req_data, + input wire [`VX_CFG_NUM_LSU_BLOCKS-1:0] tcu_mem_rsp_valid, + output wire [`VX_CFG_NUM_LSU_BLOCKS-1:0] tcu_mem_rsp_ready, + input wire [`VX_CFG_NUM_LSU_BLOCKS-1:0][$bits(lsu_rsp_data_t)-1:0] tcu_mem_rsp_data, +`endif + +`ifdef VX_CFG_TCU_TMEM_ENABLE + output wire tcu_bar_valid, + output wire [$bits(tcu_bar_t)-1:0] tcu_bar_data, + input wire tcu_bar_ready, + input wire cta_exit_valid, + input wire [NCTA_WIDTH-1:0] cta_exit_id, +`endif + + input wire [`VX_CFG_ISSUE_WIDTH-1:0] dispatch_valid, + output wire [`VX_CFG_ISSUE_WIDTH-1:0] dispatch_ready, + input wire [`VX_CFG_ISSUE_WIDTH-1:0][$bits(dispatch_t)-1:0] dispatch_data, + + output wire [`VX_CFG_ISSUE_WIDTH-1:0] commit_valid, + input wire [`VX_CFG_ISSUE_WIDTH-1:0] commit_ready, + output wire [`VX_CFG_ISSUE_WIDTH-1:0][$bits(commit_t)-1:0] commit_data +); +`ifdef VX_CFG_TCU_WGMMA_ENABLE + localparam TCU_LMEM_BANK_ADDR_W = `VX_CFG_LMEM_LOG_SIZE - `CLOG2(LSU_WORD_SIZE) - `CLOG2(`VX_CFG_LMEM_NUM_BANKS); + + VX_mem_bus_if #( + .DATA_SIZE (`VX_CFG_LMEM_NUM_BANKS * (`VX_CFG_XLEN / 8)), + .TAG_WIDTH (UUID_WIDTH), + .ADDR_WIDTH (TCU_LMEM_BANK_ADDR_W) + ) tcu_lmem_if(); + + assign tcu_lmem_req_valid = tcu_lmem_if.req_valid; + assign tcu_lmem_if.req_ready = tcu_lmem_req_ready; + assign tcu_lmem_req_addr = tcu_lmem_if.req_data.addr; + assign tcu_lmem_if.rsp_valid = tcu_lmem_rsp_valid; + assign tcu_lmem_if.rsp_data.data = tcu_lmem_rsp_data; + assign tcu_lmem_if.rsp_data.tag = '0; + `UNUSED_VAR (tcu_lmem_if.req_data) + `UNUSED_VAR (tcu_lmem_if.rsp_ready) +`endif + +`ifdef TCU_META_ENABLE + VX_lsu_sched_if tcu_mem_if [`VX_CFG_NUM_LSU_BLOCKS](); + for (genvar i = 0; i < `VX_CFG_NUM_LSU_BLOCKS; ++i) begin : g_mem + assign tcu_mem_req_valid[i] = tcu_mem_if[i].req_valid; + assign tcu_mem_req_data[i] = tcu_mem_if[i].req_data; + assign tcu_mem_if[i].req_ready = tcu_mem_req_ready[i]; + assign tcu_mem_if[i].rsp_valid = tcu_mem_rsp_valid[i]; + assign tcu_mem_if[i].rsp_data = tcu_mem_rsp_data[i]; + assign tcu_mem_rsp_ready[i] = tcu_mem_if[i].rsp_ready; + end +`endif + +`ifdef VX_CFG_TCU_TMEM_ENABLE + VX_tcu_job_if job_if [`VX_CFG_NUM_TCU_BLOCKS](); + VX_tcu_bar_if tcu_bar_if(); + assign tcu_bar_valid = tcu_bar_if.req_valid; + assign tcu_bar_data = tcu_bar_if.req_data; + assign tcu_bar_if.req_ready = tcu_bar_ready; +`endif + + VX_dispatch_if dispatch_if[`VX_CFG_ISSUE_WIDTH](); + VX_commit_if commit_if [`VX_CFG_ISSUE_WIDTH](); + + for (genvar i = 0; i < `VX_CFG_ISSUE_WIDTH; ++i) begin : g_slots + assign dispatch_if[i].valid = dispatch_valid[i]; + assign dispatch_if[i].data = dispatch_data[i]; + assign dispatch_ready[i] = dispatch_if[i].ready; + assign commit_valid[i] = commit_if[i].valid; + assign commit_data[i] = commit_if[i].data; + assign commit_if[i].ready = commit_ready[i]; + end + +`ifdef VX_CFG_TCU_WGMMA_ENABLE + wire [`VX_CFG_NUM_TCU_BLOCKS-1:0] tcu_exec_valid, tcu_exec_ready; + tcu_execute_t tcu_exec_data [`VX_CFG_NUM_TCU_BLOCKS]; + wire [`VX_CFG_NUM_TCU_BLOCKS-1:0][TCU_WG_A_DATA_SIZE-1:0][`VX_CFG_XLEN-1:0] tcu_tbuf_rs1_data; + wire [`VX_CFG_NUM_TCU_BLOCKS-1:0][TCU_WG_RS2_WIDTH-1:0][`VX_CFG_XLEN-1:0] tcu_tbuf_rs2_data; + wire [`VX_CFG_NUM_TCU_BLOCKS-1:0] tcu_tbuf_ready; +`endif + + VX_tcu_unit #( + .INSTANCE_ID ("tcu_wide_top") + ) tcu_unit ( + `SCOPE_IO_BIND (0) + .clk (clk), + .reset (reset), + `ifdef VX_CFG_TCU_WGMMA_ENABLE + .exec_valid (tcu_exec_valid), + .exec_ready (tcu_exec_ready), + .exec_data (tcu_exec_data), + .tbuf_rs1_data (tcu_tbuf_rs1_data), + .tbuf_rs2_data (tcu_tbuf_rs2_data), + .tbuf_ready (tcu_tbuf_ready), + `endif + `ifdef TCU_META_ENABLE + .tcu_mem_if (tcu_mem_if), + `endif + `ifdef VX_CFG_TCU_TMEM_ENABLE + .job_if (job_if), + `endif + .dispatch_if (dispatch_if), + .commit_if (commit_if) + ); + +`ifdef VX_CFG_TCU_WGMMA_ENABLE + VX_tcu_shared #( + .INSTANCE_ID ("tcu_wide_top"), + .BLOCK_SIZE (`VX_CFG_NUM_TCU_BLOCKS) + ) tcu_shared ( + .exec_valid (tcu_exec_valid), + .exec_ready (tcu_exec_ready), + .exec_data (tcu_exec_data), + .tbuf_rs1_data (tcu_tbuf_rs1_data), + .tbuf_rs2_data (tcu_tbuf_rs2_data), + .tbuf_ready_eff (tcu_tbuf_ready), + .tcu_lmem_if (tcu_lmem_if), + `ifdef VX_CFG_TCU_TMEM_ENABLE + .job_if (job_if), + .tcu_bar_if (tcu_bar_if), + .cta_exit_valid (cta_exit_valid), + .cta_exit_id (cta_exit_id), + `endif + .clk (clk), + .reset (reset) + ); +`endif + +endmodule diff --git a/profiles/b200.json b/profiles/b200.json new file mode 100644 index 0000000000..284832def0 --- /dev/null +++ b/profiles/b200.json @@ -0,0 +1,98 @@ +{ + "name": "b200", + "description": "NVIDIA B200 (two GB100 dies, Blackwell, sm_100) at 1980 MHz: one Vortex core per SM, with tensor memory.", + "xlen": 32, + "core": { + "VX_CFG_NUM_WARPS": 64, + "VX_CFG_NUM_THREADS": 32, + "VX_CFG_ISSUE_WIDTH": 4, + "VX_CFG_NUM_ALU_LANES": 16, + "VX_CFG_NUM_FPU_LANES": 32, + "VX_CFG_NUM_LSU_LANES": 8, + "VX_CFG_DCACHE_SIZE": 262144, + "VX_CFG_FETCH_WIDTH": 4, + "VX_CFG_LMEM_LOG_SIZE": 18, + "VX_CFG_LMEM_SIZE": 233472, + "VX_CFG_LMEM_NUM_BANKS": 32, + "VX_CFG_VM_ENABLE": true, + "VX_CFG_EXT_A_ENABLE": true, + "VX_CFG_EXT_ZACAS_ENABLE": true, + "VX_CFG_EXT_ZFHMIN_ENABLE": true, + "VX_CFG_EXT_TFU_ENABLE": true, + "VX_CFG_NUM_TFU_LANES": 16, + "VX_CFG_EXT_TCU_ENABLE": true, + "VX_CFG_TCU_TF32_ENABLE": true, + "VX_CFG_TCU_FP8_ENABLE": true, + "VX_CFG_TCU_FP4_ENABLE": true, + "VX_CFG_TCU_MX_ENABLE": true, + "VX_CFG_TCU_MXFP4_ENABLE": true, + "VX_CFG_TCU_NVFP4_ENABLE": true, + "VX_CFG_TCU_INT8_ENABLE": true, + "VX_CFG_TCU_SPARSE_ENABLE": true, + "VX_CFG_TCU_WGMMA_ENABLE": true, + "VX_CFG_TCU_FEDP2K": 1, + "VX_CFG_TCU_TMEM_ENABLE": true, + "VX_CFG_TCU_TMEM_COLS": 512, + "VX_CFG_EXT_DXA_ENABLE": true, + "VX_CFG_NUM_BARRIERS": 16, + "VX_CFG_FDIV_PE_RATIO": 8, + "VX_CFG_FSQRT_PE_RATIO": 8, + "VX_CFG_FCVT_PE_RATIO": 8, + "VX_CFG_DCACHE_NUM_BANKS": 4, + "VX_CFG_L1_LINK_LATENCY": 1 + }, + "chip": { + "VX_CFG_NUM_CLUSTERS": 1, + "VX_CFG_NUM_CORES": 148, + "VX_CFG_L2_ENABLE": true, + "VX_CFG_L2_SIZE": 132120576, + "VX_CFG_L2_NUM_WAYS": 63, + "VX_CFG_L2_NUM_BANKS": 128, + "VX_CFG_CP_LLC_CLIENT": 1, + "VX_CFG_L2_LINK_LATENCY": 102, + "VX_CFG_L2_MSHR_SIZE": 256 + }, + "platform": { + "VX_CFG_PLATFORM_MEMORY_NUM_BANKS": 64, + "VX_CFG_PLATFORM_CLOCK_RATE": 1980, + "VX_CFG_PLATFORM_MEMORY_PEAK_BW": 8000000, + "VX_CFG_PLATFORM_MEMORY_TYPE": "HBM3", + "VX_CFG_PLATFORM_MEMORY_DATA_RATE": 7813, + "VX_CFG_PLATFORM_MEMORY_LATENCY": 445 + }, + "reference": { + "fp32_lanes": 18944, + "dram_bandwidth_gbs": 8000, + "l1_hit_cycles": 39, + "l2_hit_cycles": 296, + "dram_cycles": 824 + }, + "sources": { + "NUM_CORES": "148 SMs across eight GPCs on the two dies, presented to software as one device (Microbenchmarking NVIDIA's Blackwell Architecture, arXiv 2512.02189, Sec. II)", + "NUM_WARPS, NUM_THREADS, ISSUE_WIDTH, FETCH_WIDTH": "64 resident warps per SM for compute capability 10.0 (NVIDIA Blackwell Tuning Guide); 32-thread warps; 4 SM processing blocks, each with its own scheduler, as on Hopper (the sub-partition count tcgen05's 4 x 32 TMEM lane quarters follow)", + "PLATFORM_CLOCK_RATE": "1980 MHz, derived from NVIDIA's FP32 peak: HGX B200 lists 600 TFLOPS FP32 for 8 GPUs, 75 TFLOPS per GPU = 148 SMs x 128 FP32 lanes x 2 FLOP x 1.98 GHz. Third-party listings disagree (1830-1980 MHz), so the vendor peak decides", + "NUM_ALU_LANES, NUM_FPU_LANES, NUM_LSU_LANES": "Compute capability 10.0 throughput per SM per clock (CUDA C++ Programming Guide 12.9, arithmetic instructions): 128 FP32, 64 INT32 add, the same as 9.0, so the h100 split carries over: one ALU/FPU/LSU block per processing block with 16 INT32 and 32 FP32 lanes. NVIDIA publishes no LD/ST unit count for sm_100; Hopper's 8 per processing block is kept", + "FP64": "Not modelled: XLEN=32 leaves out the D extension. B200 runs FP64 at half the FP32 rate (64 per SM per clock, compute capability 10.0 table), but ML workloads do not use it", + "FDIV_PE_RATIO, FSQRT_PE_RATIO, FCVT_PE_RATIO": "16 results per clock per SM for reciprocal, reciprocal square root and the 32-bit conversions (compute capability 10.0 table), 4 per processing block: 32 FPU lanes / 8", + "NUM_TFU_LANES": "16 special-function results per clock per SM for rcp, rsqrt, log2, exp2, sin, cos (compute capability 10.0 table)", + "VM_ENABLE, EXT_A_ENABLE, EXT_ZACAS_ENABLE, EXT_ZFHMIN_ENABLE, EXT_TFU_ENABLE": "Demand-paged MMU, global and shared-memory atomics with atomicCAS, FP16 storage and conversion, and per-partition special-function units for the transcendentals (TFU), as on every NVIDIA GPU since Pascal", + "EXT_TCU_ENABLE, TCU_*": "Fifth-generation tensor cores: FP16/BF16, TF32, FP8, FP6/FP4, MXFP8/MXFP6/MXFP4 and NVFP4 block scaling, INT8 (no INT4), 2:4 sparsity (HGX B200 specifications; arXiv 2512.02189 Sec. IV). Vortex has no FP6 format; MX covers the block-scaled types it has", + "TCU_FEDP2K": "Twice Hopper's dense tensor rate per SM: B200 2.25 PFLOPS FP16 (HGX: 36 PFLOPS sparse for 8 GPUs, dense half) = 7678 FLOP/clock/SM at 148 SMs and 1.98 GHz, against H100's 989 TFLOPS = 3786 at 132 SMs. FEDP2K doubles the FEDP's K, which h100 leaves off", + "TCU_WGMMA_ENABLE": "Required by Vortex's tensor memory, which uses the WGMMA tile buffers and operand path (VX_define.vh, SimX tcu_unit.cpp). Warps never issue WGMMA in a TMEM build, so, as on sm_100, there is no warpgroup MMA instruction", + "TCU_TMEM_ENABLE, TCU_TMEM_COLS": "'512 columns and 128 rows per CTA, with each cell being 32-bits' on sm_100a (PTX ISA 9.7.18.1); arXiv 2512.02189 Sec. III-A. cta_group::2 pairs two SMs' 128-lane TMEMs for M=256; it does not widen one SM's. Vortex derives its lanes from the TCU blocks x WGMMA M (4 x 16 = 64 at NT=32), so a core implements the sm_100 cta_group::1 M=64 shape, not M=128; only the 512 columns are set here", + "EXT_DXA_ENABLE": "The Tensor Memory Accelerator is the DXA; Vortex's tensor memory also requires it", + "NUM_BARRIERS": "16 named CTA barriers (bar.sync 0-15, PTX ISA)", + "EXT_TEX_ENABLE, EXT_RASTER_ENABLE, EXT_OM_ENABLE, EXT_RTU_ENABLE": "Off: a compute part, and no NVIDIA source describes texture units on B200", + "LMEM_SIZE, LMEM_LOG_SIZE, DCACHE_SIZE": "228 KB maximum shared memory per SM in a 256 KB combined L1/shared pool, the same as Hopper (NVIDIA Blackwell Tuning Guide, compute capability 10.0)", + "LMEM_NUM_BANKS": "32 banks of 4 B per clock, as every NVIDIA SM since Maxwell; Vortex banks are XLEN wide, 4 B at XLEN=32, so the count matches the part", + "DCACHE_NUM_BANKS": "NVIDIA publishes no L1 bandwidth for sm_100; Hopper's 128 B per clock (4 banks of the 32 B dcache word) is kept, as the L1/shared pool is unchanged", + "L2_SIZE, L2_NUM_WAYS": "126 MB L2 (NVIDIA Blackwell Tuning Guide): 63 ways over 32768 sets of 64 B lines, the power-of-two set count h100 uses", + "L2_NUM_BANKS": "Four L2 partitions, double Hopper's (arXiv 2512.02189 Sec. II): twice h100's 64 banks", + "CP_LLC_CLIENT": "Host copies reach device memory through the L2 like every other client", + "PLATFORM_MEMORY_TYPE, PLATFORM_MEMORY_NUM_BANKS, PLATFORM_MEMORY_DATA_RATE, PLATFORM_MEMORY_PEAK_BW": "8 HBM3e stacks (arXiv 2512.02189 Sec. II) at 8 TB/s per GPU (DGX B200: 64 TB/s for 8 GPUs). Modelled as 64 HBM3 channel pairs of 16 B at 7813 MT/s = 8.0 TB/s; the enum has no HBM3e, as for h200", + "L2_MSHR_SIZE": "256 per bank: Little's law on B200's L2-miss round trip (824 - 296 = 528 cycles) x 4040 B/cycle (8000 GB/s / 1980 MHz) / (128 banks x 64 B) = 260; 256 is the ceiling of the TOML's own derivation (98% of the requirement)", + "reference": "fp32_lanes = 148 SMs x 128 FP32 lanes; dram_bandwidth_gbs the vendor peak (DGX B200). Latencies: Chips and Cheese, 'Nvidia's B200: Keeping the CUDA Juggernaut Rolling' (2025), OpenCL pointer chase on a B200: L1 19.61 ns ('19.6 ns, or 39 cycles'), L2 149.65 ns in the near L2 partition, DRAM 416.00 ns at 2 GB, at 1980 MHz = 39, 296 and 824 cycles. The same test gives H100 PCIe 154.69 and 377.64 ns, which at its 1755 MHz boost are within 1% of h100's references from arXiv 2507.10789, so the two sources agree. The far L2 partition (316.19 ns past 64 MB) is not modelled: Vortex has one L2", + "L1_LINK_LATENCY, L2_LINK_LATENCY, PLATFORM_MEMORY_LATENCY": "1, 102 and 445 core cycles, calibrated with ci/profile_check.py so the one-core SimX pointer chase gives the B200's measured latencies in 'reference' (L1 37.9, L2 295.8, DRAM 823.7 cycles)", + "xlen": "32-bit machine: NVIDIA's per-thread registers are 32 bits (64-bit values take register pairs), and Vortex TMEM cells are 32 bits, so tmem.ld needs no NaN-boxing. XLEN=32 also means no FP64 (the D extension follows XLEN=64; ML workloads do not use it) and a 32-bit device address space (4 GB, against the part's 49-bit virtual addresses); configure --profile picks a build32 tree and a build64 tree rejects the profile" + } +} diff --git a/sim/simx/core.cpp b/sim/simx/core.cpp index f7e9726c8b..3c2e6b8af6 100644 --- a/sim/simx/core.cpp +++ b/sim/simx/core.cpp @@ -354,6 +354,9 @@ class Core::Impl { // its first read in the same cycle, seen by the LMEM the next. snprintf(sname, 100, "%s-tcu-tbuf", name.c_str()); tcu_unit_->set_tbuf(TcuTbuf::Create(sname)); + #ifdef VX_CFG_TCU_TMEM_ENABLE + scheduler_->cta_dispatcher()->cta_exit_out.bind(&tcu_unit_->cta_exit_in); + #endif #ifdef VX_CFG_TCU_WGMMA_ENABLE // Bind the TCU tile-buffer subsystem (TcuTbuf) to the LMEM DMA port, diff --git a/sim/simx/csr_unit.cpp b/sim/simx/csr_unit.cpp index 9291bf8a86..a0e429a5f4 100644 --- a/sim/simx/csr_unit.cpp +++ b/sim/simx/csr_unit.cpp @@ -245,6 +245,11 @@ Word CsrUnit::get_csr(uint32_t addr, uint32_t wid, uint32_t tid) { CSR_READ_64(VX_CSR_MPM_TCU_TBUF_STALLS, tcu_perf.tbuf_stalls); CSR_READ_64(VX_CSR_MPM_TCU_TBUF_CACHE_HITS, tcu_perf.tbuf_cache_hits); CSR_READ_64(VX_CSR_MPM_TCU_LMEM_READS, tcu_perf.lmem_reads); + CSR_READ_64(VX_CSR_MPM_TCU_MMA_BUSY, tcu_perf.mma_busy); + CSR_READ_64(VX_CSR_MPM_TCU_OPND_WAITS, tcu_perf.opnd_waits); + CSR_READ_64(VX_CSR_MPM_TCU_JOB_OTHER, tcu_perf.job_other); + CSR_READ_64(VX_CSR_MPM_TCU_IDLE, tcu_perf.idle); + CSR_READ_64(VX_CSR_MPM_TCU_TMEM_XFERS, tcu_perf.tmem_xfers); } } break; #endif diff --git a/sim/simx/cta_dispatcher.cpp b/sim/simx/cta_dispatcher.cpp index 3bd887829a..707ee2a111 100644 --- a/sim/simx/cta_dispatcher.cpp +++ b/sim/simx/cta_dispatcher.cpp @@ -16,6 +16,7 @@ #include #include "core.h" #include +#include #include #include @@ -25,6 +26,9 @@ CtaDispatcher::CtaDispatcher(const SimContext& ctx, const char* name, Core* core : SimObject(ctx, name) , bus_in(this, 1) , credit_out(this) +#ifdef VX_CFG_TCU_TMEM_ENABLE + , cta_exit_out(this) +#endif , core_(core) , num_threads_(VX_CFG_NUM_THREADS) , num_warps_(VX_CFG_NUM_WARPS) @@ -125,6 +129,12 @@ uint32_t CtaDispatcher::step(const WarpMask& active_warps, uint32_t* wids, cta_w } assert(slot_rem_warps_[retiring_[i].first] > 0); --slot_rem_warps_[retiring_[i].first]; + #ifdef VX_CFG_TCU_TMEM_ENABLE + // The CTA's last warp: its tensor-memory columns are freed with it. + if (slot_rem_warps_[retiring_[i].first] == 0) { + cta_exit_out.send(int32_t(retiring_[i].first), 1); + } + #endif retire_write |= (retiring_[i].second == now); retiring_.erase(retiring_.begin() + i); } @@ -151,6 +161,22 @@ uint32_t CtaDispatcher::step(const WarpMask& active_warps, uint32_t* wids, cta_w // same way to stay consistent. uint32_t stride = lmem_slot_pitch(next.lmem_size); uint32_t max_slots = usable_slots(stride); + #ifdef VX_CFG_TCU_TMEM_ENABLE + // A CTA's TMEM budget, a power-of-two run of 32-column chunks, counts + // toward occupancy like its LMEM: the resident CTAs' allocations fit. + if (next.tmem_cols != 0) { + uint32_t budget = 32; + while (budget < next.tmem_cols) { + budget <<= 1; + } + if (budget > VX_CFG_TCU_TMEM_COLS) { + std::cout << "Error: a CTA TMEM budget of " << next.tmem_cols << " columns exceeds the " + << VX_CFG_TCU_TMEM_COLS << " of a core" << std::endl; + std::abort(); + } + max_slots = std::min(max_slots, uint32_t(VX_CFG_TCU_TMEM_COLS / budget)); + } + #endif uint32_t k = next.cluster_dim[0] * next.cluster_dim[1] @@ -229,6 +255,13 @@ uint32_t CtaDispatcher::step(const WarpMask& active_warps, uint32_t* wids, cta_w cur_slot_ = base; lmem_addr_ = lmem_base_ + uint64_t(base) * stride; + #ifdef VX_CFG_TCU_TMEM_ENABLE + // A TMEM CTA's warps launch as runs of consecutive lanes from lane 0, so + // rank r lands on lane (TCU block) r % FETCH_WIDTH. + if (cta_.tmem_cols != 0) { + lane_rr_ = 0; + } + #endif slot_rem_warps_[base] = cta_size_; if (!is_single) { tail_slot_ = (base + 1) % max_slots; @@ -270,12 +303,24 @@ uint32_t CtaDispatcher::step(const WarpMask& active_warps, uint32_t* wids, cta_w uint32_t lane = (lane_rr_ + o) % VX_CFG_FETCH_WIDTH; int free_wid = -1; for (uint32_t wid = lane; wid < num_warps_; wid += VX_CFG_FETCH_WIDTH) { + #ifdef VX_CFG_TCU_TMEM_ENABLE + // A tensor-memory CTA's warp of rank r runs on TCU block r % ISSUE_WIDTH, + // whose TMEM lanes its tmem.ld/st reach. + if (cta_.tmem_cols != 0 && (wid % VX_CFG_ISSUE_WIDTH) != (rank_ % VX_CFG_ISSUE_WIDTH)) { + continue; + } + #endif if (!active_warps.test(wid) && !cta_wids_.test(wid)) { free_wid = int(wid); break; } } if (free_wid < 0) { + #ifdef VX_CFG_TCU_TMEM_ENABLE + if (cta_.tmem_cols != 0) { + break; + } + #endif continue; } // Skip the startup only if every lane this launch activates has already run it. diff --git a/sim/simx/cta_dispatcher.h b/sim/simx/cta_dispatcher.h index 395f5c32fb..a7a0ee5af3 100644 --- a/sim/simx/cta_dispatcher.h +++ b/sim/simx/cta_dispatcher.h @@ -53,6 +53,12 @@ class CtaDispatcher : public SimObject { // rests on explicit slot accounting rather than transport back-pressure. SimChannel credit_out; +#ifdef VX_CFG_TCU_TMEM_ENABLE + // A CTA's last warp has retired (its slot, the CTA id): the TCU frees the + // TMEM columns it still owns. + SimChannel cta_exit_out; +#endif + CtaDispatcher(const SimContext& ctx, const char* name, Core* core); ~CtaDispatcher(); diff --git a/sim/simx/decode.cpp b/sim/simx/decode.cpp index 0905cc5864..ba88144a65 100644 --- a/sim/simx/decode.cpp +++ b/sim/simx/decode.cpp @@ -1099,21 +1099,30 @@ Instr::Ptr Decoder::decode(uint32_t code, uint64_t uuid) { instr->set_fu_type(FUType::TCU); switch (funct3) { case 0: { // WMMA_SYNC / WMMA_SP_SYNC — single macro Instr, sequencer expands to micro-ops + #ifndef VX_CFG_TCU_WMMA_ENABLE + std::cout << "Error: WMMA on a core built without VX_CFG_TCU_WMMA_ENABLE" << std::endl; + std::abort(); + #endif uint32_t fmt_d = rd, fmt_s = rs1; bool is_sparse = (rs2 & 1) != 0; instr->set_op_type(is_sparse ? TcuType::WMMA_SP : TcuType::WMMA); - instr->set_args(IntrTcuArgs{0, 0, fmt_s, fmt_d, 0, 0, 0, 0, 0, 0}); + instr->set_args(IntrTcuArgs{0, 0, fmt_s, fmt_d, 0, 0, 0, 0, 0, 0, 0, 0, 0}); instr->set_fcsr_use(tcu_meta_reads(fmt_s, is_sparse), 0); instr->set_macro_op(); } break; #ifdef VX_CFG_TCU_WGMMA_ENABLE case 1: { // WGMMA_SYNC — single macro Instr, sequencer expands to micro-ops + #ifdef VX_CFG_TCU_TMEM_ENABLE + // A tensor-memory build has no warp WGMMA: the TCU's MMAs are tc.mma. + std::cout << "Error: WGMMA in a tensor-memory build" << std::endl; + std::abort(); + #endif uint32_t fmt_d = rd, fmt_s = rs1; bool is_sparse = (rs2 & 1) != 0; uint32_t cd_nregs = (rs2 >> 1) & 0x3; bool is_a_smem = (rs2 >> 3) & 1; instr->set_op_type(is_sparse ? TcuType::WGMMA_SP : TcuType::WGMMA); - instr->set_args(IntrTcuArgs{is_a_smem ? 1u : 0u, cd_nregs, fmt_s, fmt_d, 0, 0, 0, 0, 0, 0}); + instr->set_args(IntrTcuArgs{is_a_smem ? 1u : 0u, cd_nregs, fmt_s, fmt_d, 0, 0, 0, 0, 0, 0, 0, 0, 0}); instr->set_fcsr_use(tcu_meta_reads(fmt_s, is_sparse), 0); instr->set_macro_op(); } break; @@ -1123,11 +1132,15 @@ Instr::Ptr Decoder::decode(uint32_t code, uint64_t uuid) { uint32_t fmt_s = rs2; uint32_t slot = rd; instr->set_op_type(TcuType::TCU_LD); - instr->set_args(IntrTcuArgs{0, 0, fmt_s, slot, 0, 0, 0, 0, 0, 0}); + instr->set_args(IntrTcuArgs{0, 0, fmt_s, slot, 0, 0, 0, 0, 0, 0, 0, 0, 0}); // rs1 holds the warp-broadcast base address (real I-reg read). instr->set_src_reg(0, rs1, RegType::Integer); instr->set_fcsr_use(0, (rd & 0x10) ? Instr::FCSR_FRM : Instr::FCSR_FFLAGS); } break; + #else + case 2: + std::cout << "Error: TCU_LD on a core without the metadata store (per-warp MMAs with sparse or MX)" << std::endl; + std::abort(); #endif // TCU_META_ENABLE default: std::abort(); @@ -1137,6 +1150,68 @@ Instr::Ptr Decoder::decode(uint32_t code, uint64_t uuid) { case 2: std::cout << "Error: TCU instruction on a core built without VX_CFG_EXT_TCU_ENABLE" << std::endl; std::abort(); + #endif + #ifdef VX_CFG_TCU_TMEM_ENABLE + case 5: { + instr->set_fu_type(FUType::TCU); + IntrTcuArgs args{}; + switch (funct3) { + case 0: // TMEM_LD fd, (rs1), n: rd = first FP destination, rs2 = n-1 + case 4: // TMEM_LD.F: fragment shape + args.fmt_d = rd; + args.tmem_row = (funct3 == 4); + args.tmem_n = rs2 + 1; + instr->set_op_type(TcuType::TMEM_LD); + instr->set_src_reg(0, rs1, RegType::Integer); + instr->set_macro_op(); + break; + case 1: // TMEM_ST fs, (rs1), n: rd = first FP source, rs2 = n-1 + case 5: // TMEM_ST.F: fragment shape + args.fmt_s = rd; + args.tmem_row = (funct3 == 5); + args.tmem_n = rs2 + 1; + instr->set_op_type(TcuType::TMEM_ST); + instr->set_src_reg(0, rs1, RegType::Integer); + instr->set_macro_op(); + break; + case 6: // TMEM_ALLOC rd, rs1: rs1 columns + instr->set_op_type(TcuType::TMEM_ALLOC); + instr->set_dest_reg(rd, RegType::Integer); + instr->set_src_reg(0, rs1, RegType::Integer); + break; + case 7: // TMEM_DEALLOC rs1, rs2: rs2 columns from column rs1 + instr->set_op_type(TcuType::TMEM_DEALLOC); + instr->set_src_reg(0, rs1, RegType::Integer); + instr->set_src_reg(1, rs2, RegType::Integer); + break; + default: + std::abort(); + } + instr->set_args(args); + } break; + case 6: { // tcgen05-style async tensor ops + instr->set_fu_type(FUType::TCU); + IntrTcuArgs args{}; + switch (funct3) { + case 1: // TC_COMMIT rs1, rs2: barrier id, arrival count + instr->set_op_type(TcuType::TC_COMMIT); + instr->set_src_reg(1, rs2, RegType::Integer); + break; + case 2: // TC_CP rs1, rs2: {columns, taddr}, source + instr->set_op_type(TcuType::TC_CP); + instr->set_src_reg(1, rs2, RegType::Integer); + break; + case 4: // TC_MMA rs1, rs2, rs3 (rd field): instruction descriptor, A, B + instr->set_op_type(TcuType::TC_MMA); + instr->set_src_reg(1, rs2, RegType::Integer); + instr->set_src_reg(2, rd, RegType::Integer); + break; + default: + std::abort(); + } + instr->set_src_reg(0, rs1, RegType::Integer); + instr->set_args(args); + } break; #endif case 4: { // Load/Store Packing extensions — macro-ops, sequencer expands to N single-elem uops instr->set_fu_type(FUType::LSU); diff --git a/sim/simx/dxa/dxa_core.cpp b/sim/simx/dxa/dxa_core.cpp index 1e7f62ec38..7afdaaf717 100644 --- a/sim/simx/dxa/dxa_core.cpp +++ b/sim/simx/dxa/dxa_core.cpp @@ -31,6 +31,8 @@ using namespace vortex; // response tags index the in-flight slots by masking static_assert(VX_CFG_DXA_MAX_INFLIGHT >= 2 && (VX_CFG_DXA_MAX_INFLIGHT & (VX_CFG_DXA_MAX_INFLIGHT - 1)) == 0, "DXA_MAX_INFLIGHT must be a power of two of at least 2"); +static_assert(VX_CFG_DXA_MAX_XFERS >= 2 && (VX_CFG_DXA_MAX_XFERS & (VX_CFG_DXA_MAX_XFERS - 1)) == 0, + "DXA_MAX_XFERS must be a power of two of at least 2"); namespace { @@ -85,7 +87,6 @@ class DxaCore::Impl { uint32_t valid_length; // valid bytes per write uint32_t cfill; // OOB fill value (lane-replicated) bool oob; // skip GMEM read; use cfill - bool last; // last work item of the transfer bool scatter; // K-major/tiled: one element written per beat uint32_t km_num_elems; // K-major scatter fan-out (1 = contiguous write) uint32_t km_lane_stride; // SMEM byte stride between scattered elements @@ -94,50 +95,67 @@ class DxaCore::Impl { uint32_t tile_n_base; // tiled scatter: N (dim0) index where the span starts }; + // ── Transfer context: one per transfer a worker has in flight ─────── + // The next transfer issues while earlier ones still drain, so everything + // smem_wr needs per line lives here, indexed by the line's slot. + struct Xfer { + bool valid = false; + bool issued = false; // every line has been issued + uint32_t outstanding = 0; // lines issued, not yet written + uint64_t free_cycle = 0; // first cycle the context can be reused + DxaReq req; + Descriptor desc; + bool is_multicast = false; + std::vector cta_indices; + uint32_t smem_stride = 0; + uint64_t issue_cycle = 0; + uint32_t writes_emitted = 0; + }; + // ── Inflight slot for a GMEM read ────────────────────────────────── struct InflightSlot { bool allocated = false; bool rsp_arrived = false; - bool oob_pending = false; // OOB line waiting for its turn into smem_wr - bool deferred = false; // last line parked until the others drain uint64_t ready_cycle = 0; // first cycle the line can be written to SMEM uint64_t free_cycle = 0; // first cycle the slot can carry a new read + uint32_t xfer = 0; // owning transfer context LineWork work; // captured at allocation std::shared_ptr rsp_data; }; // ── Worker (one per slice) ─────────────────────────────────────────── - enum class WState { IDLE, RUNNING }; - struct Worker { - WState state = WState::IDLE; uint32_t worker_id = 0; - DxaReq req; - Descriptor desc; - bool is_multicast = false; - std::vector cta_indices; - uint32_t smem_stride = 0; - uint64_t issue_cycle = 0; - - // setup engine: the next transfer is set up while this one drains + + // setup engine: the next transfer is set up while this one issues bool staged = false; DxaReq staged_req; uint64_t staged_ready = 0; - // addr_gen: pre-enumerated work list (one entry per GMEM CL + - // multicast replays handled at smem_wr stage). + // addr_gen: pre-enumerated work list of the transfer being issued (one + // entry per GMEM CL; multicast replays are handled at the smem_wr stage). + bool issuing = false; + uint32_t issue_xfer = 0; std::vector work_list; uint32_t ag_idx = 0; // next entry to issue (gmem_req) + std::array xfers; + // gmem_req → smem_wr inflight bookkeeping. std::array inflight; - std::deque issued_order; // outstanding tags in issue order + // Tag pools: never-used slots count up from 0, released slots recycle in + // release order; OOB lines wait for smem_wr in issue order. + uint32_t fresh_slots = 0; + std::deque free_fifo; + std::deque oob_fifo; + uint32_t stg_slot = UINT32_MAX; // response stage (slot read) + uint32_t pend_slot = UINT32_MAX; // captured, waiting to drain uint32_t drain_slot = UINT32_MAX; // slot currently draining + bool drain_final = false; // drain_slot is its transfer's last line // smem_wr multicast replay state. uint32_t mc_cta_idx = 0; // 0..cta_indices.size() uint32_t km_elem_idx = 0; // 0..km_num_elems (K-major scatter) - uint32_t writes_emitted = 0; // count for perf }; // ── Constructor ────────────────────────────────────────────────────── @@ -156,17 +174,21 @@ class DxaCore::Impl { queue_.clear(); // perf_stats_ survives: the MPM counters run from device reset. for (auto& w : workers_) { - w.state = WState::IDLE; - w.work_list.clear(); - w.cta_indices.clear(); - w.issued_order.clear(); - w.drain_slot = UINT32_MAX; - for (auto& s : w.inflight) { s = InflightSlot(); } w.staged = false; + w.issuing = false; + w.work_list.clear(); w.ag_idx = 0; + for (auto& x : w.xfers) { x = Xfer(); } + for (auto& s : w.inflight) { s = InflightSlot(); } + w.fresh_slots = 0; + w.free_fifo.clear(); + w.oob_fifo.clear(); + w.stg_slot = UINT32_MAX; + w.pend_slot = UINT32_MAX; + w.drain_slot = UINT32_MAX; + w.drain_final = false; w.mc_cta_idx = 0; w.km_elem_idx = 0; - w.writes_emitted = 0; } } @@ -231,21 +253,23 @@ class DxaCore::Impl { // (the per-worker slot id). for (uint32_t worker_id = 0; worker_id < workers_.size(); ++worker_id) { auto& w = workers_[worker_id]; - if (w.state == WState::RUNNING) { - tick_worker_smem_wr(w); - } + tick_worker_smem_wr(w); capture_line(w, gmem_arb_->RspOut.at(worker_id)); - if (w.state == WState::RUNNING) { + if (w.issuing) { tick_worker_gmem_req(w); } } - // 3) Start a set-up transfer on an idle worker; otherwise let the - // worker's setup engine take the next request. + // 3) Start a set-up transfer once the worker has issued the previous + // one and holds a free transfer context; otherwise let the worker's + // setup engine take the next request. for (auto& w : workers_) { - if (w.staged && w.state == WState::IDLE && cycle_ >= w.staged_ready) { - w.staged = false; - start_worker(w, w.staged_req); + if (w.staged && !w.issuing && cycle_ >= w.staged_ready) { + uint32_t xi = free_xfer(w); + if (xi != UINT32_MAX) { + w.staged = false; + start_worker(w, xi, w.staged_req); + } } else if (!w.staged && !queue_.empty()) { w.staged_req = queue_.front(); w.staged_ready = cycle_ + this->setup_latency(w.staged_req); @@ -357,66 +381,71 @@ class DxaCore::Impl { } } + uint32_t free_xfer(const Worker& w) const { + for (uint32_t i = 0; i < w.xfers.size(); ++i) { + if (!w.xfers[i].valid && cycle_ >= w.xfers[i].free_cycle) + return i; + } + return UINT32_MAX; + } + // ── Setup: pre-enumerate the work list for this transfer ───────────── - void start_worker(Worker& w, const DxaReq& req) { - w.req = req; - w.issue_cycle = cycle_; - w.work_list.clear(); - w.ag_idx = 0; - w.issued_order.clear(); - w.drain_slot = UINT32_MAX; - for (auto& s : w.inflight) { s.allocated = false; s.rsp_arrived = false; s.rsp_data.reset(); } - w.mc_cta_idx = 0; - w.km_elem_idx = 0; - w.writes_emitted = 0; + void start_worker(Worker& w, uint32_t xi, const DxaReq& req) { + auto& x = w.xfers[xi]; + x.req = req; + x.issue_cycle = cycle_; + x.writes_emitted = 0; // Multicast setup. - w.is_multicast = (__builtin_popcount(req.cta_mask) > 1); - w.cta_indices.clear(); - if (w.is_multicast) { + x.is_multicast = (__builtin_popcount(req.cta_mask) > 1); + x.cta_indices.clear(); + if (x.is_multicast) { for (uint32_t i = 0; i < 32; ++i) { - if (req.cta_mask & (1u << i)) w.cta_indices.push_back(i); + if (req.cta_mask & (1u << i)) x.cta_indices.push_back(i); } } if (req.desc_slot >= VX_DCR_DXA_DESC_COUNT) { // Invalid descriptor — release barrier(s) directly without any LMEM write. - release_all_barriers(w); - finish_worker(w); + release_all_barriers(x); + count_transfer(w, x); return; } - w.desc = descriptors_.at(req.desc_slot); - w.smem_stride = w.desc.smem_stride; + x.desc = descriptors_.at(req.desc_slot); + x.smem_stride = x.desc.smem_stride; - enumerate_work_list(w); + w.work_list.clear(); + enumerate_work_list(x, w.work_list); if (w.work_list.empty()) { // No work — same edge case as above. - release_all_barriers(w); - finish_worker(w); + release_all_barriers(x); + count_transfer(w, x); return; } - // Mark the *last* work item — its multicast replay's last write carries - // notify_done. - w.work_list.back().last = true; - - w.state = WState::RUNNING; + x.valid = true; + x.issued = false; + x.outstanding = 0; + w.issuing = true; + w.issue_xfer = xi; + w.ag_idx = 0; perf_stats_.gmem_reads += w.work_list.size(); DT(3, simobject_->name() << "[" << w.worker_id << "] start: core=" << req.core->id() << ", wid=" << req.wid << ", slot=" << req.desc_slot + << ", xfer=" << xi << ", lines=" << w.work_list.size() - << ", multicast=" << w.is_multicast - << ", num_ctas=" << w.cta_indices.size()); + << ", multicast=" << x.is_multicast + << ", num_ctas=" << x.cta_indices.size()); } // Enumerate (CL, smem-word, byte-offset, length, oob) tuples — one per // GMEM CL the transfer needs to read. Row-major iteration over outer // dims, contiguous span over dim-0, dedup of consecutive same-CL. - void enumerate_work_list(Worker& w) { - const auto& desc = w.desc; + void enumerate_work_list(const Xfer& x, std::vector& work_list) { + const auto& desc = x.desc; uint32_t rank = desc_rank(desc.meta); if (rank < 1 || rank > 5) return; @@ -467,21 +496,21 @@ class DxaCore::Impl { // OOB check on outer dims. bool row_in_bounds = true; for (uint32_t d = 1; d < rank; ++d) { - if (w.req.coords[d] + outer[d - 1] >= desc.sizes[d]) { row_in_bounds = false; break; } + if (x.req.coords[d] + outer[d - 1] >= desc.sizes[d]) { row_in_bounds = false; break; } } // First element GMEM addr in this row. - uint64_t row_gbase = desc.base_addr + uint64_t(w.req.coords[0]) * elem_bytes; + uint64_t row_gbase = desc.base_addr + uint64_t(x.req.coords[0]) * elem_bytes; for (uint32_t d = 1; d < rank; ++d) - row_gbase += uint64_t(w.req.coords[d] + outer[d - 1]) * uint64_t(desc.strides[d - 1]); + row_gbase += uint64_t(x.req.coords[d] + outer[d - 1]) * uint64_t(desc.strides[d - 1]); // SMEM destination base for this row: // Row-major: base + row_idx * row_elems * elem_bytes (i1 outer × i0 inner). // K-major: base + outer[0] * elem_bytes (lane stride applies per e0 below). // Tiled: computed per-element below (smem_wr recomputes the permuted dest). uint64_t row_smem_base = dest_kmajor - ? (w.req.smem_addr + uint64_t(outer[0]) * elem_bytes) - : (w.req.smem_addr + uint64_t(row * row_elems) * elem_bytes); + ? (x.req.smem_addr + uint64_t(outer[0]) * elem_bytes) + : (x.req.smem_addr + uint64_t(row * row_elems) * elem_bytes); // Walk dim-0 elements; each LineWork carries one MemReq write of at // most one LMEM word AND at most one GMEM CL (so byteen fits in the @@ -492,7 +521,7 @@ class DxaCore::Impl { uint64_t saddr_e; if (dest_tiled) { uint32_t de = tiled_dest_elem(layout, outer[0], e0, geo_ratio, geo_tcN, geo_nsteps, geo_bkK); - saddr_e = w.req.smem_addr + uint64_t(de) * elem_bytes; + saddr_e = x.req.smem_addr + uint64_t(de) * elem_bytes; } else if (dest_kmajor) { saddr_e = row_smem_base + uint64_t(e0) * uint64_t(per_lane_stride_bytes); } else { @@ -521,7 +550,7 @@ class DxaCore::Impl { if (gspan == 0) break; uint32_t num_elems = gspan / elem_bytes; - bool elem_oob = !row_in_bounds || (w.req.coords[0] + e0 >= desc.sizes[0]); + bool elem_oob = !row_in_bounds || (x.req.coords[0] + e0 >= desc.sizes[0]); // OOB is determined per-element at the start of the span; tile widths // are typically aligned to dim-0 size, so this is exact for the common case. @@ -535,7 +564,6 @@ class DxaCore::Impl { lw.valid_length = scatter ? elem_bytes : gspan; lw.cfill = cfill; lw.oob = elem_oob; - lw.last = false; lw.scatter = scatter; lw.km_num_elems = scatter ? num_elems : 1; lw.km_lane_stride = dest_kmajor ? per_lane_stride_bytes : 0; @@ -549,57 +577,51 @@ class DxaCore::Impl { } else if (!elem_oob) { global_prev_cl = cl_addr; } - w.work_list.push_back(lw); + work_list.push_back(lw); e0 += num_elems; } } } - // ── smem_wr capture: one line per cycle into its line registers ─────── - // A GMEM response has priority over a pending OOB line. smem_wr holds one - // line being written, one captured behind it, and the transfer's last line - // while others are outstanding. A response it cannot take stays on the - // memory response path and holds the responses queued behind it. + // ── Response stage, then smem_wr capture ──────────────────────────── + // The slot table is a RAM with a registered read, so a line (a GMEM + // response, which has priority, or a pending OOB line) first spends a cycle + // in a one-entry stage while its slot is read. smem_wr captures the staged + // line once its line register is free; the stage refills in the same cycle. + // A response that cannot enter the stage stays on the memory response path + // and holds the responses queued behind it. void capture_line(Worker& w, SimChannel& ch) { - bool pend_busy = false; - bool defer_busy = false; - uint32_t oob_slot = UINT32_MAX; - for (uint32_t i = 0; i < w.inflight.size(); ++i) { - const auto& s = w.inflight[i]; - if (s.rsp_arrived && i != w.drain_slot) { - (s.deferred ? defer_busy : pend_busy) = true; - } - if (s.oob_pending && oob_slot == UINT32_MAX) { - oob_slot = i; - } + if (w.stg_slot != UINT32_MAX && w.pend_slot == UINT32_MAX) { + auto& s = w.inflight[w.stg_slot]; + s.rsp_arrived = true; + s.ready_cycle = cycle_ + kSmemWrLatency; + w.pend_slot = w.stg_slot; + w.stg_slot = UINT32_MAX; } - uint32_t slot = oob_slot; + uint32_t slot = UINT32_MAX; if (!ch.empty()) { slot = uint32_t(ch.peek().tag) & (VX_CFG_DXA_MAX_INFLIGHT - 1); if (!w.inflight[slot].allocated) { ch.pop(); return; } + } else if (!w.oob_fifo.empty()) { + slot = w.oob_fifo.front(); } - if (slot == UINT32_MAX) { + if (slot == UINT32_MAX || w.stg_slot != UINT32_MAX) { return; } auto& s = w.inflight[slot]; - bool defer = s.work.last && (w.issued_order.size() > 1); - if (defer ? defer_busy : pend_busy) { - return; - } if (!ch.empty()) { s.rsp_data = ch.peek().data; ch.pop(); + } else { + w.oob_fifo.pop_front(); } - s.oob_pending = false; - s.rsp_arrived = true; - s.deferred = defer; - s.ready_cycle = cycle_ + kSmemWrLatency; + w.stg_slot = slot; } // ── gmem_req: issue MemReqs with available inflight slots ──────────── @@ -607,16 +629,14 @@ class DxaCore::Impl { // One AGU step per cycle: advance ag_idx by at most one, issuing at most // one GMEM read to this worker's ReqIn port (or one OOB skip). A while-loop // here would issue many reads to a single port in one cycle. - if (w.ag_idx >= w.work_list.size()) - return; - // Find a free slot. + // Next free slot: a never-used one, else the oldest released one (a + // slot released this cycle is reusable from the next). uint32_t slot = UINT32_MAX; - for (uint32_t s = 0; s < w.inflight.size(); ++s) { - if (!w.inflight[s].allocated && cycle_ >= w.inflight[s].free_cycle) { - slot = s; - break; - } + if (w.fresh_slots < w.inflight.size()) { + slot = w.fresh_slots; + } else if (!w.free_fifo.empty() && cycle_ >= w.inflight[w.free_fifo.front()].free_cycle) { + slot = w.free_fifo.front(); } const LineWork& lw = w.work_list[w.ag_idx]; @@ -633,14 +653,8 @@ class DxaCore::Impl { // OOB lines skip the GMEM request entirely; smem_wr takes them in a cycle // with no GMEM response (rsp data left null — smem_wr will use cfill). if (lw.oob) { - w.inflight[slot].allocated = true; - w.inflight[slot].rsp_arrived = false; - w.inflight[slot].oob_pending = true; - w.inflight[slot].deferred = false; - w.inflight[slot].rsp_data.reset(); - w.inflight[slot].work = lw; - w.issued_order.push_back(slot); - ++w.ag_idx; + w.oob_fifo.push_back(slot); + issue_line(w, slot, lw); return; } @@ -650,59 +664,56 @@ class DxaCore::Impl { MemReq mreq; mreq.addr = lw.gmem_cl_addr; mreq.tag = slot; - mreq.hart_id = w.req.core->id(); - mreq.uuid = w.req.uuid; + const auto& req = w.xfers[w.issue_xfer].req; + mreq.hart_id = req.core->id(); + mreq.uuid = req.uuid; auto& ch = gmem_arb_->ReqIn.at(w.worker_id); if (!ch.try_send(mreq)) return; // arb backpressure - w.inflight[slot].allocated = true; - w.inflight[slot].rsp_arrived = false; - w.inflight[slot].oob_pending = false; - w.inflight[slot].deferred = false; - w.inflight[slot].rsp_data.reset(); - w.inflight[slot].work = lw; - w.issued_order.push_back(slot); - ++w.ag_idx; + issue_line(w, slot, lw); + } + + void issue_line(Worker& w, uint32_t slot, const LineWork& lw) { + if (slot == w.fresh_slots) { + ++w.fresh_slots; + } else { + w.free_fifo.pop_front(); + } + auto& s = w.inflight[slot]; + s.allocated = true; + s.rsp_arrived = false; + s.xfer = w.issue_xfer; + s.rsp_data.reset(); + s.work = lw; + auto& x = w.xfers[w.issue_xfer]; + ++x.outstanding; + if (++w.ag_idx == w.work_list.size()) { + x.issued = true; + w.issuing = false; + } } // ── smem_wr: drain ready slots, build LMEM MemReqs ─────────────────── void tick_worker_smem_wr(Worker& w) { - if (w.issued_order.empty()) { - // Nothing in flight — if all addr_gen done, transfer is finished. - if (w.ag_idx == w.work_list.size()) finish_worker(w); - return; + // Lines drain in arrival order, whatever their transfer. The line that + // leaves its transfer with nothing else outstanding once the transfer + // has issued every line is the final one: its write carries notify_done, + // so it lands after every other write of the transfer. + if (w.drain_slot == UINT32_MAX) { + uint32_t p = w.pend_slot; + if (p == UINT32_MAX || cycle_ < w.inflight[p].ready_cycle) + return; + const auto& px = w.xfers[w.inflight[p].xfer]; + w.drain_final = px.issued && (px.outstanding == 1); + w.drain_slot = p; + w.pend_slot = UINT32_MAX; } - // Match the RTL's OoO direct-drain behavior: select any ready non-last - // slot without waiting for older requests. Once selected, keep draining - // the same slot because the multicast/scatter cursors are worker-local. - // The last work item carries notify_done and must remain deferred until - // it is the only outstanding slot. - uint32_t slot = w.drain_slot; - if (slot == UINT32_MAX) { - for (uint32_t i = 0; i < w.inflight.size(); ++i) { - const auto& candidate = w.inflight[i]; - if (candidate.allocated && candidate.rsp_arrived && !candidate.work.last - && cycle_ >= candidate.ready_cycle) { - slot = i; - break; - } - } - - if (slot == UINT32_MAX && w.issued_order.size() == 1) { - uint32_t last_slot = w.issued_order.front(); - const auto& candidate = w.inflight[last_slot]; - if (candidate.allocated && candidate.rsp_arrived && cycle_ >= candidate.ready_cycle) - slot = last_slot; - } - - if (slot == UINT32_MAX) return; - w.drain_slot = slot; - } + auto& x = w.xfers[w.inflight[w.drain_slot].xfer]; // Determine destination core's LMEM port group. - uint32_t socket_local_cid = w.req.core->id() % kCoresPerSocket; + uint32_t socket_local_cid = x.req.core->id() % kCoresPerSocket; // One drain beat per cycle covers one aligned LMEM row // (DxaCore::LMEM_ROW_SIZE bytes — the full banked row the RTL writes in @@ -724,7 +735,7 @@ class DxaCore::Impl { uint64_t beat_row = UINT64_MAX; for (uint32_t emitted = 0; emitted < DxaCore::LMEM_PORTS_PER_CORE; ++emitted) { - slot = w.drain_slot; + uint32_t slot = w.drain_slot; if (slot == UINT32_MAX) { break; // slot released mid-beat } @@ -743,25 +754,25 @@ class DxaCore::Impl { uint32_t cta_warp_idx = 0; uint64_t cta_off = 0; - if (w.is_multicast) { - cta_warp_idx = w.cta_indices.at(w.mc_cta_idx); - cta_off = uint64_t(cta_warp_idx) * w.smem_stride; + if (x.is_multicast) { + cta_warp_idx = x.cta_indices.at(w.mc_cta_idx); + cta_off = uint64_t(cta_warp_idx) * x.smem_stride; } // Per-element SMEM byte destination. K-major: uniform lane stride from a // span base. Tiled (Flat/BlockMajor): permuted index from the WGMMA // B-buffer layout formula (idx = within-span dim-0 offset → N = base+idx). - const bool tiled = desc_dest_tiled(w.desc.meta); - const uint32_t t_eb = desc_elem_bytes(w.desc.meta); + const bool tiled = desc_dest_tiled(x.desc.meta); + const uint32_t t_eb = desc_elem_bytes(x.desc.meta); const uint32_t t_ratio = tiled ? std::max(1u, 4u / t_eb) : 1u; - const uint32_t t_tcN = tiled ? desc_geo_tcn(w.desc) : 1u; - const uint32_t t_bkK = tiled ? desc_geo_bkk(w.desc) : 1u; - const uint32_t t_nsteps = tiled ? std::max(1u, uint32_t(w.desc.tile_sizes[0]) / t_tcN) : 1u; + const uint32_t t_tcN = tiled ? desc_geo_tcn(x.desc) : 1u; + const uint32_t t_bkK = tiled ? desc_geo_bkk(x.desc) : 1u; + const uint32_t t_nsteps = tiled ? std::max(1u, uint32_t(x.desc.tile_sizes[0]) / t_tcN) : 1u; auto dest_byte_of = [&](uint32_t idx) -> uint64_t { if (tiled) { uint32_t de = tiled_dest_elem(DestLayout(lw.dest_layout), lw.tile_k_row, lw.tile_n_base + idx, t_ratio, t_tcN, t_nsteps, t_bkK); - return w.req.smem_addr + uint64_t(de) * t_eb + cta_off; + return x.req.smem_addr + uint64_t(de) * t_eb + cta_off; } return lw.smem_word_addr + lw.smem_byte_offset + uint64_t(idx) * lw.km_lane_stride + cta_off; @@ -793,9 +804,9 @@ class DxaCore::Impl { MemReq req; req.addr = dword; req.op = MemOp::ST; - req.tag = w.req.core->id(); // routing tag - req.hart_id = w.req.core->id(); - req.uuid = w.req.uuid; + req.tag = x.req.core->id(); // routing tag + req.hart_id = x.req.core->id(); + req.uuid = x.req.uuid; uint64_t byteen = 0; auto blk = make_mem_block(); const uint32_t pat = lw.cfill; @@ -826,17 +837,16 @@ class DxaCore::Impl { req.data = blk; // notify_done on the LAST block write of the transfer — when the write - // reached the last scatter element of the last work item, per receiver. + // reached the last scatter element of the final line, per receiver. bool is_last_elem = (ee == num_elems); - bool is_last_work = lw.last; - bool is_last_replay = !w.is_multicast || (w.mc_cta_idx + 1 == w.cta_indices.size()); - if (is_last_work && is_last_elem && (w.is_multicast || is_last_replay)) { + bool is_last_replay = !x.is_multicast || (w.mc_cta_idx + 1 == x.cta_indices.size()); + if (w.drain_final && is_last_elem && (x.is_multicast || is_last_replay)) { req.flags.dxa_notify_done = 1; - req.flags.dxa_notify_bar_id = w.req.bar_id + (w.is_multicast ? cta_warp_idx : 0u); + req.flags.dxa_notify_bar_id = x.req.bar_id + (x.is_multicast ? cta_warp_idx : 0u); } lmem_ch.send(req); - ++w.writes_emitted; + ++x.writes_emitted; // Count write transactions, not port requests: one per banked-row beat. // A beat spans LMEM_PORTS_PER_CORE ports of the same row, so only its // first emission is counted. @@ -850,18 +860,20 @@ class DxaCore::Impl { w.km_elem_idx = ee; } else { w.km_elem_idx = 0; - if (w.is_multicast && (w.mc_cta_idx + 1) < w.cta_indices.size()) { + if (x.is_multicast && (w.mc_cta_idx + 1) < x.cta_indices.size()) { ++w.mc_cta_idx; } else { w.mc_cta_idx = 0; // Slot done — release. s.allocated = false; s.rsp_arrived = false; - s.deferred = false; s.free_cycle = cycle_ + 1; + w.free_fifo.push_back(slot); s.rsp_data.reset(); - auto it = std::find(w.issued_order.begin(), w.issued_order.end(), slot); - if (it != w.issued_order.end()) w.issued_order.erase(it); + --x.outstanding; + if (w.drain_final) { + finish_xfer(w, x); + } w.drain_slot = UINT32_MAX; } } @@ -871,37 +883,34 @@ class DxaCore::Impl { } // per-tick row-beat emission loop } - void release_all_barriers(Worker& w) { + void release_all_barriers(const Xfer& x) { // bar_id is RAW (encoded); decode at release call site. - if (w.is_multicast) { - for (uint32_t cta : w.cta_indices) { - uint32_t decoded = bar_decode_id(w.req.bar_id + cta, VX_CFG_NUM_BARRIERS); - w.req.core->barrier_event_release(decoded); + if (x.is_multicast) { + for (uint32_t cta : x.cta_indices) { + uint32_t decoded = bar_decode_id(x.req.bar_id + cta, VX_CFG_NUM_BARRIERS); + x.req.core->barrier_event_release(decoded); } } else { - uint32_t decoded = bar_decode_id(w.req.bar_id, VX_CFG_NUM_BARRIERS); - w.req.core->barrier_event_release(decoded); + uint32_t decoded = bar_decode_id(x.req.bar_id, VX_CFG_NUM_BARRIERS); + x.req.core->barrier_event_release(decoded); } } - void finish_worker(Worker& w) { - if (w.state == WState::RUNNING || w.state == WState::IDLE) { - uint64_t latency = cycle_ - w.issue_cycle; - ++perf_stats_.transfers; - perf_stats_.total_latency += latency; - DT(3, simobject_->name() << "[" << w.worker_id << "] complete: core=" - << w.req.core->id() << ", bar=" << w.req.bar_id - << ", writes=" << w.writes_emitted << ", latency=" << latency); - } - w.state = WState::IDLE; - w.work_list.clear(); - w.cta_indices.clear(); - w.issued_order.clear(); - w.drain_slot = UINT32_MAX; - w.ag_idx = 0; - w.mc_cta_idx = 0; - w.km_elem_idx = 0; - w.writes_emitted = 0; + void count_transfer(const Worker& w, const Xfer& x) { + __unused(w); + uint64_t latency = cycle_ - x.issue_cycle; + ++perf_stats_.transfers; + perf_stats_.total_latency += latency; + DT(3, simobject_->name() << "[" << w.worker_id << "] complete: core=" + << x.req.core->id() << ", bar=" << x.req.bar_id + << ", writes=" << x.writes_emitted << ", latency=" << latency); + } + + void finish_xfer(Worker& w, Xfer& x) { + count_transfer(w, x); + x.valid = false; + x.free_cycle = cycle_ + 1; + x.cta_indices.clear(); } // ── Members ────────────────────────────────────────────────────────── diff --git a/sim/simx/kmu/kmu.cpp b/sim/simx/kmu/kmu.cpp index 731dcdf3ac..76e3563b40 100644 --- a/sim/simx/kmu/kmu.cpp +++ b/sim/simx/kmu/kmu.cpp @@ -24,6 +24,7 @@ Kmu::Kmu(const SimContext& ctx, const char* name, uint32_t num_cores) , entry_(0) , param_(0) , lmem_size_(0) + , tmem_cols_(0) , block_size_(0) , running_(false) , cta_id_(0) @@ -75,6 +76,7 @@ void Kmu::dcr_write(uint32_t addr, uint32_t value) { case VX_DCR_KMU_GRID_DIM_Y: grid_dim_[1] = value; break; case VX_DCR_KMU_GRID_DIM_Z: grid_dim_[2] = value; break; case VX_DCR_KMU_LMEM_SIZE: lmem_size_ = value; break; + case VX_DCR_KMU_TMEM_COLS: tmem_cols_ = value; break; case VX_DCR_KMU_BLOCK_SIZE: block_size_ = value; break; case VX_DCR_KMU_WARP_STEP_X: warp_step_[0] = value; break; case VX_DCR_KMU_WARP_STEP_Y: warp_step_[1] = value; break; @@ -194,6 +196,7 @@ bool Kmu::next_cta(kmu_req_t* req, uint32_t core_id) { req->grid_dim[1] = grid_dim_[1]; req->grid_dim[2] = grid_dim_[2]; req->lmem_size = lmem_size_; + req->tmem_cols = tmem_cols_; req->block_size = block_size_; req->warp_step[0] = warp_step_[0]; req->warp_step[1] = warp_step_[1]; diff --git a/sim/simx/kmu/kmu.h b/sim/simx/kmu/kmu.h index 687bd40ec9..a0ffc624b4 100644 --- a/sim/simx/kmu/kmu.h +++ b/sim/simx/kmu/kmu.h @@ -29,6 +29,7 @@ struct kmu_req_t { uint32_t block_dim[3]; uint32_t grid_dim[3]; uint32_t lmem_size; + uint32_t tmem_cols; // TMEM columns a CTA may allocate (0 = none) uint32_t block_size; uint32_t warp_step[3]; uint32_t cluster_dim[3]; @@ -95,6 +96,7 @@ class Kmu : public SimObject { uint32_t block_dim_[3]; uint32_t grid_dim_[3]; uint32_t lmem_size_; + uint32_t tmem_cols_; uint32_t block_size_; uint32_t warp_step_[3]; uint32_t cluster_dim_[3]; diff --git a/sim/simx/lsu_unit.h b/sim/simx/lsu_unit.h index f0757dc710..434b072299 100644 --- a/sim/simx/lsu_unit.h +++ b/sim/simx/lsu_unit.h @@ -22,9 +22,9 @@ #include "VX_config.h" // The TCU metadata SRAM is present when any metadata-consuming mode (MX or -// sparse) is enabled. Internal derived macro — not a VX_CFG_* knob; same +// sparse) is enabled with per-warp MMAs. Internal derived macro — not a VX_CFG_* knob; same // derivation as tcu_unit.h. -#if defined(VX_CFG_TCU_MX_ENABLE) || defined(VX_CFG_TCU_SPARSE_ENABLE) +#if (defined(VX_CFG_TCU_MX_ENABLE) || defined(VX_CFG_TCU_SPARSE_ENABLE)) && defined(VX_CFG_TCU_WMMA_ENABLE) #define TCU_META_ENABLE #endif diff --git a/sim/simx/mem/local_mem.cpp b/sim/simx/mem/local_mem.cpp index 69d3ee00d1..3c6befd81f 100644 --- a/sim/simx/mem/local_mem.cpp +++ b/sim/simx/mem/local_mem.cpp @@ -247,6 +247,23 @@ class LocalMem::Impl { return false; } + // Sleeping is safe only with nothing delivered or in flight toward an + // input: a packet reserved this cycle by a module scanned earlier is not + // yet visible to empty(), and its wake-up has already been consumed. + bool inputs_quiet() const { + for (auto& in : simobject_->ReqIn) { + if (in.size() != 0) { + return false; + } + } + for (auto& in : simobject_->DmaInputs) { + if (in.size() != 0) { + return false; + } + } + return true; + } + // Serve one DMA client's row access. Clients are served round-robin, // starting after the last one served. void dma_fire() { @@ -577,7 +594,7 @@ class LocalMem::Impl { for (auto& r : rsp_regs_) { idle = idle && !r.valid; } - if (idle && !this->dma_pending()) { + if (idle && this->inputs_quiet()) { simobject_->tick_sleep(); } } diff --git a/sim/simx/tcu/tcu_tbuf.cpp b/sim/simx/tcu/tcu_tbuf.cpp index 7c691f241f..9e08e67254 100644 --- a/sim/simx/tcu/tcu_tbuf.cpp +++ b/sim/simx/tcu/tcu_tbuf.cpp @@ -24,12 +24,18 @@ namespace { constexpr uint64_t kLineMask = ~uint64_t(VX_CFG_MEM_BLOCK_SIZE - 1); -// Q+1 buffers share one LMEM port. Buffer IDs, in priority order: +// The buffers share one LMEM port. Buffer IDs, in priority order: // 0 .. VX_CFG_NUM_TCU_BLOCKS-1 → abuf[b] // VX_CFG_NUM_TCU_BLOCKS → bbuf +// VX_CFG_NUM_TCU_BLOCKS + 1 → cbuf (TMEM builds) +#ifdef VX_CFG_TCU_TMEM_ENABLE +constexpr uint32_t kNumBuffers = VX_CFG_NUM_TCU_BLOCKS + 2; +#else constexpr uint32_t kNumBuffers = VX_CFG_NUM_TCU_BLOCKS + 1; +#endif constexpr uint32_t kAOffset = 0; constexpr uint32_t kBOffset = VX_CFG_NUM_TCU_BLOCKS; +[[maybe_unused]] constexpr uint32_t kCOffset = VX_CFG_NUM_TCU_BLOCKS + 1; struct Buffer { std::deque pending_; @@ -38,6 +44,7 @@ struct Buffer { bool rsp_seen_ = false; // a response arrived this cycle uint32_t next_tag_ = 0; uint64_t reads_ = 0; + uint32_t max_inflight_ = 1; bool filling() const { return !pending_.empty() || !inflight_.empty(); @@ -70,6 +77,7 @@ struct Buffer { rsp_seen_ = false; next_tag_ = 0; // reads_ survives: it backs an MPM counter, which runs from device reset. + max_inflight_ = 1; } }; @@ -151,10 +159,10 @@ class TcuTbuf::Impl { } for (uint32_t s = 0; s < kNumBuffers; ++s) { auto& b = bufs_.at(s); - if (b.pending_.empty() || !b.inflight_.empty()) { + if (b.pending_.empty() || b.inflight_.size() >= b.max_inflight_) { continue; } - if (s == kBOffset && b.rsp_seen_) { + if (s == kBOffset && b.rsp_seen_ && b.max_inflight_ == 1) { continue; } this->issue(s, b); @@ -195,8 +203,13 @@ class TcuTbuf::Impl { } std::string buf_name(uint32_t source) const { - return (source == kBOffset) ? std::string("bbuf") - : ("abuf" + std::to_string(source - kAOffset)); + if (source == kBOffset) { + return "bbuf"; + } + if (source > kBOffset) { + return "cbuf"; + } + return "abuf" + std::to_string(source - kAOffset); } TcuTbuf* simobject_; @@ -218,8 +231,10 @@ void TcuTbuf::on_tick() { impl_->tick(); } void TcuTbuf::fill_a(uint32_t b, std::vector reads) { impl_->buf(kAOffset + b).fill(std::move(reads)); } -void TcuTbuf::fill_b(std::vector reads) { - impl_->buf(kBOffset).fill(std::move(reads)); +void TcuTbuf::fill_b(std::vector reads, uint32_t max_inflight) { + auto& b = impl_->buf(kBOffset); + b.fill(std::move(reads)); + b.max_inflight_ = max_inflight; } bool TcuTbuf::filling_a(uint32_t b) const { return impl_->buf(kAOffset + b).filling(); } @@ -232,6 +247,16 @@ std::shared_ptr TcuTbuf::read_b(uint64_t line_addr) const { return impl_->buf(kBOffset).read(line_addr); } +#ifdef VX_CFG_TCU_TMEM_ENABLE +void TcuTbuf::fill_c(std::vector reads) { + impl_->buf(kCOffset).fill(std::move(reads)); +} +bool TcuTbuf::filling_c() const { return impl_->buf(kCOffset).filling(); } +std::shared_ptr TcuTbuf::read_c(uint64_t line_addr) const { + return impl_->buf(kCOffset).read(line_addr); +} +#endif + void TcuTbuf::invalidate_a(uint32_t b) { impl_->buf(kAOffset + b).invalidate(); } void TcuTbuf::invalidate_b() { impl_->buf(kBOffset).invalidate(); } diff --git a/sim/simx/tcu/tcu_tbuf.h b/sim/simx/tcu/tcu_tbuf.h index 91d3f32224..370ad972a0 100644 --- a/sim/simx/tcu/tcu_tbuf.h +++ b/sim/simx/tcu/tcu_tbuf.h @@ -24,13 +24,14 @@ namespace vortex { // // abuf × Q per-block A k-stripe // bbuf × 1 B bank row, shared by all Q blocks +// cbuf × 1 rows of a tensor-job TMEM copy (TMEM builds) // // The consumer (TcuUnit) owns the refill keys: it decides when a buffer // refills and hands over the refill as a list of LMEM reads. Each read is // one bank-row request on the hardware port and covers one or more // mem_block lines here, sent together on parallel ports. A buffer keeps one -// read in flight; buffers share the port at fixed priority, abuf[0] first -// and bbuf last. +// read in flight (the B buffer may keep more); buffers share the port at fixed priority, abuf[0] first +// and cbuf last. // // Sparse metadata is preloaded into the TcuUnit's per-warp `sparse_meta_` // SRAM via TCU_LD ahead of the MMA dispatch; it does not flow through here. @@ -54,11 +55,19 @@ class TcuTbuf : public SimObject { // Drop the buffer's contents and fetch `reads` in order. `b` indexes the // per-block A buffer. void fill_a(uint32_t b, std::vector reads); - void fill_b(std::vector reads); + // max_inflight: reads the B buffer keeps outstanding (a tensor op's dense + // K-major block issues its row reads back to back). + void fill_b(std::vector reads, uint32_t max_inflight = 1); bool filling_a(uint32_t b) const; bool filling_b() const; +#ifdef VX_CFG_TCU_TMEM_ENABLE + void fill_c(std::vector reads); + bool filling_c() const; + std::shared_ptr read_c(uint64_t line_addr) const; +#endif + std::shared_ptr read_a(uint32_t b, uint64_t line_addr) const; std::shared_ptr read_b(uint64_t line_addr) const; diff --git a/sim/simx/tcu/tcu_unit.cpp b/sim/simx/tcu/tcu_unit.cpp index d01eb597e7..69991502ae 100644 --- a/sim/simx/tcu/tcu_unit.cpp +++ b/sim/simx/tcu/tcu_unit.cpp @@ -24,9 +24,12 @@ #include "processor_impl.h" #include "mem/memory.h" #include "stack_interleave.h" +#include #include #include #include +#include +#include #include #include @@ -41,6 +44,21 @@ static constexpr bool kFedp2K = true; #else static constexpr bool kFedp2K = false; #endif +// A tensor op's sparse step covers fedpK compressed A words (TMEM builds with +// FEDP2K), as Blackwell's sparse tcgen05.mma; a warp WGMMA_SP uop covers tcK. +static constexpr bool kSpFullK = (wg_cfg::sp_k_mult > 1); +// Dense FEDP2K RS uops read A from both rs1 and rs2, so they carry the B +// descriptor in a leading setup uop. +static constexpr bool wgmma_needs_setup(bool is_a_smem, bool is_sparse) { + return kFedp2K && !is_a_smem && !is_sparse; +} + +#if defined(VX_CFG_TCU_TMEM_ENABLE) && !defined(VX_CFG_TCU_WGMMA_ENABLE) +#error "VX_CFG_TCU_TMEM_ENABLE requires VX_CFG_TCU_WGMMA_ENABLE" +#endif +#if !defined(VX_CFG_TCU_WMMA_ENABLE) && !defined(VX_CFG_TCU_TMEM_ENABLE) +#error "disabling VX_CFG_TCU_WMMA_ENABLE requires VX_CFG_TCU_TMEM_ENABLE" +#endif // Dot-product pipeline depth of the configured tensor-PE type. static constexpr uint32_t kFedpLatency = VX_CFG_TCU_LATENCY; @@ -346,7 +364,7 @@ class TcuUnit::Impl { Impl(TcuUnit* simobject, Core* core) : simobject_(simobject) , core_(core) - , sparse_meta_(VX_CFG_NUM_WARPS, std::vector(kMetaBanks * kMaxMetaCols, 0)) + , sparse_meta_(kMetaSlots, std::vector(kMetaBanks * kMaxMetaCols, 0)) #ifdef VX_CFG_TCU_MX_ENABLE , mx_meta_a_(VX_CFG_NUM_WARPS, std::vector(VX_CFG_NUM_THREADS, 0)) , mx_meta_b_(VX_CFG_NUM_WARPS, std::vector(VX_CFG_NUM_THREADS, 0)) @@ -354,9 +372,14 @@ class TcuUnit::Impl { , perf_stats_() { exec_done_.fill(false); + tj_fresh_.fill(true); + tj_hold_until_.fill(0); slices_.fill(0); in_wgmma_.fill(false); wgmma_desc_.fill({0, 0}); + #ifdef VX_CFG_TCU_TMEM_ENABLE + tmem_.assign(kTmemLanes * kTmemCols, reg_data_t{}); + #endif } ~Impl() {} @@ -388,6 +411,20 @@ class TcuUnit::Impl { bbuf_ = bbuf_slot_t{}; #endif cur_block_ = 0; + #ifdef VX_CFG_TCU_TMEM_ENABLE + std::fill(tmem_.begin(), tmem_.end(), reg_data_t{}); + tmem_used_ = 0; + tmem_owner_.fill(-1); + ops_.clear(); + run_valid_ = false; + commits_.clear(); + step_wb_.clear(); + spans_.clear(); + steps_issued_ = 0; + steps_done_ = 0; + blk_port_ops_.fill(0); + tmem_rd_taken_ = false; + #endif #ifdef TCU_META_ENABLE agu_.fill(agu_state_t{}); agu_issue_rr_ = 0; @@ -579,6 +616,7 @@ class TcuUnit::Impl { #endif // TCU_META_ENABLE void tick() { + cyc_ = {}; #ifdef TCU_META_ENABLE this->agu_collect(); #endif @@ -586,6 +624,10 @@ class TcuUnit::Impl { uint32_t wgmma_ready = this->tbuf_step(); uint32_t setup_fired = 0; #endif + #ifdef VX_CFG_TCU_TMEM_ENABLE + this->job_step(); + tj_port_busy_ = false; + #endif uint64_t now = SimPlatform::instance().cycles(); for (uint32_t b = 0; b < VX_CFG_NUM_TCU_BLOCKS; ++b) { @@ -606,8 +648,12 @@ class TcuUnit::Impl { result_ready &= !agu_.at(b).complete; #endif auto& input = simobject_->Inputs.at(b); - if (input.empty()) + if (input.empty()) { + #ifdef VX_CFG_TCU_TMEM_ENABLE + tj_fresh_.at(b) = true; + #endif continue; + } auto trace = input.peek(); auto tcu_type = std::get(trace->op_type); auto tpuArgs = std::get(trace->instr_ptr->get_args()); @@ -631,10 +677,28 @@ class TcuUnit::Impl { continue; } + #ifdef VX_CFG_TCU_TMEM_ENABLE + // TMEM and tc ops pass a registered select stage: one reaching an idle + // input is taken the cycle after; one queued behind follows back to back. + bool is_tj_op = tcu_is_tj_op(tcu_type); + if (is_tj_op) { + if (tj_fresh_.at(b)) { + tj_fresh_.at(b) = false; + tj_hold_until_.at(b) = now + 1; + } + if (now < tj_hold_until_.at(b)) { + continue; + } + } + #else + constexpr bool is_tj_op = false; + #endif + #ifdef VX_CFG_TCU_WGMMA_ENABLE // A WGMMA compute uop fires once its tile-buffer operands are ready. if (tcu_is_wgmma(tcu_type) && !tpuArgs.is_setup_uop && !exec_done_.at(b) && !((wgmma_ready >> b) & 1u)) { + cyc_.opnd = true; continue; } #endif @@ -650,7 +714,7 @@ class TcuUnit::Impl { trace->dst_data.assign(num_threads, reg_data_t{}); auto& rd_data = trace->dst_data; - if (!vt::tcu_output_valid(tpuArgs.fmt_s, tpuArgs.fmt_d)) { + if (!is_tj_op && !vt::tcu_output_valid(tpuArgs.fmt_s, tpuArgs.fmt_d)) { std::cerr << "*** TCU output format " << tpuArgs.fmt_d << " for input format " << tpuArgs.fmt_s << " is not supported: the TCU returns fp32 (int32 for integer inputs)" << std::endl; std::abort(); @@ -663,6 +727,7 @@ class TcuUnit::Impl { tpuArgs.step_m, tpuArgs.step_n, tpuArgs.step_k, rs1_data, rs2_data, rs3_data, rd_data, tcu_is_sparse(tcu_type)); + ++cyc_.busy_blocks; break; #ifdef VX_CFG_TCU_WGMMA_ENABLE case TcuType::WGMMA: @@ -693,6 +758,7 @@ class TcuUnit::Impl { if (tpuArgs.is_setup_uop) { setup_fired |= (1u << b); } else { + ++cyc_.busy_blocks; // The block owns its CTA from its first compute uop to its last. if (tpuArgs.is_first_uop) { in_wgmma_.at(b) = true; @@ -704,6 +770,161 @@ class TcuUnit::Impl { } } } break; + #endif + #ifdef VX_CFG_TCU_TMEM_ENABLE + case TcuType::TMEM_LD: + case TcuType::TMEM_ST: { + // A warp's transfers go to its own block's TMEM lanes, through the + // block's port. taddr = {lane [31:16], column [15:0]}; the lane is + // the block's first. Lane per thread: thread t holds lane + // + t % xtileM and register r column + r * kTmemThreadsPerLane + // + t / xtileM. Fragment: register r is the fragment of M step + // r % m_steps, columns + (r / m_steps) * tcN: thread t holds lane + // + m * tcM + t / tcN, column + t % tcN (the WGMMA accumulator layout). + uint32_t taddr = rs1_data.at(0).u; + uint32_t r = tpuArgs.tmem_idx; + uint32_t lane0 = taddr >> 16; + uint32_t col0 = taddr & 0xffff; + uint32_t cols = kTmemThreadsPerLane; + if (tpuArgs.tmem_row) { + lane0 += (r % wg_cfg::m_steps) * wg_cfg::tcM; + col0 += (r / wg_cfg::m_steps) * wg_cfg::tcN; + cols = wg_cfg::tcN; + } else { + col0 += r * kTmemThreadsPerLane; + } + bool is_ld = (tcu_type == TcuType::TMEM_LD); + if ((taddr >> 16) != b * wg_cfg::xtileM || ((taddr & 0xffff) % kFragCols) != 0 + || col0 + cols > kTmemCols) { + std::cout << "Error: tmem." << (is_ld ? "ld" : "st") << " of lane " << (taddr >> 16) + << " column " << (taddr & 0xffff) << " from a warp of block " << b + << " (its lanes start at " << b * wg_cfg::xtileM << ", columns are whole groups of " + << kFragCols << " below " << kTmemCols << ")" << std::endl; + std::abort(); + } + // A register is one read or write: of both M steps' rows (lane per + // thread) or of one (fragment). + uint32_t port_ops = 1; + // A step's D write-back has the write port before a tmem.st. + if (!is_ld && port_ops != 0 && this->job_writing(now)) { + ++perf_stats_.tmem_stalls; + continue; + } + if (port_ops != 0) { + if (blk_port_ops_.at(b) + 1 < port_ops) { + ++blk_port_ops_.at(b); + if (is_ld) { + tmem_rd_taken_ = true; + } + ++perf_stats_.tmem_stalls; + continue; + } + blk_port_ops_.at(b) = 0; + if (is_ld) { + tmem_rd_taken_ = true; + } + } + int32_t cta = (int32_t)core_->scheduler().warp(wid).cta_csrs.cta_id; + this->contract_check(is_ld ? "tmem.ld" : "tmem.st", cta, col0, col0 + cols, !is_ld); + ++perf_stats_.tmem_xfers; + if (is_ld) { + rd_data.resize(VX_CFG_NUM_THREADS); + } + for (uint32_t t = 0; t < VX_CFG_NUM_THREADS; ++t) { + auto& cell = tpuArgs.tmem_row + ? this->tmem_at(lane0 + t / wg_cfg::tcN, col0 + t % wg_cfg::tcN) + : this->tmem_at(lane0 + t % wg_cfg::xtileM, col0 + t / wg_cfg::xtileM); + if (is_ld) { + rd_data.at(t).u64 = nan_box(cell.u32); + } else { + cell.u64 = nan_box(rs2_data.at(t).u32); + } + } + } break; + case TcuType::TMEM_ALLOC: + case TcuType::TMEM_DEALLOC: { + if (tj_port_busy_) { + continue; + } + uint32_t t0 = scalar_thread(trace); + uint32_t col = rs1_data.at(t0).u; + uint32_t ncols = (tcu_type == TcuType::TMEM_ALLOC) ? col : rs2_data.at(t0).u; + int32_t cta = (int32_t)core_->scheduler().warp(wid).cta_csrs.cta_id; + if (ncols < kAllocCols || ncols > kTmemCols || (ncols & (ncols - 1)) != 0) { + std::cout << "Error: TMEM allocation of " << ncols << " columns (a power of two from " + << kAllocCols << " to " << kTmemCols << ")" << std::endl; + std::abort(); + } + uint32_t k = ncols / kAllocCols; + uint32_t mask = (k == 32) ? ~0u : ((1u << k) - 1); + if (tcu_type == TcuType::TMEM_ALLOC) { + // Waits until a run fits; the launch budget keeps the resident + // CTAs' allocations within TMEM. + uint32_t first = this->alloc_fit(k); + if (first == ~0u) { + ++perf_stats_.tmem_stalls; + continue; + } + tmem_used_ |= mask << first; + for (uint32_t i = first; i < first + k; ++i) { + tmem_owner_.at(i) = cta; + } + // The column goes to thread 0 only, as in the RTL; the other + // threads get a poison value, an address no transfer accepts. + rd_data.resize(VX_CFG_NUM_THREADS); + for (auto& rd : rd_data) { + rd.u = ~0u; + } + rd_data.at(0).u = first * kAllocCols; + } else { + uint32_t first = col / kAllocCols; + bool owned = (col % ncols) == 0 && (tmem_used_ & (mask << first)) == (mask << first); + for (uint32_t i = first; owned && i < first + k; ++i) { + owned = (tmem_owner_.at(i) == cta); + } + if (!owned) { + std::cout << "Error: TMEM dealloc of " << ncols << " columns at column " << col + << " that the CTA does not own" << std::endl; + std::abort(); + } + this->contract_check("tmem.dealloc", cta, col, col + ncols, true); + tmem_used_ &= ~(mask << first); + } + tj_port_busy_ = true; + } break; + case TcuType::TC_MMA: + case TcuType::TC_CP: + case TcuType::TC_COMMIT: { + // One op per cycle into the in-order queue: scalars only. + if (tj_port_busy_ || (tcu_type == TcuType::TC_COMMIT ? !this->tc_commit_ready() + : ops_.size() >= kOpQueue)) { + continue; + } + tj_port_busy_ = true; + tj_t job; + job.cta = (int32_t)core_->scheduler().warp(wid).cta_csrs.cta_id; + job.wid = wid; + job.seq = tj_seq_++; + uint32_t t0 = scalar_thread(trace); + uint32_t s1 = rs1_data.at(t0).u; + uint32_t s2 = rs2_data.at(t0).u; + if (tcu_type == TcuType::TC_COMMIT) { + this->tc_commit(job.cta, wid, s1, s2); + break; + } else if (tcu_type == TcuType::TC_CP) { + job.kind = tc_kind_t::CP; + job.taddr = s1 & 0xffff; + job.cols = s1 >> 16; + job.a_base = s2; + this->copy_check(job); + this->span_post(job); + } else { + job.kind = tc_kind_t::MMA; + this->job_decode(job, s1, s2, rs3_data.at(t0).u); + this->span_post(job); + } + ops_.push_back(job); + } break; #endif default: std::abort(); @@ -714,7 +935,7 @@ class TcuUnit::Impl { // A compute uop holds its input while its leading output slices go // through the FEDP array, under the admission conditions of its fire, // and leaves with the last one. - if (kPeRatio > 1 && !tpuArgs.is_setup_uop && slices_.at(b) + 1 < kPeRatio) { + if (kPeRatio > 1 && !is_tj_op && !tpuArgs.is_setup_uop && slices_.at(b) + 1 < kPeRatio) { #ifdef VX_CFG_TCU_WGMMA_ENABLE bool tbuf_ready = !tcu_is_wgmma(tcu_type) || ((wgmma_ready >> b) & 1u); #else @@ -726,8 +947,14 @@ class TcuUnit::Impl { continue; } - if (simobject_->Outputs.at(b).try_send(trace, kMmaLatency)) { - due.push_back(now + kMmaLatency); + uint32_t delay = kMmaLatency; + #ifdef VX_CFG_TCU_TMEM_ENABLE + if (is_tj_op) { + delay = (tcu_type == TcuType::TMEM_LD) ? (kTmemReadLatency + 1) : 1; + } + #endif + if (simobject_->Outputs.at(b).try_send(trace, delay)) { + due.push_back(now + delay); exec_done_.at(b) = false; slices_.at(b) = 0; DT(3, simobject_->name() << " execute: op=" << tcu_type << ", " << *trace); @@ -755,6 +982,16 @@ class TcuUnit::Impl { tbuf->invalidate_b(); } #endif + + if (cyc_.busy_blocks != 0) { + perf_stats_.mma_busy += cyc_.busy_blocks; + } else if (cyc_.opnd) { + ++perf_stats_.opnd_waits; + } else if (cyc_.other) { + ++perf_stats_.job_other; + } else { + ++perf_stats_.idle; + } } // The tile buffers cannot fetch a descriptor that breaks the alignment rule, @@ -839,6 +1076,7 @@ class TcuUnit::Impl { uint32_t step_n = 0; uint32_t step_k = 0; uint32_t cd_nregs = 0; + uint32_t xtile_n = 0; uint32_t fmt_s = 0; uint32_t desc_b = 0; @@ -892,7 +1130,7 @@ class TcuUnit::Impl { } bool is_sparse = (tcu_type == TcuType::WGMMA_SP); - bool needs_setup = kFedp2K && !tpuArgs.is_a_smem && !is_sparse; + bool needs_setup = wgmma_needs_setup(tpuArgs.is_a_smem, is_sparse); if (tpuArgs.is_first_uop && !needs_setup) { // The first compute uop carries the live descriptors. if (tpuArgs.is_a_smem) { @@ -913,6 +1151,7 @@ class TcuUnit::Impl { req.step_n = tpuArgs.step_n; req.step_k = tpuArgs.step_k; req.cd_nregs = tpuArgs.cd_nregs; + req.xtile_n = xtile_n_of(tpuArgs.cd_nregs); req.fmt_s = tpuArgs.fmt_s; req.desc_b = wgmma_desc_[wid][1]; if (rep < 0) { @@ -920,6 +1159,13 @@ class TcuUnit::Impl { } } + #ifdef VX_CFG_TCU_TMEM_ENABLE + if (rep >= 0 && (run_valid_ || !ops_.empty())) { + std::cout << "Error: WGMMA issued while a tensor job owns the tile buffers" << std::endl; + std::abort(); + } + #endif + // Shared B buffer, keyed by the lowest block with a uop. bool bbuf_ready = true; if (rep >= 0) { @@ -1031,7 +1277,7 @@ class TcuUnit::Impl { key.step_k = req.step_k; key.step_n = req.step_n; } else { - uint32_t n_steps = xtile_n_of(req.cd_nregs) / cfg::tcN; + uint32_t n_steps = req.xtile_n / cfg::tcN; uint32_t blk = req.step_k * n_steps + req.step_n; uint32_t blk_bytes = req.is_sparse ? (kBBlockWordsSp * 4) : (kBBlockWords * 4); uint32_t blks_per_row = req.is_sparse ? 1 : kBSubBlocks; @@ -1047,9 +1293,9 @@ class TcuUnit::Impl { const auto& sd_b = lmem_desc_[req.wid][1]; uint32_t e_bits = elem_bits(req.fmt_s); uint32_t ratio = 32 / e_bits; - uint32_t xtile_n = xtile_n_of(req.cd_nregs); + uint32_t xtile_n = req.xtile_n; uint32_t n_steps = xtile_n / cfg::tcN; - uint32_t k_words = req.is_sparse ? cfg::tcK : kFedpWords; + uint32_t k_words = req.is_sparse ? wg_cfg::sp_k_words : kFedpWords; bool kmajor = (sd_b.ldm != 0); // (step_k, step_n) blocks this refill brings in. @@ -1075,8 +1321,26 @@ class TcuUnit::Impl { } } - uint32_t num_reads = kmajor ? cfg::tcN - : (req.is_sparse && kBSparseTwoFetch) ? 2 : 1; + uint32_t num_reads = (req.is_sparse && kBSparseTwoFetch) ? 2 : 1; + if (kmajor) { + num_reads = cfg::tcN; + } +#ifdef VX_CFG_TCU_TMEM_ENABLE + if (kmajor) { + // The bbuf reads consecutive N-rows that share an LMEM bank row at once. + constexpr uint64_t kBankRowBytes = uint64_t(kLmemBanks) * (VX_CFG_XLEN / 8); + uint32_t k_elem = req.step_k * k_words * ratio * (req.is_sparse ? 2 : 1); + uint64_t prev_row = ~uint64_t(0); + num_reads = 0; + for (uint32_t j = 0; j < cfg::tcN; ++j) { + uint64_t off = elem_offset(sd_b, k_elem, req.step_n * cfg::tcN + j, e_bits, xtile_n, + true, req.is_sparse, false); + uint64_t row = (sd_b.base + off * e_bits / 8) / kBankRowBytes; + num_reads += (row != prev_row); + prev_row = row; + } + } +#endif return split_reads(std::move(lines), num_reads); } @@ -1086,8 +1350,10 @@ class TcuUnit::Impl { const auto& sd_a = lmem_desc_[req.wid][0]; uint32_t e_bits = elem_bits(req.fmt_s); uint32_t ratio = 32 / e_bits; - uint32_t xtile_n = xtile_n_of(req.cd_nregs); - uint32_t k_words = req.is_sparse ? cfg::tcK : kFedpWords; + uint32_t xtile_n = req.xtile_n; + // A full-K sparse step's compressed A has the dense shape (fedpK words). + bool sparse_a = req.is_sparse && !kSpFullK; + uint32_t k_words = sparse_a ? cfg::tcK : kFedpWords; std::vector lines; for (uint32_t row = 0; row < wg_cfg::m_steps * cfg::tcM; ++row) { @@ -1095,14 +1361,14 @@ class TcuUnit::Impl { uint32_t k_elem = (req.step_k * k_words + z) * ratio; for (uint32_t e = 0; e < ratio; ++e) { uint64_t off = elem_offset(sd_a, row, k_elem + e, e_bits, xtile_n, - false, false, req.is_sparse); + false, false, sparse_a); lines.push_back((sd_a.base + off * e_bits / 8) & kLineMask); } } } uint32_t num_reads = (sd_a.ldm != 0) ? (wg_cfg::m_steps * cfg::tcM) - : req.is_sparse ? kAStripeReadsSp : kAStripeReads; + : sparse_a ? kAStripeReadsSp : kAStripeReads; return split_reads(std::move(lines), num_reads); } @@ -1126,6 +1392,701 @@ class TcuUnit::Impl { } return reads; } + +#ifdef VX_CFG_TCU_TMEM_ENABLE + // Tensor memory: VX_CFG_NUM_TCU_BLOCKS * xtileM lanes by kTmemCols 32-bit + // columns. Block b owns lanes [b*xtileM, (b+1)*xtileM), the M rows it + // computes, and holds them fragment-major: a row of its storage is one C/D + // fragment, tcM lanes by tcN columns, and the two M steps of a column group + // sit in two RAMs, so an MMA step reads and writes one row of one RAM and a + // thread-per-row transfer reads both RAMs once. + // + // tc.mma, tc.cp and tc.commit enter one in-order queue per core, with their + // scalars only. The engine runs the head op: a tc.mma is one K step, walked + // (m, n) on all blocks in lockstep with C read from and D written back to + // TMEM; a tc.cp copies whole LMEM bank rows of pre-packed data through the + // tile-buffer port. A tc.commit at the head marks the steps issued so far + // and leaves; it arrives on its barrier once they have been written back. + // tmem.ld/st go to the issuing warp's own block. Their ordering with the + // MMAs is the software's (tc.commit, a barrier wait, tmem::wait_st); the + // contract checker below reports a transfer that breaks it. + static constexpr uint32_t kTmemLanes = VX_CFG_NUM_TCU_BLOCKS * wg_cfg::xtileM; + static constexpr uint32_t kTmemCols = VX_CFG_TCU_TMEM_COLS; + static constexpr uint32_t kTmemThreadsPerLane = VX_CFG_NUM_THREADS / wg_cfg::xtileM; + static constexpr uint32_t kFragCols = wg_cfg::tcN; // columns of a fragment row + static_assert(VX_CFG_NUM_THREADS % wg_cfg::xtileM == 0, "TMEM needs NUM_THREADS to be a multiple of WGMMA M"); + static_assert(wg_cfg::tcM * wg_cfg::tcN == VX_CFG_NUM_THREADS, "C fragment must span the warp"); + static_assert(kPeRatio == 1, "TMEM requires VX_CFG_TCU_PE_RATIO=1"); + static_assert(VX_CFG_FETCH_WIDTH == VX_CFG_ISSUE_WIDTH, "TMEM needs one launch lane per TCU block"); + static_assert(kTmemCols % kFragCols == 0, "TMEM columns are whole fragment groups"); + static_assert(kFedpWords % kFragCols == 0, "a K step of A from TMEM is whole fragment groups"); + static constexpr uint32_t kTmemReadLatency = 1; + static constexpr uint32_t kOpQueue = 4; // tc.mma / tc.cp / tc.commit + static constexpr uint32_t kOpCommits = 2; // commits an op carries + static constexpr uint32_t kCommitQueue = 4; // commits waiting for their steps + static constexpr uint32_t kAllocCols = 32; + static constexpr uint32_t kAllocChunks = kTmemCols / kAllocCols; + static_assert(kTmemCols % kAllocCols == 0 && kAllocChunks <= 32, "TMEM allocation granularity"); + // tc.cp moves whole LMEM bank rows. + static constexpr uint32_t kCpRowWords = kLmemBanks * (VX_CFG_XLEN / 32); + static_assert(kCpRowWords % VX_CFG_NUM_THREADS == 0, "a bank row holds whole fragment rows"); + static constexpr uint32_t kJobKeyBase = 0x10000; // lmem_desc_ key of block 0 + + // Instruction descriptor of a tc.mma (rs1): fmt_s [4:0], sparse [5], + // a_tmem [6], acc_init [7], n_frag - 1 [14:8], D fragment group [22:15], + // side-operand column [31:23] (sparse metadata). + struct idesc_t { + uint32_t fmt_s, n_frag, d_col, side_col; + bool sparse, a_tmem, acc_init; + }; + static idesc_t idesc_decode(uint32_t w) { + idesc_t d; + d.fmt_s = w & 0x1f; + d.sparse = (w >> 5) & 1; + d.a_tmem = (w >> 6) & 1; + d.acc_init = (w >> 7) & 1; + d.n_frag = ((w >> 8) & 0x7f) + 1; + d.d_col = ((w >> 15) & 0xff) * kFragCols; + d.side_col = w >> 23; + return d; + } + + reg_data_t& tmem_at(uint32_t lane, uint32_t col) { + return tmem_.at(lane * kTmemCols + col); + } + + const reg_data_t& tmem_at(uint32_t lane, uint32_t col) const { + return tmem_.at(lane * kTmemCols + col); + } + + enum class tc_kind_t { MMA, CP, COMMIT }; + + struct tj_t { + tc_kind_t kind = tc_kind_t::MMA; + int32_t cta = -1; + uint32_t wid = 0; + uint64_t seq = 0; + // tc.mma + uint32_t fmt_s = 0; + uint32_t fmt_d = 0; + uint32_t n_frag = 0; + bool acc_init = false; + bool sparse = false; + bool a_tmem = false; // a_base is A's first TMEM column + uint32_t taddr = 0; // D's first column (tc.cp: the first column written) + uint32_t side = 0; // metadata column + uint32_t a_base = 0; // shared-memory byte offset, or TMEM column + uint32_t b_base = 0; + uint32_t lda = 0; // leading bytes + uint32_t ldb = 0; + // tc.cp: cols columns of every lane from a_base + uint32_t cols = 0; + // tc.commit, or the commits that follow the op: they arrive once its + // steps (and every earlier op's) are written back. + uint32_t ncommit = 0; + uint32_t bar[2] = {}; + uint32_t cnt[2] = {}; + // MMA walk + uint32_t n = 0; + uint32_t m = 0; + uint64_t start_at = 0; + uint32_t pro_done = 0; + bool a_valid = false; + bool a_fetching = false; + bool b_valid = false; + bool b_fetching = false; + uint32_t b_n = 0; + bool copying = false; + }; + + // An op whose TMEM columns are not settled yet, for the contract checker: + // D (or tc.cp's columns) [d_lo, d_hi), A [a_lo, a_hi), metadata [s_lo, s_hi). + struct tc_span_t { + int32_t cta; + uint64_t seq; + uint32_t d_lo, d_hi, a_lo, a_hi, s_lo, s_hi; + uint64_t steps = ~uint64_t(0); // steps_issued_ after its last step; ~0 while it runs + }; + + struct tc_wb_t { + uint64_t due; + uint32_t m, col0; + }; + + struct tc_commit_t { + uint32_t bar, cnt, wid; + uint64_t target; + }; + + // Columns of one K step's metadata per lane: a lane holds, from bit 0, the + // VX_tcu_sp_mux rows of the step's lower then upper TC_K words. + uint32_t job_meta_cols(const tj_t& job) const { + return std::max(1u, kFedpWords * 2 * elem_ratio(job.fmt_s) / 32); + } + + static uint32_t scalar_thread(const instr_trace_t* trace) { + if (!trace->tmask.test(0)) { + std::cout << "Error: tensor-memory op without thread 0" << std::endl; + std::abort(); + } + return 0; + } + + static void tc_error(const char* op, int32_t cta, const char* err) { + std::cout << "Error: " << op << " (cta=" << cta << "): " << err << std::endl; + std::abort(); + } + + void job_decode(tj_t& job, uint32_t w, uint32_t a, uint32_t b) { + auto d = idesc_decode(w); + job.fmt_s = d.fmt_s; + job.fmt_d = vt::tcu_output_fmt(d.fmt_s); + job.sparse = d.sparse; + job.a_tmem = d.a_tmem; + job.acc_init = d.acc_init; + job.n_frag = d.n_frag; + job.taddr = d.d_col; + job.side = d.side_col; + job.a_base = d.a_tmem ? a : vt::smem_desc_offset(a); + job.lda = d.a_tmem ? 0 : vt::smem_desc_stride(a); + job.b_base = vt::smem_desc_offset(b); + job.ldb = vt::smem_desc_stride(b); + + uint32_t d_end = job.taddr + job.n_frag * wg_cfg::tcN; + auto bad_columns = [&](uint32_t base, uint32_t cols) { + return (base % kFragCols) != 0 || base + cols > kTmemCols + || (base < d_end && job.taddr < base + cols); + }; + const char* err = nullptr; + if (job.sparse && !vt::sparse_format_supported(job.fmt_s)) { + err = "sparse MMA with an unsupported input format"; + } else if (job.sparse && bad_columns(job.side, kFragCols)) { + err = "metadata columns misaligned, past TMEM or overlapping D"; + } else if (job.a_tmem && bad_columns(job.a_base, kFedpWords)) { + err = "A columns misaligned, past TMEM or overlapping D"; + } else if (!job.a_tmem && job.lda == 0) { + err = "A must be row-major (a nonzero leading dimension)"; + } else if (job.ldb == 0) { + err = "B must be K-major (a nonzero leading dimension)"; + } else if (d_end > kTmemCols) { + err = "D columns exceed TMEM"; + } else if (!vt::tcu_output_valid(job.fmt_s, job.fmt_d)) { + err = "unsupported input format"; + } + if (err) { + tc_error("tc.mma", job.cta, err); + } + DT(3, simobject_->name() << " tc-mma: cta=" << job.cta << ", n_frag=" << job.n_frag + << ", taddr=" << job.taddr << ", acc_init=" << job.acc_init + << ", a_base=0x" << std::hex << job.a_base << ", b_base=0x" << job.b_base + << ", lda=0x" << job.lda << ", ldb=0x" << job.ldb << std::dec); + } + + // tc.cp source: the pre-packed fragment rows of columns [taddr, taddr + cols) + // in storage order, column group by column group, block by block, M step by M + // step, NT words each (word i*tcN + j is lane m*tcM + i, column j of the group). + void copy_check(const tj_t& job) { + const char* err = nullptr; + uint32_t words = job.cols * kTmemLanes; + if (job.cols == 0 || (job.cols % kFragCols) != 0 || (job.taddr % kFragCols) != 0) { + err = "copy columns must be whole fragment groups"; + } else if ((job.a_base % (kCpRowWords * 4)) != 0 || (words % kCpRowWords) != 0) { + err = "copy source must be whole LMEM bank rows"; + } else if (job.taddr + job.cols > kTmemCols) { + err = "copy columns exceed TMEM"; + } + if (err) { + tc_error("tc.cp", job.cta, err); + } + DT(3, simobject_->name() << " tc-cp: cta=" << job.cta << ", cols=" << job.cols + << ", taddr=" << job.taddr << ", src=0x" << std::hex << job.a_base << std::dec); + } + + // One read per LMEM bank row. + std::vector copy_reads(const tj_t& job) const { + std::vector reads; + uint32_t rows = job.cols * kTmemLanes / kCpRowWords; + for (uint32_t r = 0; r < rows; ++r) { + uint64_t addr = uint64_t(VX_MEM_LMEM_BASE_ADDR) + job.a_base + uint64_t(r) * kCpRowWords * 4; + TcuTbuf::LmemRead read; + for (uint32_t off = 0; off < kCpRowWords * 4; off += VX_CFG_MEM_BLOCK_SIZE) { + read.push_back((addr + off) & ~uint64_t(VX_CFG_MEM_BLOCK_SIZE - 1)); + } + std::sort(read.begin(), read.end()); + read.erase(std::unique(read.begin(), read.end()), read.end()); + reads.push_back(std::move(read)); + } + return reads; + } + + void copy_write(const tj_t& job) { + auto& tbuf = simobject_->tbuf(); + uint32_t words = job.cols * kTmemLanes; + for (uint32_t w = 0; w < words; ++w) { + uint32_t frag = w / VX_CFG_NUM_THREADS; + uint32_t t = w % VX_CFG_NUM_THREADS; + uint32_t m = frag % wg_cfg::m_steps; + uint32_t b = (frag / wg_cfg::m_steps) % VX_CFG_NUM_TCU_BLOCKS; + uint32_t g = frag / (wg_cfg::m_steps * VX_CFG_NUM_TCU_BLOCKS); + uint32_t lane = b * wg_cfg::xtileM + m * wg_cfg::tcM + t / wg_cfg::tcN; + uint32_t col = job.taddr + g * kFragCols + t % wg_cfg::tcN; + uint64_t addr = uint64_t(VX_MEM_LMEM_BASE_ADDR) + job.a_base + uint64_t(w) * 4; + auto line = tbuf->read_c(addr & ~uint64_t(VX_CFG_MEM_BLOCK_SIZE - 1)); + if (!line) { + std::cout << "Error: tc.cp source line 0x" << std::hex << addr << std::dec << " was not read" << std::endl; + std::abort(); + } + uint32_t word; + std::memcpy(&word, line->data() + (addr & (VX_CFG_MEM_BLOCK_SIZE - 1)), 4); + this->tmem_at(lane, col).u64 = nan_box(word); + } + } + + // MX scales of a tensor op's step, kMxSf bytes per A row and B column (scale + // s covers the step's K elements from s * step_elems / kMxSf), as the RTL + // reads them. A: lane l, columns side + s/4, byte s%4. B: byte + // q = col * kMxSf + s of a dense stream of NT*4-byte rows; row r is M step 1 + // of block r % NUM_TCU_BLOCKS at group side/TC_N + 1 + r / NUM_TCU_BLOCKS. + static constexpr uint32_t kMxSf = vt::mx_max_fedp_sf(kFedpWords); + struct job_mx_t { + bool active = false; + uint32_t side = 0, m = 0, n = 0, block = 0; + }; + job_mx_t job_mx_; + + uint32_t tmem_scale_a(uint32_t i, uint32_t s) const { + uint32_t lane = job_mx_.block * wg_cfg::xtileM + job_mx_.m * cfg::tcM + i; + uint32_t word = this->tmem_at(lane, job_mx_.side + s / 4).u32; + return (word >> (8 * (s % 4))) & 0xff; + } + + uint32_t tmem_scale_b(uint32_t j, uint32_t s) const { + constexpr uint32_t kRowBytes = VX_CFG_NUM_THREADS * 4; + uint32_t q = (job_mx_.n * cfg::tcN + j) * kMxSf + s; + uint32_t r = q / kRowBytes; + uint32_t o = q % kRowBytes; + uint32_t blk = r % VX_CFG_NUM_TCU_BLOCKS; + uint32_t g = job_mx_.side / cfg::tcN + 1 + r / VX_CFG_NUM_TCU_BLOCKS; + uint32_t w = o / 4; + uint32_t lane = blk * wg_cfg::xtileM + cfg::tcM + w / cfg::tcN; + uint32_t word = this->tmem_at(lane, g * cfg::tcN + w % cfg::tcN).u32; + return (word >> (8 * (o % 4))) & 0xff; + } + + // Latch the op's metadata from TMEM into each block's job metadata slot, in + // the bank layout mma_lmem reads: one fragment group, both M steps, once. + void job_load_meta(const tj_t& job) { + uint32_t row_w = cfg::tcK * 2 * elem_ratio(job.fmt_s); + for (uint32_t b = 0; b < VX_CFG_NUM_TCU_BLOCKS; ++b) { + auto& meta = sparse_meta_.at(this->meta_slot(kJobKeyBase + b)); + std::fill(meta.begin(), meta.end(), 0); + for (uint32_t lane = 0; lane < wg_cfg::xtileM; ++lane) { + uint32_t m = lane / cfg::tcM; + uint32_t i = lane % cfg::tcM; + for (uint32_t h = 0; h < kFedpWords / cfg::tcK; ++h) { + for (uint32_t bit = 0; bit < row_w; ++bit) { + uint32_t src = h * row_w + bit; + uint32_t word = this->tmem_at(b * wg_cfg::xtileM + lane, job.side + src / 32).u32; + uint32_t dst = i * row_w + bit; + uint32_t bank = m * (cfg::k_steps / 2) + h; + meta.at(bank * kMaxMetaCols + dst / 32) |= ((word >> (src % 32)) & 1u) << (dst % 32); + } + } + } + } + } + + // Point each block's LMEM descriptors at the op's K step. + void job_set_descs(const tj_t& job) { + uint32_t e_bits = elem_bits(job.fmt_s); + uint64_t a_addr = uint64_t(VX_MEM_LMEM_BASE_ADDR) + job.a_base; + uint64_t b_addr = uint64_t(VX_MEM_LMEM_BASE_ADDR) + job.b_base; + for (uint32_t b = 0; b < VX_CFG_NUM_TCU_BLOCKS; ++b) { + auto& d = lmem_desc_[kJobKeyBase + b]; + d[0] = {a_addr + uint64_t(b) * wg_cfg::xtileM * job.lda, job.lda * 8 / e_bits, false}; + d[1] = {b_addr, job.ldb * 8 / e_bits, false}; + } + } + + // A dense K-major block's row reads stay in flight together. + static uint32_t job_b_inflight(const tj_t& job) { + return (!job.sparse && job.ldb != 0) ? cfg::tcN : 1; + } + + tbuf_req_t job_req(const tj_t& job, uint32_t b, uint32_t n = 0) const { + tbuf_req_t req; + req.valid = true; + req.wid = kJobKeyBase + b; + req.cta = job.cta; + req.a_is_smem = !job.a_tmem; + req.is_sparse = job.sparse; + req.step_m = job.m; + req.step_n = n; + req.xtile_n = job.n_frag * cfg::tcN; + req.fmt_s = job.fmt_s; + return req; + } + + // TMEM reads ahead of an MMA's first step: the metadata row, then A, one + // fragment group (both M steps) per read. + uint32_t job_pro_reads(const tj_t& job) const { + bool side = job.sparse || vt::mx_scale_format(job.fmt_s); + return (side ? 1 : 0) + (job.a_tmem ? kFedpWords / kFragCols : 0); + } + + // D write-backs land in order, kFedpLatency after their step. + void steps_retire(uint64_t now) { + while (!step_wb_.empty() && step_wb_.front().due < now) { + step_wb_.pop_front(); + ++steps_done_; + } + } + + bool job_writing(uint64_t now) const { + return !step_wb_.empty() && step_wb_.front().due == now; + } + + // Consecutive MMAs on the same accumulators: a step waits while its C + // fragment's D write-back is still in flight. + bool row_hazard(uint32_t m, uint32_t col0) const { + for (auto& wb : step_wb_) { + if (wb.m == m && wb.col0 == col0) { + return true; + } + } + return false; + } + + // ---- contract checker ---- + + void span_settle() { + while (!spans_.empty() && spans_.front().steps <= steps_done_) { + spans_.pop_front(); + } + } + + // A transfer or dealloc of the CTA's columns [lo, hi) while an op of the CTA + // that reads or writes them is unsettled breaks the tcgen05 ordering contract. + void contract_check(const char* op, int32_t cta, uint32_t lo, uint32_t hi, bool is_write) { + this->span_settle(); + for (auto& s : spans_) { + if (s.cta != cta) { + continue; + } + bool d_hit = lo < s.d_hi && s.d_lo < hi; + bool r_hit = (lo < s.a_hi && s.a_lo < hi) || (lo < s.s_hi && s.s_lo < hi); + if (d_hit || (is_write && r_hit)) { + std::cout << "Error: TMEM contract violation: " << op << " (cta=" << cta << ") of columns [" + << lo << ", " << hi << ") while tensor op " << s.seq + << " still uses them; wait for its tc.commit barrier (and tmem::wait_st before an MMA reads stored columns)" << std::endl; + std::abort(); + } + } + } + + void span_post(const tj_t& job) { + tc_span_t s{job.cta, job.seq, 0, 0, 0, 0, 0, 0}; + if (job.kind == tc_kind_t::CP) { + s.d_lo = job.taddr; + s.d_hi = job.taddr + job.cols; + } else { + s.d_lo = job.taddr; + s.d_hi = job.taddr + job.n_frag * wg_cfg::tcN; + if (job.a_tmem) { + s.a_lo = job.a_base; + s.a_hi = job.a_base + kFedpWords; + } + if (job.sparse) { + s.s_lo = job.side; + s.s_hi = job.side + kFragCols; + } + } + spans_.push_back(s); + } + + void span_ran(uint64_t seq) { + for (auto& s : spans_) { + if (s.seq == seq) { + s.steps = steps_issued_; + } + } + } + + // ---- engine ---- + + // One commit arrival per cycle, the oldest first, once its steps are written. + void job_bar_op() { + if (commits_.empty() || commits_.front().target > steps_done_) { + return; + } + auto& c = commits_.front(); + DT(3, simobject_->name() << " tc-commit: bar=0x" << std::hex << c.bar << std::dec); + core_->barrier_arrive(bar_decode_id(c.bar, VX_CFG_NUM_BARRIERS), c.cnt, c.wid, false); + commits_.pop_front(); + } + + // An op leaving the engine posts its commits, marking the steps issued so far. + bool job_post_commits(const tj_t& job) { + if (commits_.size() + job.ncommit > kCommitQueue) { + return false; + } + for (uint32_t c = 0; c < job.ncommit; ++c) { + commits_.push_back({job.bar[c], job.cnt[c], job.wid, steps_issued_}); + } + return true; + } + + // A tc.commit rides on the youngest op not yet out of the engine, or posts + // at once when there is none; else it queues as an op of its own. + // The running op takes one only while it is a tc.mma short of its last step. + bool run_open() const { + return run_valid_ && run_.kind == tc_kind_t::MMA + && !(run_.m + 1 == wg_cfg::m_steps && run_.n + 1 == run_.n_frag); + } + + void tc_commit(int32_t cta, uint32_t wid, uint32_t bar, uint32_t cnt) { + tj_t* young = !ops_.empty() ? &ops_.back() : (this->run_open() ? &run_ : nullptr); + if (young != nullptr && young->ncommit < kOpCommits) { + young->bar[young->ncommit] = bar; + young->cnt[young->ncommit] = cnt; + ++young->ncommit; + return; + } + tj_t job; + job.kind = tc_kind_t::COMMIT; + job.cta = cta; + job.wid = wid; + job.seq = tj_seq_++; + job.ncommit = 1; + job.bar[0] = bar; + job.cnt[0] = cnt; + ops_.push_back(job); + } + + bool tc_commit_ready() const { + tj_t const* young = !ops_.empty() ? &ops_.back() : (this->run_open() ? &run_ : nullptr); + return (young != nullptr && young->ncommit < kOpCommits) || ops_.size() < kOpQueue; + } + + void job_step() { + uint64_t now = SimPlatform::instance().cycles(); + this->steps_retire(now); + this->job_bar_op(); + + if (!commits_.empty() || (run_valid_ && run_.kind == tc_kind_t::CP)) { + cyc_.other = true; + } + + // A tmem.ld has priority over the running op's TMEM reads; the op loses + // the cycle after the transfer's. + bool rd_taken = tmem_rd_taken_; + tmem_rd_taken_ = false; + + if (run_valid_) { + if (run_.kind == tc_kind_t::CP) { + this->job_copy(now); + } else { + this->job_run(run_, rd_taken); + } + if (run_valid_) { + return; + } + } + // The datapath is free: the head op takes it in the same cycle. + if (ops_.empty()) { + return; + } + auto& head = ops_.front(); + if (head.kind == tc_kind_t::COMMIT) { + if (this->job_post_commits(head)) { + ops_.pop_front(); + } + return; + } + run_ = head; + run_valid_ = true; + ops_.pop_front(); + cyc_.other = true; + if (run_.kind == tc_kind_t::CP) { + DT(3, simobject_->name() << " tc-cp-run: cta=" << run_.cta); + run_.start_at = now + 1; + } else { + DT(3, simobject_->name() << " tc-run: cta=" << run_.cta); + run_.start_at = now + 1; + this->job_set_descs(run_); + } + } + + // The copy's rows land in TMEM once read; the op then leaves the engine. + // It starts once the steps in flight are written back, as its rows share + // the write port with them. + void job_copy(uint64_t now) { + auto& tbuf = simobject_->tbuf(); + if (!run_.copying) { + if (now >= run_.start_at && steps_done_ == steps_issued_) { + tbuf->fill_c(this->copy_reads(run_)); + run_.copying = true; + } + return; + } + if (tbuf->filling_c()) { + return; + } + if (!this->job_post_commits(run_)) { + return; + } + this->copy_write(run_); + this->span_ran(run_.seq); + run_valid_ = false; + } + + // One MMA step per cycle on all blocks. A step's A stripes (first step) and + // B block are fetched when it is presented. + void job_run(tj_t& job, bool rd_taken) { + auto& tbuf = simobject_->tbuf(); + uint64_t now = SimPlatform::instance().cycles(); + if (now < job.start_at) { + cyc_.other = true; + return; + } + + // Prologue: metadata and A come over the TMEM read port, all blocks in + // parallel, ahead of the first step. + uint32_t pro_reads = this->job_pro_reads(job); + if (job.pro_done < pro_reads) { + if (!rd_taken && ++job.pro_done == pro_reads) { + if (job.sparse) { + this->job_load_meta(job); + } + job.a_valid = job.a_tmem; + } + ++perf_stats_.tbuf_stalls; + cyc_.opnd = true; + return; + } + + bool landed = false; + if (!job.a_valid) { + if (!job.a_fetching) { + for (uint32_t b = 0; b < VX_CFG_NUM_TCU_BLOCKS; ++b) { + tbuf->fill_a(b, this->a_refill(this->job_req(job, b))); + } + job.a_fetching = true; + } else { + bool filling = false; + for (uint32_t b = 0; b < VX_CFG_NUM_TCU_BLOCKS; ++b) { + filling |= tbuf->filling_a(b); + } + if (!filling) { + job.a_fetching = false; + job.a_valid = true; + landed = true; + } + } + } + + // B: the step's N block, refetched when the step moves to the next one. + if (job.b_fetching) { + if (!tbuf->filling_b()) { + job.b_fetching = false; + job.b_valid = true; + landed = (job.b_n == job.n); + } + } else if (!job.b_valid || job.b_n != job.n) { + tbuf->fill_b(this->b_refill(this->job_req(job, 0, job.n)), this->job_b_inflight(job)); + job.b_fetching = true; + job.b_valid = false; + job.b_n = job.n; + } + bool b_ready = job.b_valid && job.b_n == job.n; + + // A step presents the cycle after its operands land. + if (!job.a_valid || !b_ready || landed) { + ++perf_stats_.tbuf_stalls; + cyc_.opnd = true; + return; + } + uint32_t col0 = job.taddr + job.n * wg_cfg::tcN; + bool zero_c = job.acc_init; + bool last_step = (job.m + 1 == wg_cfg::m_steps) && (job.n + 1 == job.n_frag); + if (rd_taken || (!zero_c && this->row_hazard(job.m, col0)) + || (last_step && commits_.size() + job.ncommit > kCommitQueue)) { + cyc_.other = true; + return; + } + + // Thread t of fragment (m, n) is M row m*tcM + t/tcN, N column n*tcN + t%tcN. + uint32_t xtile_n = job.n_frag * cfg::tcN; + static const RegDataVec kNone; + RegDataVec c_frag(VX_CFG_NUM_THREADS); + RegDataVec d_frag(VX_CFG_NUM_THREADS); + RegDataVec a_lo(VX_CFG_NUM_THREADS); + RegDataVec a_hi(VX_CFG_NUM_THREADS); + for (uint32_t b = 0; b < VX_CFG_NUM_TCU_BLOCKS; ++b) { + uint32_t lane0 = b * wg_cfg::xtileM + job.m * wg_cfg::tcM; + if (job.a_tmem) { + // The operand layout of the register-A path: rs1 lower, rs2 upper K words. + for (uint32_t i = 0; i < cfg::tcM; ++i) { + for (uint32_t z = 0; z < cfg::tcK; ++z) { + a_lo.at(i * cfg::tcK + z) = this->tmem_at(lane0 + i, job.a_base + z); + a_hi.at(i * cfg::tcK + z) = this->tmem_at(lane0 + i, job.a_base + cfg::tcK + z); + } + } + } + for (uint32_t t = 0; t < VX_CFG_NUM_THREADS; ++t) { + c_frag.at(t) = zero_c ? reg_data_t{} + : this->tmem_at(lane0 + t / wg_cfg::tcN, col0 + t % wg_cfg::tcN); + } + cur_block_ = b; + job_mx_ = {vt::mx_scale_format(job.fmt_s), job.side, job.m, job.n, b}; + this->mma_lmem(kJobKeyBase + b, job.fmt_s, job.fmt_d, job.m, job.n, 0, + job.a_tmem ? a_lo : kNone, job.a_tmem ? a_hi : kNone, c_frag, d_frag, + job.sparse, !job.a_tmem, xtile_n); + for (uint32_t t = 0; t < VX_CFG_NUM_THREADS; ++t) { + this->tmem_at(lane0 + t / wg_cfg::tcN, col0 + t % wg_cfg::tcN) = d_frag.at(t); + } + } + ++perf_stats_.tj_mma_uops; + ++steps_issued_; + step_wb_.push_back({now + kFedpLatency, job.m, col0}); + cyc_.busy_blocks += VX_CFG_NUM_TCU_BLOCKS; + + if (++job.m < wg_cfg::m_steps) { + return; + } + job.m = 0; + if (++job.n < job.n_frag) { + return; + } + // Last step issued: the op leaves the engine and posts its commits; its + // write-backs settle it. + this->job_post_commits(job); + this->span_ran(job.seq); + run_valid_ = false; + } + + // ---- allocation ---- + + // The lowest free run of `chunks` chunks aligned to its size, or ~0. + uint32_t alloc_fit(uint32_t chunks) const { + uint32_t mask = (chunks == 32) ? ~0u : ((1u << chunks) - 1); + for (uint32_t i = 0; i + chunks <= kAllocChunks; i += chunks) { + if ((tmem_used_ & (mask << i)) == 0) { + return i; + } + } + return ~0u; + } + + // A CTA's last warp has retired: free the columns it still owns. + void cta_exit(int32_t cta) { + for (uint32_t i = 0; i < kAllocChunks; ++i) { + if (((tmem_used_ >> i) & 1u) && tmem_owner_.at(i) == cta) { + tmem_used_ &= ~(1u << i); + } + } + } +#endif // VX_CFG_TCU_TMEM_ENABLE #endif // VX_CFG_TCU_WGMMA_ENABLE @@ -1229,29 +2190,55 @@ class TcuUnit::Impl { std::abort(); } - uint32_t ratio = elem_ratio(fmt_s); - uint32_t k_words = is_sparse ? cfg::tcK : kFedpWords; + // NRC: cd_nregs 0/1/2 → 8/16/32; xtileN = NRC * NT / xtileM. + uint32_t nrc = (cd_nregs == 0) ? 8 : (cd_nregs == 1) ? 16 : 32; + uint32_t xtile_n = (nrc * VX_CFG_NUM_THREADS) / wg_cfg::xtileM; // Decode smem descriptors (B always from smem, A optionally). if (is_setup_uop) { wgmma_desc_[wid][0] = a_desc; wgmma_desc_[wid][1] = b_desc; this->decode_descs(wid, fmt_s, is_a_smem, is_sparse); - uint32_t nrc = (cd_nregs == 0) ? 8 : (cd_nregs == 1) ? 16 : 32; - cur_xtile_n_ = (nrc * VX_CFG_NUM_THREADS) / wg_cfg::xtileM; + cur_xtile_n_ = xtile_n; return; } - lmem_desc_t sd_a = lmem_desc_[wid][0]; - lmem_desc_t sd_b = lmem_desc_[wid][1]; + this->mma_lmem(wid, fmt_s, fmt_d, step_m, step_n, step_k, + rs1_data, rs2_data, rs3_data, rd_data, + is_sparse, is_a_smem, xtile_n); + __unused(b_desc); + } + + // One WGMMA compute uop with B (and A when is_a_smem) read through the tile + // buffers. `key` selects the decoded LMEM descriptors. + void mma_lmem(uint32_t key, + uint32_t fmt_s, + uint32_t fmt_d, + uint32_t step_m, + uint32_t step_n, + uint32_t step_k, + const RegDataVec& rs1_data, + const RegDataVec& rs2_data, + const RegDataVec& rs3_data, + RegDataVec& rd_data, + bool is_sparse, + bool is_a_smem, + uint32_t xtile_n) { + uint32_t wid = key; + uint32_t ratio = elem_ratio(fmt_s); + uint32_t k_words = is_sparse ? wg_cfg::sp_k_words : kFedpWords; + lmem_desc_t sd_a = lmem_desc_[key][0]; + lmem_desc_t sd_b = lmem_desc_[key][1]; + if (is_sparse && kSpFullK && sd_b.ldm == 0) { + // A block-major sparse B block holds tcK K words, not the fedpK a + // full-K sparse step consumes. + std::cout << "Error: a full-K sparse step requires a K-major B descriptor (ldm != 0)" << std::endl; + std::abort(); + } // load_lmem_word distinguishes A from B by descriptor base. cur_a_desc_base_ = is_a_smem ? sd_a.base : ~uint64_t(0); cur_is_sparse_ = is_sparse; - // NRC: cd_nregs 0/1/2 → 8/16/32; xtileN = NRC * NT / xtileM. - { - uint32_t nrc = (cd_nregs == 0) ? 8 : (cd_nregs == 1) ? 16 : 32; - cur_xtile_n_ = (nrc * VX_CFG_NUM_THREADS) / wg_cfg::xtileM; - } + cur_xtile_n_ = xtile_n; reg_data_t a_tile[cfg::tcM * kFedpWords] = {}; for (uint32_t i = 0; i < cfg::tcM; ++i) { @@ -1275,13 +2262,15 @@ class TcuUnit::Impl { if (is_sparse) { uint32_t ebits = elem_bits(fmt_s); uint32_t rtl_i_ratio = 32 / ebits; - uint32_t meta_row_w = k_words * 2 * rtl_i_ratio; - // Bank encoding {step_m, step_k_half}: m=1 → bank (cfg::k_steps/2). - uint32_t wg_bank = step_m * (cfg::k_steps / 2) + step_k; + // One metadata bank per tcK compressed words: bank {step_m, + // step_k_half}, m=1 -> bank (cfg::k_steps/2). A full-K sparse step spans + // two banks (its upper FEDP half reads {step_m, 1}). + uint32_t meta_row_w = cfg::tcK * 2 * rtl_i_ratio; + uint32_t wg_bank = 0; // Metadata is preloaded into sparse_meta_ via TCU_LD before dispatch. auto meta_bit_wg = [&](uint32_t bit_idx) -> uint32_t { uint32_t word_idx = wg_bank * kMaxMetaCols + bit_idx / 32; - uint32_t word_val = sparse_meta_.at(wid).at(word_idx); + uint32_t word_val = sparse_meta_.at(this->meta_slot(wid)).at(word_idx); // Trace: META_RD (CSV: wid,step_m,step_k,bank,value). if (const char* p = std::getenv("VORTEX_TCU_TRACE")) { if (p[0] == '1' && (bit_idx % 32) == 0) { @@ -1296,10 +2285,12 @@ class TcuUnit::Impl { for (uint32_t j = 0; j < cfg::tcN; ++j) { uint32_t b_col_idx = step_n * cfg::tcN + j; for (uint32_t z = 0; z < k_words; ++z) { + uint32_t zz = z % cfg::tcK; + wg_bank = step_m * (cfg::k_steps / 2) + step_k + z / cfg::tcK; uint32_t lo = 0, hi = 0; for (uint32_t b = 0; b < rtl_i_ratio; ++b) { - lo |= meta_bit_wg(row_base + rtl_i_ratio * z + b) << b; - hi |= meta_bit_wg(row_base + rtl_i_ratio * (k_words + z) + b) << b; + lo |= meta_bit_wg(row_base + rtl_i_ratio * zz + b) << b; + hi |= meta_bit_wg(row_base + rtl_i_ratio * (cfg::tcK + zz) + b) << b; } constexpr uint32_t kCompression = 2; uint32_t k_elem_b0 = (step_k * k_words + z) * ratio * kCompression; @@ -1335,7 +2326,6 @@ class TcuUnit::Impl { a_tile, b_tile, rs3_data, rd_data, is_sparse, k_words, k_words, wg_cfg::k_steps * wg_cfg::fedpK); - __unused(b_desc); } const PerfStats& perf_stats() const { @@ -1398,11 +2388,26 @@ class TcuUnit::Impl { uint32_t ratio = elem_ratio(fmt_s); uint32_t scale_blocks_k = mx_tile_scale_blocks(fmt_s, tile_k_words); uint32_t block_size = vt::mx_scale_block_size(fmt_s); - auto scale_a = [&](uint32_t elem_k) { +#ifdef VX_CFG_TCU_TMEM_ENABLE + // A tensor op's step reads its scales from TMEM (tmem_scale_a/b). + bool job_mx = (wid >= kJobKeyBase) && job_mx_.active; + uint32_t step_elems = fedp_words * ratio * (is_sparse ? 2 : 1); +#endif + auto scale_a = [&](uint32_t elem_k) -> uint32_t { +#ifdef VX_CFG_TCU_TMEM_ENABLE + if (job_mx) { + return this->tmem_scale_a(i, elem_k * kMxSf / step_elems); + } +#endif uint32_t row = step_m * cfg::tcM + i; return meta_byte(mx_meta_a_.at(wid), row * scale_blocks_k + elem_k / block_size); }; - auto scale_b = [&](uint32_t elem_k) { + auto scale_b = [&](uint32_t elem_k) -> uint32_t { +#ifdef VX_CFG_TCU_TMEM_ENABLE + if (job_mx) { + return this->tmem_scale_b(j, elem_k * kMxSf / step_elems); + } +#endif uint32_t col = step_n * cfg::tcN + j; return meta_byte(mx_meta_b_.at(wid), col * scale_blocks_k + elem_k / block_size); }; @@ -1597,7 +2602,8 @@ class TcuUnit::Impl { if (desc.base == cur_a_desc_base_) { uint32_t b = cur_block_; return gather_word([&](uint64_t addr) { return tbuf->read_a(b, addr); }, - desc, row, col, fmt_s, pack_along_row, false, cur_is_sparse_); + desc, row, col, fmt_s, pack_along_row, false, + cur_is_sparse_ && !kSpFullK); } return gather_word([&](uint64_t addr) { return tbuf->read_b(addr); }, desc, row, col, fmt_s, pack_along_row, sparse_b, false); @@ -1606,6 +2612,16 @@ class TcuUnit::Impl { static constexpr uint32_t kSparseKSteps = cfg::k_steps / 2; static constexpr uint32_t kMetaBanks = cfg::m_steps * kSparseKSteps; static constexpr uint32_t kMaxMetaCols = VX_CFG_NUM_THREADS / 2; +#ifdef VX_CFG_TCU_TMEM_ENABLE + // Tensor jobs hold one K-tile's metadata per block, after the warps' slots. + static constexpr uint32_t kMetaSlots = VX_CFG_NUM_WARPS + VX_CFG_NUM_TCU_BLOCKS; + uint32_t meta_slot(uint32_t key) const { + return (key >= kJobKeyBase) ? (VX_CFG_NUM_WARPS + key - kJobKeyBase) : key; + } +#else + static constexpr uint32_t kMetaSlots = VX_CFG_NUM_WARPS; + uint32_t meta_slot(uint32_t key) const { return key; } +#endif // FEDP tile computation for both WMMA and WGMMA. // a_tile: [tcM][k_words] flat array of pre-loaded A operand words. @@ -1658,8 +2674,15 @@ class TcuUnit::Impl { std::unordered_map lmem_desc_; std::array, VX_CFG_NUM_WARPS> wgmma_desc_; mutable PerfStats perf_stats_; + // This cycle's MMA activity, for the busy/wait breakdown. + struct { + uint32_t busy_blocks; + bool opnd, other; + } cyc_ = {}; // Per-block guard: execute already happened for this trace; reset on pop(). std::array exec_done_; + std::array tj_fresh_; + std::array tj_hold_until_; // Output slices of the head uop already through the FEDP array. std::array slices_; // Cycles at which each block's results sent so far become visible. @@ -1668,6 +2691,7 @@ class TcuUnit::Impl { std::array in_wgmma_; // Current block index, set before delegating to wgmma(). uint32_t cur_block_ = 0; + // B buffer slot read by the current MMA. // A-descriptor base for the current wgmma(); distinguishes A from B in load_lmem_word. uint64_t cur_a_desc_base_ = ~uint64_t(0); bool cur_is_sparse_ = false; @@ -1679,6 +2703,23 @@ class TcuUnit::Impl { std::array abuf_; bbuf_slot_t bbuf_; #endif +#ifdef VX_CFG_TCU_TMEM_ENABLE + std::vector tmem_; // [lane][column] + std::deque ops_; // posted tc.mma / tc.cp / tc.commit, in order + tj_t run_; // the op the engine runs + bool run_valid_ = false; + std::deque commits_; + std::deque step_wb_; // in-flight steps' D write-backs, in order + std::deque spans_; // unsettled ops, for the contract checker + uint64_t steps_issued_ = 0; + uint64_t steps_done_ = 0; + bool tj_port_busy_ = false; + bool tmem_rd_taken_ = false; + std::array blk_port_ops_{}; // port cycles of the head transfer so far + uint64_t tj_seq_ = 0; + std::array tmem_owner_{}; + uint32_t tmem_used_ = 0; // allocated kAllocCols-column chunks, bit per chunk +#endif }; /////////////////////////////////////////////////////////////////////////////// @@ -1702,6 +2743,20 @@ op_string_t TcuUnit::op_string(TcuType tcu_type, IntrTcuArgs args) { case TcuType::TCU_LD: return {"TCU_LD." + std::string((args.fmt_d & 0x10) ? "MX." : "SP.") + std::string(vt::fmt_string(args.fmt_s)) + ".slot" + std::to_string(args.fmt_d & 0xf), ""}; + case TcuType::TMEM_LD: + return {std::string(args.tmem_row ? "TMEM_LD.F." : "TMEM_LD.") + std::to_string(args.tmem_n) + "." + std::to_string(args.tmem_idx), ""}; + case TcuType::TMEM_ST: + return {std::string(args.tmem_row ? "TMEM_ST.F." : "TMEM_ST.") + std::to_string(args.tmem_n) + "." + std::to_string(args.tmem_idx), ""}; + case TcuType::TMEM_ALLOC: + return {"TMEM_ALLOC", ""}; + case TcuType::TMEM_DEALLOC: + return {"TMEM_DEALLOC", ""}; + case TcuType::TC_MMA: + return {"TC_MMA", ""}; + case TcuType::TC_COMMIT: + return {"TC_COMMIT", ""}; + case TcuType::TC_CP: + return {"TC_CP", ""}; default: std::abort(); } @@ -1718,6 +2773,12 @@ uint32_t TcuUopGen::uop_count(const Instr& instr) { auto args = std::get(instr.get_args()); #endif +#ifdef VX_CFG_TCU_TMEM_ENABLE + if (tcu_is_tmem(tcu_type)) { + return std::get(instr.get_args()).tmem_n; + } +#endif + if (tcu_is_wmma(tcu_type)) { using wmma = vt::wmma_config_t; bool is_sparse = tcu_is_sparse(tcu_type); @@ -1732,7 +2793,7 @@ uint32_t TcuUopGen::uop_count(const Instr& instr) { #ifdef VX_CFG_TCU_WGMMA_ENABLE if (tcu_is_wgmma(tcu_type)) { bool is_sparse = tcu_is_sparse(tcu_type); - bool needs_setup = kFedp2K && !args.is_a_smem && !is_sparse; + bool needs_setup = wgmma_needs_setup(args.is_a_smem, is_sparse); uint32_t nrc = (args.cd_nregs == 0) ? 8 : (args.cd_nregs == 1) ? 16 : 32; uint32_t k_count = is_sparse ? std::max(1u, wg_cfg::k_steps / 2) : wg_cfg::k_steps; uint32_t mma_uops = k_count * nrc; @@ -1755,6 +2816,29 @@ Instr::Ptr TcuUopGen::get(const Instr& macro_instr, uint32_t uop_index) { uop_instr->set_parent_uuid(parent_uuid); uop_instr->set_fcsr_use(macro_instr.fcsr_reads(), macro_instr.fcsr_writes()); +#ifdef VX_CFG_TCU_TMEM_ENABLE + if (tcu_is_tmem(tcu_type)) { + // Uop i moves FP register (f + i) to or from its TMEM columns. + uint32_t freg = (tcu_type == TcuType::TMEM_LD) ? args.fmt_d : args.fmt_s; + if (freg + args.tmem_n > 32) { + std::cout << "Error: TMEM transfer of " << args.tmem_n << " registers from f" + << freg << " exceeds the register file" << std::endl; + std::abort(); + } + IntrTcuArgs uop_args = args; + uop_args.tmem_idx = uop_index; + uop_instr->set_op_type(tcu_type); + uop_instr->set_args(uop_args); + uop_instr->set_src_reg(0, macro_instr.get_src_reg(0).idx, RegType::Integer); + if (tcu_type == TcuType::TMEM_LD) { + uop_instr->set_dest_reg(freg + uop_index, RegType::Float); + } else { + uop_instr->set_src_reg(1, freg + uop_index, RegType::Float); + } + return uop_instr; + } +#endif + if (tcu_is_wmma(tcu_type)) { using wmma = vt::wmma_config_t; constexpr uint32_t rc_base = 0, ra_base = 10; @@ -1782,7 +2866,7 @@ Instr::Ptr TcuUopGen::get(const Instr& macro_instr, uint32_t uop_index) { uint32_t actual_n = lg_k ? (n_sp >> lg_k) : n_sp; uint32_t reg_rs3 = rc_base + (mma_idx >> 1); uop_instr->set_op_type(TcuType::WMMA_SP); - uop_instr->set_args(IntrTcuArgs{0, 0, fmt_s, fmt_d, m_sp, actual_n, 0, 0, 0, 0}); + uop_instr->set_args(IntrTcuArgs{0, 0, fmt_s, fmt_d, m_sp, actual_n, 0, 0, 0, 0, 0, 0, 0}); uop_instr->set_dest_reg(reg_rs3, RegType::Float); uop_instr->set_src_reg(0, ra_base + m_sp, RegType::Float); uop_instr->set_src_reg(1, rb_base + n_sp, RegType::Float); @@ -1817,7 +2901,7 @@ Instr::Ptr TcuUopGen::get(const Instr& macro_instr, uint32_t uop_index) { reg_rs3 = rc_base + frag::rc_off(m, n); } uop_instr->set_op_type(is_sparse ? TcuType::WMMA_SP : TcuType::WMMA); - uop_instr->set_args(IntrTcuArgs{0, 0, fmt_s, fmt_d, m, n, k, 0, 0, 0}); + uop_instr->set_args(IntrTcuArgs{0, 0, fmt_s, fmt_d, m, n, k, 0, 0, 0, 0, 0, 0}); uop_instr->set_dest_reg(reg_rs3, RegType::Float); uop_instr->set_src_reg(0, reg_rs1, RegType::Float); uop_instr->set_src_reg(1, reg_rs2, RegType::Float); @@ -1834,7 +2918,7 @@ Instr::Ptr TcuUopGen::get(const Instr& macro_instr, uint32_t uop_index) { uint32_t fmt_d = args.fmt_d; bool is_sparse = tcu_is_sparse(tcu_type); bool is_a_smem = args.is_a_smem; - bool needs_setup = kFedp2K && !is_a_smem && !is_sparse; + bool needs_setup = wgmma_needs_setup(is_a_smem, is_sparse); uint32_t cd_nregs = args.cd_nregs; uint32_t k_count = is_sparse ? std::max(1u, k_steps / 2) : k_steps; uint32_t total = uop_count(macro_instr); @@ -1845,7 +2929,7 @@ Instr::Ptr TcuUopGen::get(const Instr& macro_instr, uint32_t uop_index) { if (needs_setup && uop_index == 0) { uop_instr->set_args(IntrTcuArgs{is_a_smem ? 1u : 0u, cd_nregs, - fmt_s, fmt_d, 0, 0, 0, 1, 0, 1}); + fmt_s, fmt_d, 0, 0, 0, 1, 0, 1, 0, 0, 0}); uop_instr->set_src_reg(0, a0, RegType::Integer); uop_instr->set_src_reg(1, a1, RegType::Integer); uop_instr->set_fu_lock(true); @@ -1872,7 +2956,7 @@ Instr::Ptr TcuUopGen::get(const Instr& macro_instr, uint32_t uop_index) { bool first = (mma_idx == 0); bool last = (uop_index == (total - 1)); uop_instr->set_args(IntrTcuArgs{is_a_smem ? 1u : 0u, cd_nregs, - fmt_s, fmt_d, m, n, k, first ? 1u : 0u, last ? 1u : 0u, 0}); + fmt_s, fmt_d, m, n, k, first ? 1u : 0u, last ? 1u : 0u, 0, 0, 0, 0}); uop_instr->set_dest_reg(r, RegType::Float); if (!is_a_smem) { uint32_t rs1_off = is_sparse ? m : (m * a_reg_k_steps + k); @@ -1902,6 +2986,9 @@ TcuUnit::TcuUnit(const SimContext &ctx, const char* name, Core* core) #ifdef TCU_META_ENABLE , agu_req_out(TCU_AGU_PORTS, this) , agu_rsp_in(TCU_AGU_PORTS, this) +#endif +#ifdef VX_CFG_TCU_TMEM_ENABLE + , cta_exit_in(this) #endif , result_stall_in(VX_CFG_NUM_TCU_BLOCKS, this) , impl_(new Impl(this, core)) @@ -1924,6 +3011,12 @@ void TcuUnit::on_reset() { } void TcuUnit::on_tick() { +#ifdef VX_CFG_TCU_TMEM_ENABLE + while (!cta_exit_in.empty()) { + impl_->cta_exit(cta_exit_in.peek()); + cta_exit_in.pop(); + } +#endif impl_->tick(); } diff --git a/sim/simx/tcu/tcu_unit.h b/sim/simx/tcu/tcu_unit.h index 45070564d6..ae2c66003e 100644 --- a/sim/simx/tcu/tcu_unit.h +++ b/sim/simx/tcu/tcu_unit.h @@ -20,11 +20,13 @@ #include "instr.h" #include "func_unit.h" #include "tcu_tbuf.h" +#ifdef VX_CFG_TCU_TMEM_ENABLE +#endif // The TCU metadata SRAM is present when any metadata-consuming mode (MX or -// sparse) is enabled. Internal derived macro — not a VX_CFG_* knob; mirrors +// sparse) is enabled with per-warp MMAs (tensor ops take theirs from TMEM). Internal derived macro — not a VX_CFG_* knob; mirrors // the hardware derivation. -#if defined(VX_CFG_TCU_MX_ENABLE) || defined(VX_CFG_TCU_SPARSE_ENABLE) +#if (defined(VX_CFG_TCU_MX_ENABLE) || defined(VX_CFG_TCU_SPARSE_ENABLE)) && defined(VX_CFG_TCU_WMMA_ENABLE) #define TCU_META_ENABLE #endif @@ -70,12 +72,29 @@ class TcuUnit : public FuncUnit { uint64_t tbuf_stalls = 0; // cycles a WGMMA uop waits on its A stripe or the B row, summed over buffers uint64_t tbuf_cache_hits = 0; // cycles the resident B row serves the representative block uint64_t lmem_reads = 0; // bank-row reads issued by the A and B buffers + uint64_t tj_mma_uops = 0; // tc.mma steps (all blocks in lockstep) + uint64_t tmem_stalls = 0; // cycles a TMEM transfer waits on its CTA's ops + uint64_t tmem_xfers = 0; // tmem.ld/st transfers + // Every cycle falls in one bucket: an MMA step fired (block-cycles, so + // utilization is busy / (cycles * blocks)), else operands, other op + // activity, or idle. + uint64_t mma_busy = 0; + uint64_t opnd_waits = 0; + uint64_t job_other = 0; + uint64_t idle = 0; PerfStats& operator+=(const PerfStats& rhs) { this->latency += rhs.latency; this->tbuf_stalls += rhs.tbuf_stalls; this->tbuf_cache_hits += rhs.tbuf_cache_hits; this->lmem_reads += rhs.lmem_reads; + this->tj_mma_uops += rhs.tj_mma_uops; + this->tmem_stalls += rhs.tmem_stalls; + this->tmem_xfers += rhs.tmem_xfers; + this->mma_busy += rhs.mma_busy; + this->opnd_waits += rhs.opnd_waits; + this->job_other += rhs.job_other; + this->idle += rhs.idle; return *this; } }; @@ -90,6 +109,11 @@ class TcuUnit : public FuncUnit { std::vector> agu_req_out; std::vector> agu_rsp_in; #endif +#ifdef VX_CFG_TCU_TMEM_ENABLE + // CTA exits from the dispatcher: the TMEM columns the CTA owns are freed. + SimChannel cta_exit_in; +#endif + // Per block: the cycles its lane-gather buffer refuses a result (its ready // is a register, sent the cycle before). @@ -107,6 +131,7 @@ class TcuUnit : public FuncUnit { RegDataVec& rd_data, bool is_sparse); + void wgmma(uint32_t wid, uint32_t fmt_s, uint32_t fmt_d, diff --git a/sim/simx/types.h b/sim/simx/types.h index 7b71a8a4d4..0c9ae2a1e8 100644 --- a/sim/simx/types.h +++ b/sim/simx/types.h @@ -807,6 +807,13 @@ enum class TcuType { WMMA_SP, // Sparse variants live in distinct op_types so IntrTcuArgs WGMMA_SP, // doesn't carry a per-uop is_sparse bit. TCU_LD, // Warp-level metadata load. rd[4] selects sparse/MX namespace. + TMEM_LD, // TMEM -> FP registers, one uop per register. + TMEM_ST, // FP registers -> TMEM, one uop per register. + TMEM_ALLOC, // rd = first column of rs1 TMEM columns, owned by the CTA; waits until they fit. + TMEM_DEALLOC, // Frees rs2 TMEM columns from column rs1. + TC_MMA, // tcgen05.mma, one K step: rs1 instruction descriptor, rs2 A, rs3 B. + TC_COMMIT, // tcgen05.commit: arrive (count rs2) on barrier rs1 after earlier ops. + TC_CP, // tcgen05.cp: rs1 {columns, taddr}, rs2 source, rs3 stride. }; struct IntrTcuArgs { @@ -820,6 +827,9 @@ struct IntrTcuArgs { uint32_t is_first_uop : 1; // set per-uop by tcu_uops expansion (C4) uint32_t is_last_uop : 1; uint32_t is_setup_uop : 1; // WGMMA descriptor setup uop, no FEDP compute + uint32_t tmem_n : 6; // TMEM_LD/ST register count + uint32_t tmem_idx : 5; // TMEM_LD/ST uop register offset + uint32_t tmem_row : 1; // TMEM_LD/ST: fragment shape (else one lane per thread) }; // Helper: is_sparse derived from op_type (no per-uop bit). @@ -832,6 +842,18 @@ inline bool tcu_is_wgmma(TcuType t) { return t == TcuType::WGMMA || t == TcuType::WGMMA_SP; } +// Helper: TMEM transfers. +inline bool tcu_is_tmem(TcuType t) { + return t == TcuType::TMEM_LD || t == TcuType::TMEM_ST; +} + +// Helper: ops of the tensor-memory port (TMEM transfers, allocation, tc.*). +inline bool tcu_is_tj_op(TcuType t) { + return tcu_is_tmem(t) || t == TcuType::TMEM_ALLOC || t == TcuType::TMEM_DEALLOC + || t == TcuType::TC_MMA || t == TcuType::TC_COMMIT + || t == TcuType::TC_CP; +} + // Helper: WMMA family (covers dense + sparse). inline bool tcu_is_wmma(TcuType t) { return t == TcuType::WMMA || t == TcuType::WMMA_SP; @@ -844,6 +866,13 @@ inline std::ostream &operator<<(std::ostream &os, const TcuType& type) { case TcuType::WMMA_SP: os << "WMMA.SP"; break; case TcuType::WGMMA_SP: os << "WGMMA.SP"; break; case TcuType::TCU_LD: os << "TCU_LD"; break; + case TcuType::TMEM_LD: os << "TMEM_LD"; break; + case TcuType::TMEM_ST: os << "TMEM_ST"; break; + case TcuType::TMEM_ALLOC: os << "TMEM_ALLOC"; break; + case TcuType::TMEM_DEALLOC: os << "TMEM_DEALLOC"; break; + case TcuType::TC_MMA: os << "TC_MMA"; break; + case TcuType::TC_COMMIT: os << "TC_COMMIT"; break; + case TcuType::TC_CP: os << "TC_CP"; break; default: assert(false); } diff --git a/sw/common/tensor_cfg.h b/sw/common/tensor_cfg.h index 06d8576cc5..e629ed738e 100644 --- a/sw/common/tensor_cfg.h +++ b/sw/common/tensor_cfg.h @@ -215,6 +215,39 @@ inline constexpr bool tcu_output_valid(uint32_t it, uint32_t ot) { return (it >= int32::id) ? (ot == int32::id) : (ot == fp32::id); } +// The accumulator format of an input format: int32 for integers, else fp32. +// MX scales a WGMMA/tensor-op FEDP takes per A row and B column of a step +// (VX_tcu_pkg TCU_MX_MAX_SF): the most over the enabled block-scaled formats +// of fedpK words' elements (doubled with sparse support) per scale block. +inline constexpr uint32_t mx_fedp_sf_count(uint32_t data_bits, uint32_t block_elems, uint32_t fedp_k) { +#ifdef VX_CFG_TCU_SPARSE_ENABLE + uint32_t sparse_ratio = 2; +#else + uint32_t sparse_ratio = 1; +#endif + uint32_t fedp_elems = fedp_k * (32 / data_bits) * sparse_ratio; + return (fedp_elems + block_elems - 1) / block_elems; +} + +inline constexpr uint32_t mx_max_fedp_sf(uint32_t fedp_k) { + (void)fedp_k; // unused without a block-scaled format + uint32_t sf = 1; +#ifdef VX_CFG_TCU_FP8_ENABLE + sf = (mx_fedp_sf_count(8, 32, fedp_k) > sf) ? mx_fedp_sf_count(8, 32, fedp_k) : sf; +#endif +#ifdef VX_CFG_TCU_MXFP4_ENABLE + sf = (mx_fedp_sf_count(4, 32, fedp_k) > sf) ? mx_fedp_sf_count(4, 32, fedp_k) : sf; +#endif +#ifdef VX_CFG_TCU_NVFP4_ENABLE + sf = (mx_fedp_sf_count(4, 16, fedp_k) > sf) ? mx_fedp_sf_count(4, 16, fedp_k) : sf; +#endif + return sf; +} + +inline constexpr uint32_t tcu_output_fmt(uint32_t it) { + return (it >= int32::id) ? int32::id : fp32::id; +} + inline constexpr bool mx_scale_format(uint32_t fmt) { switch (fmt) { case mxfp8::id: @@ -420,6 +453,18 @@ struct wgmma_config_t { static constexpr uint32_t k_steps = xtileK / fedpK; static constexpr uint32_t b_blk_k = fedpK * i_ratio; // K elements per dense B block static constexpr uint32_t NRC = NRC_; + // Sparse (2:4) K coverage of a tensor op's step. With tensor memory and + // FEDP2K a sparse step drives every FEDP lane with compressed A (fedpK + // words), so it covers twice the logical K of a dense step, as Blackwell's + // sparse tcgen05.mma. It needs two half-K metadata banks per m-step (WMMA + // k_steps >= 4). Warp WGMMA sparse fills only tcK lanes. +#if defined(VX_CFG_TCU_TMEM_ENABLE) && defined(VX_CFG_TCU_SPARSE_ENABLE) && defined(VX_CFG_TCU_FEDP2K) + static constexpr uint32_t sp_k_mult = (wmma_config_t::k_steps / 2 >= 2) ? (fedpK / tcK) : 1; +#else + static constexpr uint32_t sp_k_mult = 1; +#endif + static constexpr uint32_t tileK_sp = tileK * sp_k_mult; + static constexpr uint32_t sp_k_words = tcK * sp_k_mult; // compressed A words per sparse uop }; } // namespace tensor diff --git a/sw/kernel/include/vx_tmem.h b/sw/kernel/include/vx_tmem.h new file mode 100644 index 0000000000..cb989425e6 --- /dev/null +++ b/sw/kernel/include/vx_tmem.h @@ -0,0 +1,258 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef __VX_TMEM_H__ +#define __VX_TMEM_H__ + +#include +#include +#include +#include + +// Tensor memory (CUSTOM0, funct7 = 5) and tcgen05-style async tensor ops +// (funct7 = 6). +// +// TMEM is one per-core array of lanes x 32-bit columns, addressed +// {lane [31:16], column [15:0]}. A lane is an M row of an MMA: TCU block b +// computes lanes [b*M, (b+1)*M), M being the WGMMA tile M. A column is an N +// element. + +namespace vortex { +namespace tmem { + +// Columns of a fragment row (the WGMMA tile's TC_N): TMEM is stored +// fragment-major, so D, metadata and A-from-TMEM columns and tmem.ld/st column +// addresses are multiples of it. +inline constexpr uint32_t frag_cols() { + uint32_t lg = 0; + while ((1u << (lg + 1)) <= VX_CFG_NUM_THREADS) { + ++lg; + } + return 1u << (lg / 2); +} + +// TMEM lanes of a TCU block: the WGMMA tile M. +inline constexpr uint32_t block_lanes() { + uint32_t lg = 0; + while ((1u << (lg + 1)) <= VX_CFG_NUM_THREADS) { + ++lg; + } + return 2u << ((lg + 1) / 2); +} + +// The calling warp's first TMEM lane. A warp's tmem.ld/st reach only the +// lanes of the TCU block it issues to (warp w -> block w % ISSUE_WIDTH); a +// CTA launched with a TMEM budget (vx_launch_info_t::tmem_cols) has warp rank +// r on block r % ISSUE_WIDTH. +inline uint32_t warp_lane() { + return (vx_warp_id() % VX_CFG_NUM_TCU_BLOCKS) * block_lanes(); +} + +// tc.mma instruction descriptor: one K step of D (n_frag fragments of TC_N +// columns from column d_col) = A . B (+ D unless acc_init), IType inputs +// (fp32 out, int32 for integer inputs). +// sparse: A is 2:4 compressed and side_col is the first TMEM column of the +// step's metadata: a lane holds, from bit 0, the VX_tcu_sp_mux rows of the +// step's lower then upper TC_K words. +// MX IType: side_col is the first TMEM column of the step's scales, +// tensor::mx_max_fedp_sf(fedpK) per A row and B column, laid out as in +// docs/designs/tensor_memory.md (A: lane = row, byte s at column side + s/4; +// B: a dense byte stream over M step 1 of the blocks from group side/TC_N + 1). +struct idesc_t { + uint32_t value; +}; + +template +inline constexpr idesc_t make_idesc(uint32_t n_frag, uint32_t d_col, bool acc_init, + bool sparse = false, uint32_t side_col = 0) { + return {(IType::id & 0x1f) | ((sparse ? 1u : 0u) << 5) + | ((acc_init ? 1u : 0u) << 7) | (((n_frag - 1) & 0x7f) << 8) + | (((d_col / frag_cols()) & 0xff) << 15) | ((side_col & 0x1ff) << 23)}; +} + +// A's TMEM column, for an MMA that reads A from TMEM: a lane is an M row, the +// step's fedpK K-packed words. +struct tmem_col { + uint32_t value; +}; + +// Shared-memory byte offset of a pointer, as the descriptors expect. +inline uint32_t smem_offset(const void* ptr) { + size_t lmem_base = csr_read_nv(VX_CSR_LOCAL_MEM_BASE); + return static_cast(reinterpret_cast(ptr) - lmem_base); +} + +// Shared-memory matrix descriptor (tensor::smem_matrix_desc) from a byte +// offset and the leading bytes (row stride; nonzero: A is row-major, B K-major). The +// offset form keeps the LMEM base read out of a K loop; vx_make_smem_desc +// builds one from a pointer. +inline constexpr tensor::smem_matrix_desc smem_desc(uint32_t offset, uint32_t leading_bytes) { + return {tensor::smem_desc_pack(offset, leading_bytes)}; +} + +// tmem.ld/st register layouts (funct3 bit 2). +enum : uint32_t { + LANE_PER_THREAD = 0, + FRAGMENT = 4, +}; + +inline constexpr uint32_t make_taddr(uint32_t lane, uint32_t col) { + return (lane << 16) | col; +} + +// The smallest allocation holding `cols` columns. +inline constexpr uint32_t alloc_cols(uint32_t cols) { + uint32_t n = 32; + while (n < cols) { + n <<= 1; + } + return n; +} + +// tcgen05.alloc: the first of `ncols` TMEM columns (a power of two from 32 to +// VX_CFG_TCU_TMEM_COLS), owned by the CTA; waits until they are free. A CTA +// allocates within the budget it was launched with, so it never waits on a +// CTA that is not running. One warp allocates and shares the column; the +// columns are freed by dealloc() or when the CTA exits. The column is returned +// in thread 0 only (the other threads' values are undefined), so thread 0 +// stores it for the CTA, as tcgen05.alloc writes it to shared memory. +inline uint32_t alloc(uint32_t ncols) { + uint32_t col; + __asm__ volatile (".insn r %1, 6, 5, %0, %2, x0" + : "=r"(col) : "i"(RISCV_CUSTOM0), "r"(ncols) : "memory"); + return col; +} + +// tcgen05.dealloc: frees the CTA's columns. Their MMAs must have completed +// (tc.commit and a barrier wait). +inline void dealloc(uint32_t col, uint32_t ncols) { + __asm__ volatile (".insn r %0, 7, 5, x0, %1, %2" + :: "i"(RISCV_CUSTOM0), "r"(col), "r"(ncols) : "memory"); +} + +// tcgen05.mma: one K step D (+)= A . B, issued asynchronously by a single +// thread (thread 0, which must be active). A is in shared memory or, with a +// tmem_col, in TMEM; B is in shared memory. A core's tc.mma, tc.cp and +// tc.commit run in issue order. +inline void mma(idesc_t idesc, tensor::smem_matrix_desc a, tensor::smem_matrix_desc b) { + __asm__ volatile (".insn r %0, 4, 6, %1, %2, %3" + :: "i"(RISCV_CUSTOM0), "r"(b.value), "r"(idesc.value), "r"(a.value) : "memory"); +} + +inline void mma(idesc_t idesc, tmem_col a, tensor::smem_matrix_desc b) { + __asm__ volatile (".insn r %0, 4, 6, %1, %2, %3" + :: "i"(RISCV_CUSTOM0), "r"(b.value), "r"(idesc.value | (1u << 6)), "r"(a.value) : "memory"); +} + +// tcgen05.commit: arrive on barrier `bar`, as one of its `count` participants, +// once the core's earlier tc.mma and tc.cp ops have completed. +inline void commit(uint32_t bar, uint32_t count) { + __asm__ volatile (".insn r %0, 1, 6, x0, %1, %2" + :: "i"(RISCV_CUSTOM0), "r"(bar), "r"(count) : "memory"); +} + +// tcgen05.cp: copy columns [col, col + cols) of every TMEM lane from `src` +// in shared memory, pre-packed in TMEM's storage order: column group by +// column group (frag_cols() columns), TCU block by block, M step by M step, +// NT words each, word i * frag_cols() + j holding lane m * TC_M + i of the +// block, column j of the group. col and cols are multiples of frag_cols(); +// src and the copy are whole LMEM bank rows. In order with tc.mma. +inline void cp(uint32_t col, const void* src, uint32_t cols) { + uint32_t w = (col & 0xffff) | (cols << 16); + __asm__ volatile (".insn r %0, 2, 6, x0, %1, %2" + :: "i"(RISCV_CUSTOM0), "r"(w), "r"(smem_offset(src)) : "memory"); +} + +// Register lists for transfers of NR = 8, 16 or 32 FP registers: a +// transfer names f0..f(NR-1) as its operands (the uops step through them), so +// each register is pinned. VX_FREG_REST_(M) expands M(1) .. M(NR-1). +#define VX_FREG_REST_8(M) M(1) M(2) M(3) M(4) M(5) M(6) M(7) +#define VX_FREG_REST_16(M) VX_FREG_REST_8(M) M(8) M(9) M(10) M(11) M(12) M(13) M(14) M(15) +#define VX_FREG_REST_32(M) VX_FREG_REST_16(M) M(16) M(17) M(18) M(19) M(20) M(21) M(22) M(23) M(24) M(25) M(26) M(27) M(28) M(29) M(30) M(31) + +#define VX_TMEM_LD_PIN(i) register float fr##i __asm__("f" #i); +#define VX_TMEM_LD_OUT(i) , "=f"(fr##i) +#define VX_TMEM_LD_COPY(i) frag.data[i] = fr##i; +#define VX_TMEM_ST_PIN(i) register float fr##i __asm__("f" #i) = frag.data[i]; +#define VX_TMEM_ST_IN(i) , "f"(fr##i) + +// One transfer of NR registers; rs2 = x(NR-1) encodes the count. +#define VX_TMEM_LOAD(NR, LAST) \ + VX_TMEM_LD_PIN(0) VX_FREG_REST_##NR(VX_TMEM_LD_PIN) \ + __asm__ volatile (".insn r %[insn], %[f3], 5, x0, %[taddr], x" #LAST \ + : "=f"(fr0) VX_FREG_REST_##NR(VX_TMEM_LD_OUT) \ + : [insn]"i"(RISCV_CUSTOM0), [f3]"i"(F3), [taddr]"r"(taddr) \ + : "memory"); \ + VX_TMEM_LD_COPY(0) VX_FREG_REST_##NR(VX_TMEM_LD_COPY) + +#define VX_TMEM_STORE(NR, LAST) \ + VX_TMEM_ST_PIN(0) VX_FREG_REST_##NR(VX_TMEM_ST_PIN) \ + __asm__ volatile (".insn r %[insn], %[f3], 5, x0, %[taddr], x" #LAST \ + : \ + : [insn]"i"(RISCV_CUSTOM0), [f3]"i"(F3), [taddr]"r"(taddr), \ + "f"(fr0) VX_FREG_REST_##NR(VX_TMEM_ST_IN) \ + : "memory"); + +// TMEM -> registers f0..f(NR-1). taddr's lane is warp_lane() and its column a +// multiple of frag_cols(). +// LANE_PER_THREAD: thread t gets lane + t % M, register r column +// + r * (NT / M) + t / M. +// FRAGMENT: register r is the C/D fragment of M step r % 2 and columns +// + (r / 2) * TC_N: thread t gets lane + (r % 2) * TC_M + t / TC_N, column +// + (r / 2) * TC_N + t % TC_N, the layout of the WGMMA accumulator registers +// (so the WGMMA context's store_matrix_sync stores it). +template +inline __attribute__((always_inline)) void load(Frag& frag, uint32_t taddr) { + constexpr uint32_t F3 = 0 | Shape; + static_assert(Frag::NR == 8 || Frag::NR == 16 || Frag::NR == 32, "unsupported fragment size"); + if constexpr (Frag::NR == 8) { + VX_TMEM_LOAD(8, 7) + } else if constexpr (Frag::NR == 16) { + VX_TMEM_LOAD(16, 15) + } else { + VX_TMEM_LOAD(32, 31) + } +} + +// Registers f0..f(NR-1) -> TMEM, in the layout of load(). +template +inline __attribute__((always_inline)) void store(uint32_t taddr, const Frag& frag) { + constexpr uint32_t F3 = 1 | Shape; + static_assert(Frag::NR == 8 || Frag::NR == 16 || Frag::NR == 32, "unsupported fragment size"); + if constexpr (Frag::NR == 8) { + VX_TMEM_STORE(8, 7) + } else if constexpr (Frag::NR == 16) { + VX_TMEM_STORE(16, 15) + } else { + VX_TMEM_STORE(32, 31) + } +} + +#undef VX_TMEM_LOAD +#undef VX_TMEM_STORE +#undef VX_TMEM_LD_PIN +#undef VX_TMEM_LD_OUT +#undef VX_TMEM_LD_COPY +#undef VX_TMEM_ST_PIN +#undef VX_TMEM_ST_IN + +// tcgen05.wait::st: stores are posted, so a warp waits for its own to land +// before a barrier hands their columns to a job. +inline void wait_st() { + vx_wsync(); +} + +} // namespace tmem +} // namespace vortex + +#endif // __VX_TMEM_H__ diff --git a/sw/runtime/common/perf.cpp b/sw/runtime/common/perf.cpp index 8489a3a59d..b9d2fd2a50 100644 --- a/sw/runtime/common/perf.cpp +++ b/sw/runtime/common/perf.cpp @@ -717,6 +717,19 @@ extern "C" vx_result_t vx_device_dump_perf(vx_device_h hdevice, FILE *stream) { perf_print_core(stream, core_id, "tcu: tbuf_stalls=%" PRIu64 ", tbuf_cache_hits=%" PRIu64 ", lmem_reads=%" PRIu64, tbuf_stalls, tbuf_cache_hits, lmem_reads); + uint64_t cycles = 0, busy = 0, opnd = 0, other = 0, idle = 0, xfers = 0; + CHECK_ERR(vx_device_mpm_query(hdevice, mpm_class, VX_CSR_MCYCLE, core_id, &cycles), { return err; }); + CHECK_ERR(vx_device_mpm_query(hdevice, mpm_class, VX_CSR_MPM_TCU_MMA_BUSY, core_id, &busy), { return err; }); + CHECK_ERR(vx_device_mpm_query(hdevice, mpm_class, VX_CSR_MPM_TCU_OPND_WAITS, core_id, &opnd), { return err; }); + CHECK_ERR(vx_device_mpm_query(hdevice, mpm_class, VX_CSR_MPM_TCU_JOB_OTHER, core_id, &other), { return err; }); + CHECK_ERR(vx_device_mpm_query(hdevice, mpm_class, VX_CSR_MPM_TCU_IDLE, core_id, &idle), { return err; }); + CHECK_ERR(vx_device_mpm_query(hdevice, mpm_class, VX_CSR_MPM_TCU_TMEM_XFERS, core_id, &xfers), { return err; }); + // One TCU block per issue slot. + uint64_t blocks = issue_width; + perf_print_core(stream, core_id, + "tcu: mma_util=%d%%, busy_block_cycles=%" PRIu64 ", opnd_waits=%" PRIu64 + ", job_other=%" PRIu64 ", idle=%" PRIu64 ", tmem_xfers=%" PRIu64, + calc_percent(busy, cycles * blocks), busy, opnd, other, idle, xfers); tot_tbuf_stalls += tbuf_stalls; tot_tbuf_cache_hits += tbuf_cache_hits; tot_lmem_reads += lmem_reads; diff --git a/sw/runtime/common/queue.cpp b/sw/runtime/common/queue.cpp index cb0ceb4039..49f0a11960 100644 --- a/sw/runtime/common/queue.cpp +++ b/sw/runtime/common/queue.cpp @@ -209,6 +209,9 @@ vx_result_t Queue::enqueue_write(Buffer* dst, uint64_t off, const void* host, *s = now_ns(); std::lock_guard g(enqueue_mu_); // Host->device through the CP's DMA engine (CMD_MEM_WRITE). + // (FireSim replay capture happens inside cp_submit_mem_write + // itself now, so it also covers dev_write's callers -- the + // args blob and the module image.) r = device_->cp_submit_mem_write(dst->dev_address() + off, host, sz); *e = now_ns(); @@ -313,6 +316,7 @@ vx_result_t Queue::enqueue_launch(const vx_launch_info_t* info, // kernel==NULL and args_host==NULL are the analogous PC / ARG hatches. const uint32_t ndim = info->ndim; const uint32_t lmem_size = info->lmem_size; + const uint32_t tmem_cols = info->tmem_cols; std::array grid_in = {1, 1, 1}; std::array block_in = {1, 1, 1}; for (uint32_t i = 0; i < ndim; ++i) { @@ -369,7 +373,7 @@ vx_result_t Queue::enqueue_launch(const vx_launch_info_t* info, Command cmd; cmd.queued_ns = now_ns(); - cmd.work = [this, kernel, ndim, lmem_size, grid_in, block_in, lg_in, + cmd.work = [this, kernel, ndim, lmem_size, tmem_cols, grid_in, block_in, lg_in, args_blob = std::move(args_blob)](uint64_t* s, uint64_t* e) { // Launch PCs, derived from the retained kernel handle. has_kernel is // false on the legacy escape hatch (caller pre-programmed the DCRs). @@ -475,6 +479,10 @@ vx_result_t Queue::enqueue_launch(const vx_launch_info_t* info, WR(VX_DCR_KMU_CLUSTER_DIM_X, lg_in[0]); WR(VX_DCR_KMU_CLUSTER_DIM_Y, lg_in[1]); WR(VX_DCR_KMU_CLUSTER_DIM_Z, lg_in[2]); + if (tmem_cols != 0 || device_->tmem_cols_dcr != 0) { + WR(VX_DCR_KMU_TMEM_COLS, tmem_cols); + device_->tmem_cols_dcr = tmem_cols; + } } #undef WR @@ -522,6 +530,7 @@ struct CmdRec { std::vector args; uint32_t ndim = 0; uint32_t lmem_size = 0; + uint32_t tmem_cols = 0; std::array grid = {1, 1, 1}; std::array block = {1, 1, 1}; std::array cluster = {1, 1, 1}; @@ -571,6 +580,7 @@ vx_result_t cmd_build_recs(const vx_command_t* commands, uint32_t count, } r.ndim = info->ndim; r.lmem_size = info->lmem_size; + r.tmem_cols = info->tmem_cols; for (uint32_t d = 0; d < info->ndim; ++d) { r.grid [d] = info->grid_dim [d]; r.block[d] = info->block_dim[d]; @@ -663,6 +673,10 @@ vx_result_t cmd_stage_qmds(Device* device_, const std::vector& recs, put(VX_DCR_KMU_CLUSTER_DIM_X, rec.cluster[0]); put(VX_DCR_KMU_CLUSTER_DIM_Y, rec.cluster[1]); put(VX_DCR_KMU_CLUSTER_DIM_Z, rec.cluster[2]); + if (rec.tmem_cols != 0 || device_->tmem_cols_dcr != 0) { + put(VX_DCR_KMU_TMEM_COLS, rec.tmem_cols); + device_->tmem_cols_dcr = rec.tmem_cols; + } } qmd[0] = uint32_t((qmd.size() - 1) / 2); // pair count diff --git a/sw/runtime/common/vortex2_internal.h b/sw/runtime/common/vortex2_internal.h index 6544b7859b..aa602562cc 100644 --- a/sw/runtime/common/vortex2_internal.h +++ b/sw/runtime/common/vortex2_internal.h @@ -232,6 +232,10 @@ class Device : public RefCounted { // Q_SEQNUM to reach the post's sequence number. Synchronous semantics. vx_result_t cp_submit_dcr_write(uint32_t addr, uint32_t value); + // The KMU's TMEM budget DCR as last written. Launches without a budget + // write it only to clear a previous one, so other launches are unchanged. + uint32_t tmem_cols_dcr = 0; + // Post one CMD_LAUNCH to the ring, commit Q_TAIL, and wait for // Q_SEQNUM. Synchronous. The kernel's results are flushed by the next // command that needs them (see cp_ring_append_). diff --git a/sw/runtime/include/vortex2.h b/sw/runtime/include/vortex2.h index d9c72080d9..09beb8d625 100644 --- a/sw/runtime/include/vortex2.h +++ b/sw/runtime/include/vortex2.h @@ -204,6 +204,9 @@ typedef struct { uint32_t block_dim[3]; uint32_t lmem_size; uint32_t cluster_dim[3]; + // Tensor-memory columns each CTA may allocate (tmem::alloc), counted + // against the core's TMEM to bound co-resident CTAs. 0 = none. + uint32_t tmem_cols; } vx_launch_info_t; // 3D-strided DMA descriptor for the rect enqueue ops. Mirrors OpenCL 1.2's diff --git a/tests/regression/flashattention4/Makefile b/tests/regression/flashattention4/Makefile new file mode 100644 index 0000000000..b0b78db3ec --- /dev/null +++ b/tests/regression/flashattention4/Makefile @@ -0,0 +1,30 @@ +ROOT_DIR := $(realpath ../../..) +include $(ROOT_DIR)/config.mk + +CONFIGS := $(if $(findstring -DVX_CFG_EXT_TCU_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_EXT_TCU_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_EXT_DXA_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_EXT_DXA_ENABLE) + +PROJECT := flashattention4 + +SRC_DIR := $(VORTEX_HOME)/tests/regression/$(PROJECT) + +SRCS := $(SRC_DIR)/main.cpp $(SW_COMMON_DIR)/rvfloats.cpp $(SW_COMMON_DIR)/softfloat_ext.cpp + +VX_SRCS := $(SRC_DIR)/kernel.cpp + +CONFIGS := $(if $(findstring -DVX_CFG_NUM_WARPS=,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_NUM_WARPS=16) +CONFIGS := $(if $(findstring -DVX_CFG_ISSUE_WIDTH=,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_ISSUE_WIDTH=4) +CONFIGS := $(if $(findstring -DVX_CFG_TCU_WGMMA_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_TCU_WGMMA_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_TCU_TMEM_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_TCU_TMEM_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_EXT_TFU_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_EXT_TFU_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_TCU_TMEM_COLS=,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_TCU_TMEM_COLS=512) +CONFIGS := $(if $(findstring -DDEEP_BUF,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DDEEP_BUF) + + +CXXFLAGS += -I$(THIRD_PARTY_DIR)/softfloat/source/include + +LDFLAGS += $(THIRD_PARTY_DIR)/softfloat/build/Linux-x86_64-GCC/softfloat.a + +KERNEL_LIB := vortex2 + +include ../common.mk diff --git a/tests/regression/flashattention4/common.h b/tests/regression/flashattention4/common.h new file mode 100644 index 0000000000..9b81cfe082 --- /dev/null +++ b/tests/regression/flashattention4/common.h @@ -0,0 +1,43 @@ +#ifndef _FLASHATTENTION4_TMEM_COMMON_H_ +#define _FLASHATTENTION4_TMEM_COMMON_H_ + +#include + +#ifndef WGMMA_NRC + #define WGMMA_NRC 32 +#endif + +#ifndef ITYPE + #define ITYPE fp16 +#endif + +#ifndef OTYPE + #define OTYPE fp32 +#endif + +// Shared-memory pipeline stages. +#ifndef PIPE_N + #define PIPE_N 2 +#endif + +// K-tiles per pipeline stage, one tc.mma each. +#ifndef KB + #define KB 4 +#endif + +// Control warps per CTA: a producer warp stages the operands and an MMA warp +// issues tc.mma and tc.commit. +#define CTRL_WARPS 2 + +// One head over NB KV blocks of L keys: Q is [M][D], K_T is [NB*L][D], V_T is [N][NB*L]. +// Shared memory starts with the CTA's TMEM column, padded to keep the stages aligned. +#define TMEM_SLOT_BYTES 64 + +typedef struct { + uint32_t L, N, D, NB; + float scale; + uint32_t pad; + uint64_t O_addr; +} kernel_arg_t; + +#endif diff --git a/tests/regression/flashattention4/kernel.cpp b/tests/regression/flashattention4/kernel.cpp new file mode 100644 index 0000000000..b2467710c2 --- /dev/null +++ b/tests/regression/flashattention4/kernel.cpp @@ -0,0 +1,303 @@ +#include "common.h" +#include +#include +#include +#include +#include +#include +#include + +namespace vt = vortex::tensor; +namespace tm = vortex::tmem; +using ctx = vt::wgmma_context; +using wg_cfg = vt::wgmma_config_t; + +constexpr uint32_t kDescQ = 0; +constexpr uint32_t kDescKT = 1; +constexpr uint32_t kDescVT = 2; + +constexpr uint32_t kPipeN = PIPE_N; +constexpr uint32_t kBK = KB * ctx::tileK; // K per stage +static_assert(VX_CFG_NUM_THREADS == ctx::xtileM, "one column per register"); + +// tmem.ld/st use fixed registers f0.., so the softmax moves 8 columns at a time +// to leave the rest of the FP registers to the compiler. +struct frag8_t { + static constexpr uint32_t NR = 8; + float data[NR]; +}; +constexpr uint32_t kNR = frag8_t::NR; + +// The control warps (CTRL_WARPS) stage the operands and issue tc.mma; each of +// the two Q tiles has a softmax group of one warp per TCU block, so an MMA's M +// rows are the group's TMEM lanes. +constexpr uint32_t kTiles = 2; +constexpr uint32_t kGroupWarps = VX_CFG_NUM_TCU_BLOCKS; +constexpr uint32_t kTileM = kGroupWarps * ctx::xtileM; +constexpr uint32_t kTileCols = 128; // S, P and O of a tile +constexpr uint32_t kWarps = CTRL_WARPS + kTiles * kGroupWarps; + +// Stages (full, empty), then per tile: its MMAs done, its softmax done. +constexpr uint32_t kBarDone = 2 * kPipeN; +constexpr uint32_t kBarSm = kBarDone + kTiles; +static_assert(kBarSm + kTiles <= VX_CFG_NUM_BARRIERS, "not enough barriers"); + +// P's fp16 conversion needs a normal input; attention below this weight is negligible. +constexpr float kPMin = 6.2e-5f; +// Softmax runs in base 2. O is rescaled only once a row maximum has grown by +// more than log2(256); until then P is relative to the stale maximum and stays +// below 256. +constexpr float kLog2e = 1.44269504088896341f; +constexpr float kRescaleTau = 8.0f; + +static inline float fmax32(float a, float b) { + float r; + __asm__ volatile ("fmax.s %0, %1, %2" : "=f"(r) : "f"(a), "f"(b)); + return r; +} + +static inline float max8(const float* v) { + float a = fmax32(fmax32(v[0], v[1]), fmax32(v[2], v[3])); + float b = fmax32(fmax32(v[4], v[5]), fmax32(v[6], v[7])); + return fmax32(a, b); +} + +// fp32 -> fp16 bits for a positive normal fp16 value, rounding half up. +static inline uint32_t f32_to_f16_pos(float x) { + uint32_t b; + __builtin_memcpy(&b, &x, 4); + return ((b + 0x1000u) >> 13) - 0x1C000u; +} + +// Per stage of K: wait for it, multiply, and commit it back. +// One tc.mma per K step: a stage holds KB K-tiles of k_steps steps each. +static inline __attribute__((always_inline)) void mma_steps( + uint32_t& i, uint32_t K, uint32_t cta_id, bool acc_init, uint32_t taddr, uint32_t n_frag, + uint32_t a_col, bool a_tmem, uint32_t smem_base, uint32_t stage_bytes, uint32_t b_off) { + constexpr uint32_t kSteps = KB * wg_cfg::k_steps; + constexpr uint32_t kKtBytes = wg_cfg::fedpK * 4; + constexpr uint32_t kLd = kBK * sizeof(ctx::input_t); + for (uint32_t k = 0; k < K; k += kBK, ++i) { + const uint32_t s = i % kPipeN; + const uint32_t full = cta_id | (s << 8); + int phase = vx_barrier_arrive(full, 2); + vx_barrier_wait(full, phase); + const uint32_t a_off = smem_base + s * stage_bytes; + const uint32_t b_base = a_off + b_off; + for (uint32_t kt = 0; kt < kSteps; ++kt) { + const uint32_t gk = (k / kBK) * kSteps + kt; + const auto idesc = tm::make_idesc(n_frag, taddr, acc_init && gk == 0); + const auto b = tm::smem_desc(b_base + kt * kKtBytes, kLd); + if (a_tmem) { + tm::mma(idesc, tm::tmem_col{a_col + gk * wg_cfg::fedpK}, b); + } else { + tm::mma(idesc, tm::smem_desc(a_off + kt * kKtBytes, kLd), b); + } + } + tm::commit(cta_id | ((kPipeN + s) << 8), 2); + } +} + +static inline __attribute__((always_inline)) void wait_empty(uint32_t i, uint32_t cta_id) { + if (i >= kPipeN) { + uint32_t e = cta_id | ((kPipeN + i % kPipeN) << 8); + int phase = vx_barrier_arrive(e, 2); + vx_barrier_wait(e, phase); + } +} + +// S stages: Q rows [q_row, +kTileM) and K_T rows [kv_row, +L), over D. +static inline __attribute__((always_inline)) void load_s( + uint32_t& i, uint32_t D, uint32_t cta_id, ctx::input_t* smem, uint32_t stage_elems, + uint32_t q_row, uint32_t kv_row) { + for (uint32_t k = 0; k < D; k += kBK, ++i) { + wait_empty(i, cta_id); + const uint32_t s = i % kPipeN; + const uint32_t full = cta_id | (s << 8); + auto stage = smem + s * stage_elems; + vx_barrier_expect_tx(full, 2); + vx_dxa_issue_2d_wg(kDescQ, full, stage, k, q_row); + vx_dxa_issue_2d_wg(kDescKT, full, stage + kTileM * kBK, k, kv_row); + vx_barrier_arrive(full, 2); + } +} + +// P.V stages: V_T columns [kv_col, +L). +static inline __attribute__((always_inline)) void load_pv( + uint32_t& i, uint32_t L, uint32_t cta_id, ctx::input_t* smem, uint32_t stage_elems, uint32_t kv_col) { + for (uint32_t k = 0; k < L; k += kBK, ++i) { + wait_empty(i, cta_id); + const uint32_t s = i % kPipeN; + const uint32_t full = cta_id | (s << 8); + vx_barrier_expect_tx(full, 1); + vx_dxa_issue_2d_wg(kDescVT, full, smem + s * stage_elems, kv_col + k, 0); + vx_barrier_arrive(full, 2); + } +} + +__kernel void kernel_main(kernel_arg_t* __UNIFORM__ arg) { + const uint32_t L = arg->L, N = arg->N, D = arg->D, NB = arg->NB; + const float scale = arg->scale; + auto pO = reinterpret_cast(arg->O_addr); + + const uint32_t warp_rank = threadIdx.x / VX_CFG_NUM_THREADS; + const uint32_t t = vx_thread_id(); + + auto lmem = reinterpret_cast(__local_mem()); + auto tmem_slot = reinterpret_cast(lmem); + auto smem = reinterpret_cast(lmem + TMEM_SLOT_BYTES); + const uint32_t cta_row = blockIdx.x * kTiles * kTileM; + + const uint32_t cta_id = get_local_group_id(); + auto bar = [&](uint32_t n) { return cta_id | (n << 8); }; + + // Every warp meets on the first softmax barrier before its first use, to + // share the TMEM columns and, at the end, to free them. + const uint32_t all_bar = bar(kBarSm); + if (warp_rank == 0) { + // The column is in thread 0 only. + uint32_t col = tm::alloc(kTiles * kTileCols); + if (vx_thread_id() == 0) { + *tmem_slot = col; + } + } + vx_barrier(all_bar, kWarps); + const uint32_t col_base = *tmem_slot; + auto s_col = [&](uint32_t tile) { return col_base + tile * kTileCols; }; + auto p_col = [&](uint32_t tile) { return s_col(tile) + L; }; + auto o_col = [&](uint32_t tile) { return p_col(tile) + L / 2; }; + + // Both MMAs share one stage ring: S = Q.K_T stages A (Q) then B (K_T), and + // O += P.V stages only B (V_T), as P is in TMEM. + const uint32_t stage_elems = kTileM * kBK + kBK * (L > N ? L : N); + const uint32_t smem_base = tm::smem_offset(smem); + const uint32_t q_bytes = kTileM * kBK * sizeof(ctx::input_t); + const uint32_t stage_bytes = stage_elems * sizeof(ctx::input_t); + + // MMAs in issue order. Ping-pong: while one tile's softmax runs, the TCU + // works on the other's. The steps take plain values so the per-K-tile code + // stays in registers across the asm memory clobbers. + if (warp_rank == 0) { + // Producer: it and the MMA warp are the two participants of every full and + // empty barrier. Loads run ahead of the softmax, bounded by the ring. + const uint32_t q_row = cta_row; + uint32_t i = 0; + for (uint32_t tile = 0; tile < kTiles; ++tile) { + load_s(i, D, cta_id, smem, stage_elems, q_row + tile * kTileM, 0); + } + for (uint32_t b = 0; b < NB; ++b) { + for (uint32_t tile = 0; tile < kTiles; ++tile) { + load_pv(i, L, cta_id, smem, stage_elems, b * L); + if (b + 1 < NB) { + load_s(i, D, cta_id, smem, stage_elems, q_row + tile * kTileM, (b + 1) * L); + } + } + } + // Close the last generation of every empty barrier the MMA warp committed. + for (uint32_t j = (i > kPipeN) ? (i - kPipeN) : 0; j < i; ++j) { + uint32_t e = cta_id | ((kPipeN + j % kPipeN) << 8); + int phase = vx_barrier_arrive(e, 2); + vx_barrier_wait(e, phase); + } + vx_barrier(all_bar, kWarps); + tm::dealloc(col_base, kTiles * kTileCols); + return; + } + if (warp_rank == 1) { + // A tile's softmax waits on the commit after its S MMA (or its last P.V). + uint32_t i = 0; + for (uint32_t tile = 0; tile < kTiles; ++tile) { + mma_steps(i, D, cta_id, true, s_col(tile), L / ctx::tcN, 0, false, smem_base, stage_bytes, q_bytes); + tm::commit(bar(kBarDone + tile), 1 + kGroupWarps); + } + for (uint32_t b = 0; b < NB; ++b) { + for (uint32_t tile = 0; tile < kTiles; ++tile) { + vx_barrier(bar(kBarSm + tile), 1 + kGroupWarps); + mma_steps(i, L, cta_id, b == 0, o_col(tile), N / ctx::tcN, p_col(tile), true, smem_base, stage_bytes, 0); + if (b + 1 < NB) { + mma_steps(i, D, cta_id, true, s_col(tile), L / ctx::tcN, 0, false, smem_base, stage_bytes, q_bytes); + } + tm::commit(bar(kBarDone + tile), 1 + kGroupWarps); + } + } + vx_barrier(all_bar, kWarps); + return; + } + + const uint32_t tile = (warp_rank - CTRL_WARPS) / kGroupWarps; + // A softmax group's warps are one per TCU block; each reaches its own block's lanes. + const uint32_t lane = tm::warp_lane(); + const uint32_t done_bar = bar(kBarDone + tile); + const uint32_t sm_bar = bar(kBarSm + tile); + + // The scale is positive, so the row maximum of S scales with it. + const float scale2 = scale * kLog2e; + float row_max = 0.0f; + float row_sum = 0.0f; + + for (uint32_t b = 0; b < NB; ++b) { + // S of block b, and O through block b - 1. + vx_barrier(done_bar, 1 + kGroupWarps); + + float smax = -3.0e38f; + for (uint32_t c = 0; c < L / kNR; ++c) { + frag8_t s; + tm::load(s, tm::make_taddr(lane, s_col(tile) + c * kNR)); + smax = fmax32(smax, max8(s.data)); + } + const float cand = (b == 0) ? smax * scale2 : fmax32(row_max, smax * scale2); + if (b == 0) { + row_max = cand; + } else if (vx_vote_any(cand - row_max > kRescaleTau)) { + const float rescale = vx_ex2f(row_max - cand); + row_max = cand; + row_sum *= rescale; + for (uint32_t c = 0; c < N / kNR; ++c) { + frag8_t o; + uint32_t taddr = tm::make_taddr(lane, o_col(tile) + c * kNR); + tm::load(o, taddr); + #pragma unroll + for (uint32_t r = 0; r < kNR; ++r) { + o.data[r] *= rescale; + } + tm::store(taddr, o); + } + } + + // P = exp(S - max) as fp16, K-packed for the P.V MMA. + for (uint32_t c = 0; c < L / (2 * kNR); ++c) { + frag8_t s0, s1, p; + uint32_t col = s_col(tile) + c * 2 * kNR; + tm::load(s0, tm::make_taddr(lane, col)); + tm::load(s1, tm::make_taddr(lane, col + kNR)); + float psum[kNR / 2] = {}; + #pragma unroll + for (uint32_t r = 0; r < kNR; ++r) { + float lo = (r < kNR / 2) ? s0.data[2 * r] : s1.data[2 * r - kNR]; + float hi = (r < kNR / 2) ? s0.data[2 * r + 1] : s1.data[2 * r + 1 - kNR]; + lo = fmax32(vx_ex2f(lo * scale2 - row_max), kPMin); + hi = fmax32(vx_ex2f(hi * scale2 - row_max), kPMin); + psum[r % (kNR / 2)] += lo + hi; + uint32_t word = f32_to_f16_pos(lo) | (f32_to_f16_pos(hi) << 16); + __builtin_memcpy(&p.data[r], &word, 4); + } + tm::store(tm::make_taddr(lane, p_col(tile) + c * kNR), p); + row_sum += (psum[0] + psum[1]) + (psum[2] + psum[3]); + } + tm::wait_st(); + vx_barrier_arrive(sm_bar, 1 + kGroupWarps); + } + + vx_barrier(done_bar, 1 + kGroupWarps); + const float inv_sum = vx_rcpf(row_sum); + const uint32_t row = cta_row + tile * kTileM + lane + t; + for (uint32_t c = 0; c < N / kNR; ++c) { + frag8_t o; + tm::load(o, tm::make_taddr(lane, o_col(tile) + c * kNR)); + #pragma unroll + for (uint32_t r = 0; r < kNR; ++r) { + pO[row * N + c * kNR + r] = o.data[r] * inv_sum; + } + } + vx_barrier(all_bar, kWarps); +} diff --git a/tests/regression/flashattention4/main.cpp b/tests/regression/flashattention4/main.cpp new file mode 100644 index 0000000000..ab71706380 --- /dev/null +++ b/tests/regression/flashattention4/main.cpp @@ -0,0 +1,202 @@ +#include "common.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define RT_CHECK(_expr) \ + do { \ + int _ret = _expr; \ + if (0 == _ret) \ + break; \ + printf("Error: '%s' returned %d!\n", #_expr, (int)_ret); \ + cleanup(); \ + exit(-1); \ + } while (false) + +using namespace vortex; +namespace vt = tensor; +using cfg = vt::wgmma_config_t; + +static_assert(std::is_same::value && std::is_same::value, + "P is fp16 and S, O are fp32"); + +uint32_t xl = 64; +uint32_t xn = 32; +uint32_t xd = 64; +uint32_t xb = 2; +uint32_t xc = 1; + +// fp16 rounding of P and TFU's approximations. +constexpr double kMaxRelError = 0.01; + +vx_device_h device = nullptr; +vx_buffer_h buffers[4] = {}; +vx_queue_h queue = nullptr; +vx_module_h module_ = nullptr; +vx_kernel_h kernel = nullptr; +kernel_arg_t kernel_arg = {}; + +void cleanup() { + if (device) { + for (auto b : buffers) { + if (b) vx_buffer_release(b); + } + if (kernel) vx_kernel_release(kernel); + if (module_) vx_module_release(module_); + if (queue) vx_queue_release(queue); + vx_device_dump_perf(device, stdout); + vx_device_release(device); + } +} + +static uint16_t gen_fp16() { + auto f = float(rand()) / RAND_MAX; + return rv_ftoh_s(bit_cast(f), 0, nullptr); +} + +static double htod(uint16_t h) { + return bit_cast(rv_htof_s(h, 0, nullptr)); +} + +int main(int argc, char* argv[]) { + int c; + while ((c = getopt(argc, argv, "l:n:d:b:c:")) != -1) { + switch (c) { + case 'l': xl = atoi(optarg); break; + case 'n': xn = atoi(optarg); break; + case 'd': xd = atoi(optarg); break; + case 'b': xb = atoi(optarg); break; + case 'c': xc = atoi(optarg); break; + default: return -1; + } + } + + srand(50); + RT_CHECK(vx_device_open(0, &device)); + vx_queue_info_t qi = { sizeof(qi), nullptr, VX_QUEUE_PRIORITY_NORMAL, 0 }; + RT_CHECK(vx_queue_create(device, &qi, &queue)); + + uint64_t NT, issue_width; + RT_CHECK(vx_device_query(device, VX_CAPS_NUM_THREADS, &NT)); + RT_CHECK(vx_device_query(device, VX_CAPS_ISSUE_WIDTH, &issue_width)); + + // Per CTA: the control warps and, for each of two Q tiles, one softmax warp per TCU block. + const uint32_t tile_m = issue_width * cfg::xtileM; + const uint32_t warps = CTRL_WARPS + 2 * issue_width; + const uint32_t MT = 2 * tile_m * xc; + const uint32_t L = xl, N = xn, D = xd, NB = xb, LT = L * NB; + const uint32_t nr = WGMMA_NRC; + const uint32_t stage_k = KB * cfg::tileK; + if ((L % (2 * nr)) || (N % nr) || (D % stage_k) || (L % stage_k) || (L + L / 2 + N > 128)) { + std::cout << "Error: L must be a multiple of " << 2 * nr << ", N of " << nr + << ", D and L of KB*tileK=" << stage_k << ", and L + L/2 + N <= 128" << std::endl; + return -1; + } + + // K_T and V_T are the K-major forms. + std::vector h_Q(size_t(MT) * D), h_KT(size_t(LT) * D), h_VT(size_t(N) * LT); + for (auto& x : h_Q) x = gen_fp16(); + for (auto& x : h_KT) x = gen_fp16(); + for (auto& x : h_VT) x = gen_fp16(); + + uint32_t smem_size = PIPE_N * (tile_m * stage_k + stage_k * std::max(L, N)) * sizeof(uint16_t); + smem_size += TMEM_SLOT_BYTES; + + kernel_arg.L = L; kernel_arg.N = N; kernel_arg.D = D; kernel_arg.NB = NB; + kernel_arg.scale = 1.0f / std::sqrt(float(D)); + uint64_t q_addr, kt_addr, vt_addr; + RT_CHECK(vx_buffer_create(device, h_Q.size() * 2, VX_MEM_READ, &buffers[0])); + RT_CHECK(vx_buffer_create(device, h_KT.size() * 2, VX_MEM_READ, &buffers[1])); + RT_CHECK(vx_buffer_create(device, h_VT.size() * 2, VX_MEM_READ, &buffers[2])); + RT_CHECK(vx_buffer_create(device, size_t(MT) * N * 4, VX_MEM_WRITE, &buffers[3])); + RT_CHECK(vx_buffer_address(buffers[0], &q_addr)); + RT_CHECK(vx_buffer_address(buffers[1], &kt_addr)); + RT_CHECK(vx_buffer_address(buffers[2], &vt_addr)); + RT_CHECK(vx_buffer_address(buffers[3], &kernel_arg.O_addr)); + RT_CHECK(vx_enqueue_write(queue, buffers[0], 0, h_Q.data(), h_Q.size() * 2, 0, nullptr, nullptr)); + RT_CHECK(vx_enqueue_write(queue, buffers[1], 0, h_KT.data(), h_KT.size() * 2, 0, nullptr, nullptr)); + RT_CHECK(vx_enqueue_write(queue, buffers[2], 0, h_VT.data(), h_VT.size() * 2, 0, nullptr, nullptr)); + + auto program = [&](uint32_t slot, uint64_t addr, uint32_t k, uint32_t rows, uint32_t tile_rows) { + RT_CHECK(vortex::dxa::program_2d(device, slot, addr, k, rows, k * 2, stage_k, tile_rows, 2)); + RT_CHECK(vortex::dxa::set_layout(device, slot, vortex::dxa::Layout::RowMajor, 2, 2)); + }; + program(0, q_addr, D, MT, tile_m); + program(1, kt_addr, D, LT, L); + program(2, vt_addr, LT, N, N); + + RT_CHECK(vx_module_load_file(device, "kernel.vxbin", &module_)); + RT_CHECK(vx_module_get_kernel(module_, "main", &kernel)); + + std::vector h_O(size_t(MT) * N); + + vx_event_h launch_ev = nullptr; + vx_launch_info_t li = {}; + li.struct_size = sizeof(li); + li.kernel = kernel; + li.args_host = &kernel_arg; + li.args_size = sizeof(kernel_arg); + li.ndim = 2; + li.grid_dim[0] = xc; + li.grid_dim[1] = 1; + li.block_dim[0] = warps * uint32_t(NT); + li.block_dim[1] = 1; + li.lmem_size = smem_size; + li.tmem_cols = 2 * 128; // kernel.cpp: kTiles * kTileCols (S, P and O of two Q tiles) + RT_CHECK(vx_enqueue_launch(queue, &li, 0, nullptr, &launch_ev)); + vx_event_h read_o = nullptr; + RT_CHECK(vx_enqueue_read(queue, h_O.data(), buffers[3], 0, h_O.size() * 4, 1, &launch_ev, &read_o)); + RT_CHECK(vx_event_wait_value(read_o, 1, VX_TIMEOUT_INFINITE)); + vx_event_release(read_o); + vx_event_release(launch_ev); + + // Exact softmax over all keys at once; the device computes it online per block. + int errors = 0; + double max_err = 0; + const double scale = kernel_arg.scale; + std::vector w(LT); + for (uint32_t m = 0; m < MT; ++m) { + double s_max = -INFINITY; + for (uint32_t l = 0; l < LT; ++l) { + double acc = 0; + for (uint32_t k = 0; k < D; ++k) { + acc += htod(h_Q[size_t(m) * D + k]) * htod(h_KT[size_t(l) * D + k]); + } + w[l] = acc * scale; + s_max = std::max(s_max, w[l]); + } + double sum = 0; + for (auto& x : w) { + x = std::exp(x - s_max); + sum += x; + } + for (uint32_t n = 0; n < N; ++n) { + double ref = 0; + for (uint32_t l = 0; l < LT; ++l) { + ref += (w[l] / sum) * htod(h_VT[size_t(n) * LT + l]); + } + double actual = h_O[size_t(m) * N + n]; + double err = std::abs(actual - ref) / std::abs(ref); + max_err = std::max(max_err, err); + if (!(err <= kMaxRelError) && errors++ < 20) { + printf("*** O[%u][%u]: expected=%f, actual=%f\n", m, n, ref, actual); + } + } + } + std::cout << "O: max relative error " << max_err << ", bound " << kMaxRelError << std::endl; + + cleanup(); + if (errors) { + std::cout << "Found " << errors << " errors!" << std::endl << "FAILED!" << std::endl; + return 1; + } + std::cout << "PASSED!" << std::endl; + return 0; +} diff --git a/tests/regression/sgemm_tcu_tmem/Makefile b/tests/regression/sgemm_tcu_tmem/Makefile new file mode 100644 index 0000000000..a4cd8814a0 --- /dev/null +++ b/tests/regression/sgemm_tcu_tmem/Makefile @@ -0,0 +1,32 @@ +ROOT_DIR := $(realpath ../../..) +include $(ROOT_DIR)/config.mk + +CONFIGS := $(if $(findstring -DVX_CFG_EXT_TCU_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_EXT_TCU_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_EXT_DXA_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_EXT_DXA_ENABLE) + +PROJECT := sgemm_tcu_tmem + +SRC_DIR := $(VORTEX_HOME)/tests/regression/$(PROJECT) + +SRCS := $(SRC_DIR)/main.cpp $(SW_COMMON_DIR)/rvfloats.cpp $(SW_COMMON_DIR)/softfloat_ext.cpp + +VX_SRCS := $(SRC_DIR)/kernel.cpp + +CONFIGS := $(if $(findstring -DVX_CFG_NUM_WARPS=,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_NUM_WARPS=4) +CONFIGS := $(if $(findstring -DVX_CFG_ISSUE_WIDTH=,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_ISSUE_WIDTH=4) +CONFIGS := $(if $(findstring -DVX_CFG_TCU_WGMMA_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_TCU_WGMMA_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_TCU_TMEM_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_TCU_TMEM_ENABLE) +CONFIGS := $(if $(findstring -DDEEP_BUF,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DDEEP_BUF) +CONFIGS += $(if $(PIPE_N),-DPIPE_N=$(PIPE_N)) +CONFIGS += $(if $(TMEM_LANE_PER_THREAD),-DTMEM_LANE_PER_THREAD) +CONFIGS += $(if $(TMEM_SPARSE),-DTMEM_SPARSE -DVX_CFG_TCU_SPARSE_ENABLE) +CONFIGS += $(if $(TMEM_A),-DTMEM_A) + + +CXXFLAGS += -I$(THIRD_PARTY_DIR)/softfloat/source/include + +LDFLAGS += $(THIRD_PARTY_DIR)/softfloat/build/Linux-x86_64-GCC/softfloat.a + +KERNEL_LIB := vortex2 + +include ../common.mk diff --git a/tests/regression/sgemm_tcu_tmem/common.h b/tests/regression/sgemm_tcu_tmem/common.h new file mode 100644 index 0000000000..007280e492 --- /dev/null +++ b/tests/regression/sgemm_tcu_tmem/common.h @@ -0,0 +1,48 @@ +#ifndef _SGEMM_TCU_WG_DXA_COMMON_H_ +#define _SGEMM_TCU_WG_DXA_COMMON_H_ + +#include + +#ifndef WGMMA_NRC + #define WGMMA_NRC 8 +#endif + +#ifndef ITYPE +#define ITYPE fp16 +#endif + +#ifndef OTYPE +#define OTYPE fp32 +#endif + +// Software-pipeline depth for DEEP_BUF (N-stage generalization of +// DOUBLE_BUF). Shared between kernel.cpp (loop structure) and main.cpp +// (SMEM sizing) so they can't drift out of sync. +#ifndef PIPE_N +#define PIPE_N 4 +#endif + +// Accumulator chunks per CTA tile: an MMA covers TMEM_NCHUNK register-file +// tiles along N, drained through the registers one chunk at a time. +#ifndef TMEM_NCHUNK + #define TMEM_NCHUNK 1 +#endif + +// K-tiles per DEEP_BUF pipeline stage (kernel.cpp: KB). 1 = one K-tile per +// stage (original behavior). +#ifndef KB + #define KB 1 +#endif + +// Shared memory starts with the CTA's TMEM column, padded to keep the stages aligned. +#define TMEM_SLOT_BYTES 64 + +typedef struct { + uint32_t M, N, K; + uint64_t A_addr; + uint64_t B_addr; + uint64_t C_addr; + uint64_t meta_addr; +} kernel_arg_t; + +#endif diff --git a/tests/regression/sgemm_tcu_tmem/kernel.cpp b/tests/regression/sgemm_tcu_tmem/kernel.cpp new file mode 100644 index 0000000000..cd946c1d0a --- /dev/null +++ b/tests/regression/sgemm_tcu_tmem/kernel.cpp @@ -0,0 +1,275 @@ +#include "common.h" +#include +#include +#include +#include +#include +#include + +namespace vt = vortex::tensor; +namespace tm = vortex::tmem; +using ctx = vt::wgmma_context; +using wg_cfg = vt::wgmma_config_t; + +#ifdef TMEM_SPARSE +constexpr bool kSparse = true; +constexpr uint32_t kTileK = wg_cfg::tileK_sp; +#else +constexpr bool kSparse = false; +constexpr uint32_t kTileK = ctx::tileK; +#endif +#ifdef TMEM_A +constexpr bool kATmem = true; +#else +constexpr bool kATmem = false; +#endif +// The TCU copies the staged metadata into TMEM (tc.cp) instead of the warps. +#ifdef TMEM_CP +constexpr bool kCopyMeta = kSparse; +#else +constexpr bool kCopyMeta = false; +#endif + +// DXA descriptor slots (programmed by host in main.cpp). +constexpr uint32_t kDescA = 0; +constexpr uint32_t kDescB = 1; +[[maybe_unused]] constexpr uint32_t kDescMeta = 2; + +// B is K-major (B^T, [N][K] in memory): a DXA tile is (k, col). +static inline __attribute__((always_inline)) uint32_t b_coord0(uint32_t k, uint32_t col) { + (void)col; return k; +} +static inline __attribute__((always_inline)) uint32_t b_coord1(uint32_t k, uint32_t col) { + (void)k; return col; +} + +static_assert(sizeof(ctx::output_t) == sizeof(float), "the TMEM epilogue stores fp32 lanes"); + +constexpr uint32_t kPipeN = PIPE_N; +constexpr uint32_t kTileN = ctx::xtileN * TMEM_NCHUNK; // CTA tile N +constexpr uint32_t kBK = KB * kTileK; // K per pipeline stage +// tc.mma K-tiles (one FEDP width of A each) per kTileK: a dense tile spans +// k_steps of them, a sparse one exactly one. +constexpr uint32_t kKtPerTile = kSparse ? 1 : wg_cfg::k_steps; +constexpr uint32_t kAK = kSparse ? (kBK / 2) : kBK; // A is compressed along K +constexpr uint32_t kBLdmBytes = kBK * sizeof(ctx::input_t); + +// Full, empty, done and TMEM-load barriers of a CTA. +static_assert(2 * kPipeN + 2 <= VX_CFG_NUM_BARRIERS, "not enough barriers for PIPE_N"); + +constexpr uint32_t kThreadsPerLane = VX_CFG_NUM_THREADS / ctx::xtileM; +// A K step's metadata takes one fragment group of TMEM columns per lane. +constexpr uint32_t kFragCols = tm::frag_cols(); +constexpr uint32_t kMetaCols = (wg_cfg::fedpK * 2 * (32 / vt::ITYPE::bits) + 31) / 32; +static_assert(kMetaCols <= kFragCols, "a K step's metadata fits a fragment group"); +// One tc.mma K step: fedpK words of A (compressed when sparse) and of B per +// K-major row (twice that when sparse). +constexpr uint32_t kKtBytes = wg_cfg::fedpK * 4; +// tmem::store writes whole fragments. +constexpr uint32_t kStoreCols = ctx::fragment_acc::NR * kThreadsPerLane; + +// Warp `lane` group: copy `cols` columns from global words [row][col] into TMEM. +[[maybe_unused]] static inline void load_tmem_cols(uint32_t lane, uint32_t col0, uint32_t cols, + const float* src, uint32_t stride, uint32_t row0) { + const uint32_t t = vx_thread_id(); + const uint32_t row = row0 + t % ctx::xtileM; + for (uint32_t c = 0; c < cols; c += kStoreCols) { + ctx::fragment_acc frag; + #pragma unroll + for (uint32_t r = 0; r < ctx::fragment_acc::NR; ++r) { + uint32_t col = c + r * kThreadsPerLane + t / ctx::xtileM; + frag.data[r] = (col < stride) ? src[row * stride + col] : 0.0f; + } + tm::store(tm::make_taddr(lane, col0 + c), frag); + } + tm::wait_st(); +} + +// Warp `lane` group: copy `cols` columns of the CTA's [row][stride] words in +// shared memory into TMEM, a fragment per register. Columns past `stride` +// pick up the next row's words, which the MMA never reads. +[[maybe_unused]] static inline void smem_to_tmem_cols(uint32_t lane, uint32_t col0, uint32_t cols, + const float* src, uint32_t stride) { + const uint32_t t = vx_thread_id(); + for (uint32_t c = 0; c < cols; c += kStoreCols) { + ctx::fragment_acc frag; + #pragma unroll + for (uint32_t r = 0; r < ctx::fragment_acc::NR; ++r) { + frag.data[r] = src[(lane + (r % wg_cfg::m_steps) * wg_cfg::tcM + t / wg_cfg::tcN) * stride + + c + (r / wg_cfg::m_steps) * wg_cfg::tcN + t % wg_cfg::tcN]; + } + tm::store(tm::make_taddr(lane, col0 + c), frag); + } + tm::wait_st(); +} + +__kernel void kernel_main(kernel_arg_t* __UNIFORM__ arg) { + auto pC = reinterpret_cast(arg->C_addr); + + uint32_t N = arg->N; + uint32_t K = arg->K; + + uint32_t tid = threadIdx.x; + uint32_t num_threads = blockDim.x; + uint32_t warp_rank = tid / VX_CFG_NUM_THREADS; + uint32_t num_warps = num_threads / VX_CFG_NUM_THREADS; + + // One warp per TCU block: block b computes rows [b*xtileM, (b+1)*xtileM). + uint32_t cta_M = num_warps * ctx::xtileM; + uint32_t tile_row = blockIdx.y * cta_M; + uint32_t tile_col = blockIdx.x * kTileN; + + auto lmem = reinterpret_cast(__local_mem()); + auto tmem_slot = reinterpret_cast(lmem); + auto smem = reinterpret_cast(lmem + TMEM_SLOT_BYTES); + const uint32_t stage_a_elems = kATmem ? 0 : (cta_M * kAK); + const uint32_t stage_elems = stage_a_elems + kBK * kTileN; + auto stage_A = [&](uint32_t s) { return smem + s * stage_elems; }; + auto stage_B = [&](uint32_t s) { return smem + s * stage_elems + stage_a_elems; }; + + const uint32_t cta_id = get_local_group_id(); + auto full_bar = [&](uint32_t s) { return cta_id | (s << 8); }; + auto empty_bar = [&](uint32_t s) { return cta_id | ((kPipeN + s) << 8); }; + const uint32_t done_bar = cta_id | ((2 * kPipeN) << 8); + const uint32_t load_bar = cta_id | ((2 * kPipeN + 1) << 8); + + const uint32_t num_steps = K / kBK; + const uint32_t k_tiles = K / kTileK; + + // TMEM: D, then A (a_tmem), then the metadata (sparse). + auto round_store = [](uint32_t cols) { return ((cols + kStoreCols - 1) / kStoreCols) * kStoreCols; }; + const uint32_t a_cols = k_tiles * kKtPerTile * wg_cfg::fedpK; + const uint32_t meta_words = k_tiles * kFragCols; + const uint32_t tmem_cols = tm::alloc_cols(kTileN + (kATmem ? round_store(a_cols) : 0) + + (kSparse ? round_store(meta_words) : 0)); + if (warp_rank == 0) { + uint32_t col = tm::alloc(tmem_cols); + if (vx_thread_id() == 0) { + *tmem_slot = col; + } + } + vx_barrier(load_bar, num_warps); + const uint32_t taddr = *tmem_slot; + const uint32_t a_col = taddr + kTileN; + const uint32_t meta_col = a_col + (kATmem ? round_store(a_cols) : 0); + const uint32_t lane0 = tm::warp_lane(); + const uint32_t row0 = tile_row + lane0; + // The metadata is staged through the pipeline stages, which no MMA uses yet: + // for tc.cp pre-packed in TMEM storage order (one row of the CTA's blob), + // else row by row, padded to NT words. + const uint32_t meta_pitch = (meta_words + VX_CFG_NUM_THREADS - 1) / VX_CFG_NUM_THREADS * VX_CFG_NUM_THREADS; + if constexpr (kSparse) { + if (warp_rank == 0) { + vx_barrier_expect_tx(load_bar, 1); + vx_dxa_issue_2d_wg(kDescMeta, load_bar, smem, 0, kCopyMeta ? blockIdx.y : tile_row); + } + } + if constexpr (kATmem) { + const uint32_t a_stride = ((K * sizeof(ctx::input_t)) / (kSparse ? 2 : 1)) / 4; + load_tmem_cols(lane0, a_col, a_cols, reinterpret_cast(arg->A_addr), a_stride, row0); + } + if constexpr (kCopyMeta) { + // With A in TMEM every warp meets on load_bar again, so all wait here too. + if (kATmem || warp_rank == 0) { + vx_barrier(load_bar, kATmem ? num_warps : 1); + } + } else if constexpr (kSparse) { + vx_barrier(load_bar, num_warps); + smem_to_tmem_cols(lane0, meta_col, meta_words, reinterpret_cast(smem), meta_pitch); + } + if constexpr (kATmem || (kSparse && !kCopyMeta)) { + vx_barrier(load_bar, num_warps); + } + + if (warp_rank == 0) { + if constexpr (kCopyMeta) { + // The copy runs ahead of every tc.mma; the stages that hold the staged + // metadata are refilled only once it completes. + tm::cp(meta_col, smem, meta_words); + tm::commit(load_bar, 2); + vx_barrier(load_bar, 2); + } + // Producer: this warp and the MMA warp are the two participants of every + // full and empty barrier. + for (uint32_t i = 0; i < num_steps; ++i) { + uint32_t s = i % kPipeN; + if (i >= kPipeN) { + int phase = vx_barrier_arrive(empty_bar(s), 2); + vx_barrier_wait(empty_bar(s), phase); + } + uint32_t k = i * kBK; + vx_barrier_expect_tx(full_bar(s), kATmem ? 1 : 2); + if constexpr (!kATmem) { + vx_dxa_issue_2d_wg(kDescA, full_bar(s), stage_A(s), i * kAK, tile_row); + } + vx_dxa_issue_2d_wg(kDescB, full_bar(s), stage_B(s), b_coord0(k, tile_col), b_coord1(k, tile_col)); + vx_barrier_arrive(full_bar(s), 2); + } + // Close the last generation of every empty barrier the MMA warp committed. + uint32_t first = (num_steps > kPipeN) ? (num_steps - kPipeN) : 0; + for (uint32_t i = first; i < num_steps; ++i) { + uint32_t s = i % kPipeN; + int phase = vx_barrier_arrive(empty_bar(s), 2); + vx_barrier_wait(empty_bar(s), phase); + } + } else if (warp_rank == 1) { + // Per stage: wait for it, multiply, and commit it back to the producer; + // the last commit completes the GEMM. + // One tc.mma per K step, its descriptor in the instruction. + constexpr uint32_t kSteps = KB * kKtPerTile; + constexpr uint32_t kALd = kAK * sizeof(ctx::input_t); + // B's K step: along a K-major row, or a block-major K-tile's n_frag blocks. + constexpr uint32_t kBStepBytes = (kBLdmBytes != 0) ? (kKtBytes * (kSparse ? 2 : 1)) + : (kTileN * kKtBytes); + for (uint32_t i = 0; i < num_steps; ++i) { + uint32_t s = i % kPipeN; + int phase = vx_barrier_arrive(full_bar(s), 2); + vx_barrier_wait(full_bar(s), phase); + const uint32_t a_off = tm::smem_offset(stage_A(s)); + const uint32_t b_off = tm::smem_offset(stage_B(s)); + for (uint32_t kt = 0; kt < kSteps; ++kt) { + const uint32_t gk = i * kSteps + kt; + const auto idesc = tm::make_idesc(kTileN / ctx::tcN, taddr, gk == 0, + kSparse, kSparse ? (meta_col + gk * kFragCols) : 0); + const auto b = tm::smem_desc(b_off + kt * kBStepBytes, kBLdmBytes); + if constexpr (kATmem) { + tm::mma(idesc, tm::tmem_col{a_col + gk * wg_cfg::fedpK}, b); + } else { + tm::mma(idesc, tm::smem_desc(a_off + kt * kKtBytes, kALd), b); + } + } + tm::commit(empty_bar(s), 2); + } + tm::commit(done_bar, num_warps + 1); + } + + // Epilogue: wait for the MMAs; warp r drains TMEM lanes (M rows) + // [r*xtileM, (r+1)*xtileM), xtileN columns per load. + vx_barrier(done_bar, num_warps + 1); + + const uint32_t lane = tm::warp_lane(); + for (uint32_t c = 0; c < TMEM_NCHUNK; ++c) { + ctx::fragment_acc fragC; + uint32_t col = taddr + c * ctx::xtileN; + auto pChunkC = pC + (tile_row + lane) * N + tile_col + c * ctx::xtileN; + #ifdef TMEM_LANE_PER_THREAD + // Thread t holds one M row; a store writes NT rows. + constexpr uint32_t kThreadsPerLane = VX_CFG_NUM_THREADS / ctx::xtileM; + const uint32_t t = vx_thread_id(); + tm::load(fragC, tm::make_taddr(lane, col)); + auto pRowC = reinterpret_cast(pChunkC + (t % ctx::xtileM) * N + t / ctx::xtileM); + for (uint32_t r = 0; r < ctx::fragment_acc::NR; ++r) { + pRowC[r * kThreadsPerLane] = fragC.data[r]; + } + #else + // The WGMMA accumulator layout: the WGMMA context stores it. + tm::load(fragC, tm::make_taddr(lane, col)); + ctx::store_matrix_sync(pChunkC, fragC, N); + #endif + } + + vx_barrier(load_bar, num_warps); + if (warp_rank == 0) { + tm::dealloc(taddr, tmem_cols); + } +} diff --git a/tests/regression/sgemm_tcu_tmem/main.cpp b/tests/regression/sgemm_tcu_tmem/main.cpp new file mode 100644 index 0000000000..f9a56c709c --- /dev/null +++ b/tests/regression/sgemm_tcu_tmem/main.cpp @@ -0,0 +1,759 @@ +#include "common.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// The TCU chains K/tileK dot-product ops, each rounding its accumulator to fp32 +// once, while the CPU reference accumulates in double (no intermediate rounding). +// A wider tile rounds fewer times but sums more elements per rounding, so the two +// effects cancel and the drift tracks K rather than the chain depth: it measures +// ~K/8 ULP across every gated NUM_THREADS (16 ULP at K=128 for both tileK=8 and +// tileK=16). float_ulp() therefore scales with K and carries 2x headroom, since a +// fixed bound silently depends on the tile shape. The RTL datapath itself is +// verified bit-exactly against its windowed reference by hw/unittest/tcu_fedp +// (`make -C hw/unittest run-tcu`), so this bounds a reference idealization, not a +// hardware tolerance. +static uint32_t g_float_ulp = 16; +static uint32_t g_max_ulp = 0; + +static uint32_t float_ulp(uint32_t K) { + return std::max(8, K / 5); +} +#define MAX_ERRORS 100 + +#define RT_CHECK(_expr) \ + do { \ + int _ret = _expr; \ + if (0 == _ret) \ + break; \ + printf("Error: '%s' returned %d!\n", #_expr, (int)_ret); \ + cleanup(); \ + exit(-1); \ + } while (false) + +using namespace vortex; +namespace vt = tensor; + +/////////////////////////////////////////////////////////////////////////////// + +template +class Comparator {}; + +template <> +class Comparator { +public: + static float generate() { + return static_cast(rand()) / RAND_MAX; + } + static bool compare(float a, float b, int index, int errors) { + union fi_t { + float f; + int32_t i; + }; + fi_t fa, fb; + fa.f = a; + fb.f = b; + auto d = std::abs(fa.i - fb.i); + g_max_ulp = std::max(g_max_ulp, static_cast(d)); + if (d > static_cast(g_float_ulp)) { + if (errors < MAX_ERRORS) { + printf("*** error: [%d] expected=%f, actual=%f\n", index, fb.f, fa.f); + } + return false; + } + return true; + } +}; + +template <> +class Comparator { +public: + static uint16_t generate() { + auto fvalue = float(rand()) / RAND_MAX; + return rv_ftoh_s(bit_cast(fvalue), 0, nullptr); + } + static bool compare(uint16_t a, uint16_t b, int index, int errors) { + if (a != b) { + if (errors < MAX_ERRORS) { + printf("*** error: [%d] expected=0x%x, actual=0x%x\n", index, b, a); + } + return false; + } + return true; + } +}; + +template <> +class Comparator { +public: + static uint16_t generate() { + auto fvalue = float(rand()) / RAND_MAX; + return rv_ftob_s(bit_cast(fvalue), 0, nullptr); + } +}; + +template <> +class Comparator { +public: + static uint8_t generate() { + auto fvalue = float(rand()) / RAND_MAX; + return rv_ftoe4m3_s(bit_cast(fvalue), 0, nullptr); + } + static bool compare(uint8_t a, uint8_t b, int index, int errors) { + if (a != b) { + if (errors < MAX_ERRORS) { + printf("*** error: [%d] expected=0x%x, actual=0x%x\n", index, b, a); + } + return false; + } + return true; + } +}; + +template <> +class Comparator { +public: + static uint8_t generate() { + auto fvalue = float(rand()) / RAND_MAX; + return rv_ftoe5m2_s(bit_cast(fvalue), 0, nullptr); + } + static bool compare(uint8_t a, uint8_t b, int index, int errors) { + if (a != b) { + if (errors < MAX_ERRORS) { + printf("*** error: [%d] expected=0x%x, actual=0x%x\n", index, b, a); + } + return false; + } + return true; + } +}; + +template <> +class Comparator { +public: + static int8_t generate() { + return static_cast(rand()); + } + static bool compare(int8_t a, int8_t b, int index, int errors) { + if (a != b) { + if (errors < MAX_ERRORS) { + printf("*** error: [%d] expected=%d, actual=%d\n", index, b, a); + } + return false; + } + return true; + } +}; + +template <> +class Comparator { +public: + static int32_t generate() { + return static_cast(rand()); + } + static bool compare(int32_t a, int32_t b, int index, int errors) { + if (a != b) { + if (errors < MAX_ERRORS) { + printf("*** error: [%d] expected=%d, actual=%d\n", index, b, a); + } + return false; + } + return true; + } +}; + +template <> +class Comparator { +public: + static uint32_t generate() { + auto fvalue = float(rand()) / RAND_MAX; + return rv_ftotf32_s(bit_cast(fvalue), 0, nullptr); + } + static bool compare(uint32_t a, uint32_t b, int index, int errors) { + if (a != b) { + if (errors < MAX_ERRORS) { + printf("*** error: [%d] expected=0x%x, actual=0x%x\n", index, b, a); + } + return false; + } + return true; + } +}; + +/////////////////////////////////////////////////////////////////////////////// + +template +struct muladd_t { + using stype = typename S::dtype; + using dtype = typename D::dtype; + static dtype eval(stype a, stype b, dtype c) { + return static_cast(a) * static_cast(b) + c; + } +}; + +template <> +struct muladd_t { + static float eval(uint16_t a, uint16_t b, float c) { + auto fa = bit_cast(rv_htof_s(a, 0, nullptr)); + auto fb = bit_cast(rv_htof_s(b, 0, nullptr)); + return fa * fb + c; + } +}; + +template <> +struct muladd_t { + static float eval(uint16_t a, uint16_t b, float c) { + auto fa = bit_cast(rv_btof_s(a, 0, nullptr)); + auto fb = bit_cast(rv_btof_s(b, 0, nullptr)); + return fa * fb + c; + } +}; + +template <> +struct muladd_t { + static float eval(uint8_t a, uint8_t b, float c) { + auto fa = bit_cast(rv_e4m3tof_s(a, 0, nullptr)); + auto fb = bit_cast(rv_e4m3tof_s(b, 0, nullptr)); + return fa * fb + c; + } +}; + +template <> +struct muladd_t { + static uint8_t eval(uint8_t a, uint8_t b, uint8_t c) { + auto fa = bit_cast(rv_e4m3tof_s(a, 0, nullptr)); + auto fb = bit_cast(rv_e4m3tof_s(b, 0, nullptr)); + auto fc = bit_cast(rv_e4m3tof_s(c, 0, nullptr)); + auto fd = fa * fb + fc; + return rv_ftoe4m3_s(bit_cast(fd), 0, nullptr); + } +}; + +template <> +struct muladd_t { + static float eval(uint8_t a, uint8_t b, float c) { + auto fa = bit_cast(rv_e5m2tof_s(a, 0, nullptr)); + auto fb = bit_cast(rv_e5m2tof_s(b, 0, nullptr)); + return fa * fb + c; + } +}; + +template <> +struct muladd_t { + static uint8_t eval(uint8_t a, uint8_t b, uint8_t c) { + auto fa = bit_cast(rv_e5m2tof_s(a, 0, nullptr)); + auto fb = bit_cast(rv_e5m2tof_s(b, 0, nullptr)); + auto fc = bit_cast(rv_e5m2tof_s(c, 0, nullptr)); + auto fd = fa * fb + fc; + return rv_ftoe5m2_s(bit_cast(fd), 0, nullptr); + } +}; + +template <> +struct muladd_t { + static float eval(uint32_t a, uint32_t b, float c) { + auto fa = bit_cast(rv_tf32tof_s(a, 0, nullptr)); + auto fb = bit_cast(rv_tf32tof_s(b, 0, nullptr)); + return fa * fb + c; + } +}; + +template <> +struct muladd_t { + static uint32_t eval(uint32_t a, uint32_t b, uint32_t c) { + auto fa = bit_cast(rv_tf32tof_s(a, 0, nullptr)); + auto fb = bit_cast(rv_tf32tof_s(b, 0, nullptr)); + auto fc = bit_cast(rv_tf32tof_s(c, 0, nullptr)); + auto fd = fa * fb + fc; + return rv_ftotf32_s(bit_cast(fd), 0, nullptr); + } +}; + +/////////////////////////////////////////////////////////////////////////////// + +using cfg = vt::wgmma_config_t; + +using itype_t = typename vt::ITYPE::dtype; +using otype_t = typename vt::OTYPE::dtype; + +#ifdef TMEM_SPARSE +constexpr bool kSparse = true; +constexpr uint32_t kTileK = cfg::tileK_sp; +#else +constexpr bool kSparse = false; +constexpr uint32_t kTileK = cfg::tileK; +#endif +#ifdef TMEM_A +constexpr bool kATmem = true; +#else +constexpr bool kATmem = false; +#endif +static constexpr uint32_t kIRatio = 32 / vt::ITYPE::bits; +static constexpr uint32_t kMetaRow = cfg::tcK * 2 * kIRatio; +static constexpr uint32_t kMetaCols = ((cfg::fedpK / cfg::tcK) * kMetaRow + 31) / 32; +// TMEM is stored fragment-major: a K step's metadata takes one fragment group +// (tcN columns) per lane. +static constexpr uint32_t kFragCols = cfg::tcN; +static_assert(kMetaCols <= kFragCols, "a K step's metadata fits a fragment group"); +static constexpr uint32_t kStoreCols = WGMMA_NRC * (VX_CFG_NUM_THREADS / cfg::xtileM); + +#ifdef TMEM_SPARSE +// kFragCols words per (row, K step): from bit 0, the VX_tcu_sp_mux rows of the +// step's lower then upper TC_K words. +static std::vector pack_tmem_metadata(const std::vector& masks, uint32_t M, uint32_t K) { + const uint32_t k_tiles = K / kTileK; + const uint32_t groups_per_row = K / 4; + const uint32_t half_elems = cfg::tcK * kIRatio * 2; + std::vector meta(size_t(M) * k_tiles * kFragCols, 0); + for (uint32_t row = 0; row < M; ++row) { + for (uint32_t g = 0; g < groups_per_row; ++g) { + uint8_t mask = masks[row * groups_per_row + g]; + for (uint32_t p = 0; p < 4; ++p) { + if (!(mask & (1u << p))) continue; + uint32_t k = g * 4 + p; + uint32_t kt = k / kTileK; + uint32_t elt = k % kTileK; + uint32_t half = elt / half_elems; + uint32_t e = elt % half_elems; + uint32_t k_reg = e / (2 * kIRatio); + uint32_t pos = e % (2 * kIRatio); + uint32_t bit = (pos < kIRatio) ? (k_reg * kIRatio + pos) + : ((cfg::tcK + k_reg) * kIRatio + (pos - kIRatio)); + bit += half * kMetaRow; + meta[(size_t(row) * k_tiles + kt) * kFragCols + bit / 32] |= 1u << (bit % 32); + } + } + } + return meta; +} + +// tc.cp's source: each cta_M-row band of the metadata in TMEM storage order, +// column group by column group, block by block, M step by M step, NT words +// (word i*tcN + j: lane m*tcM + i of the block, column j of the group). +[[maybe_unused]] static std::vector pack_tmem_storage_order(const std::vector& meta, uint32_t M, + uint32_t cols, uint32_t cta_M) { + std::vector out(meta.size()); + size_t w = 0; + for (uint32_t band = 0; band < M; band += cta_M) { + for (uint32_t g = 0; g < cols; g += kFragCols) { + for (uint32_t b = 0; b < cta_M / cfg::xtileM; ++b) { + for (uint32_t m = 0; m < cfg::m_steps; ++m) { + for (uint32_t i = 0; i < cfg::tcM; ++i) { + for (uint32_t j = 0; j < kFragCols; ++j) { + uint32_t row = band + b * cfg::xtileM + m * cfg::tcM + i; + out[w++] = meta[size_t(row) * cols + g + j]; + } + } + } + } + } + } + return out; +} +#endif + +static void matmul_cpu(otype_t *C, const itype_t *A, const itype_t *B, + uint32_t M, uint32_t N, uint32_t K) { + for (uint32_t m = 0; m < M; ++m) { + for (uint32_t n = 0; n < N; ++n) { + if constexpr (std::is_same::value) { + // fp32 output: the tensor core accumulates the K products in a wide + // accumulator and rounds to fp32 once; a per-step-rounded reference + // drifts by several ULP over K. Each product is exact in fp32, so a + // double accumulation reproduces the single-rounding dot product. + double acc = 0.0; + for (uint32_t k = 0; k < K; ++k) { + acc += static_cast(muladd_t::eval(A[m * K + k], B[k * N + n], otype_t(0))); + } + C[m * N + n] = static_cast(acc); + } else { + // Narrow outputs re-round the accumulator to the output type every + // step, matching the hardware chain exactly. + otype_t sum(0); + for (uint32_t k = 0; k < K; ++k) { + sum = muladd_t::eval(A[m * K + k], B[k * N + n], sum); + } + C[m * N + n] = sum; + } + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +const char *kernel_file = "kernel.vxbin"; + +uint32_t xm = 64; +uint32_t xn = 64; +uint32_t xk = 64; +// `warps` (= warps per CTA = WGMMA group size) is derived at runtime from +// VX_CAPS_ISSUE_WIDTH after the device opens. WGMMA requires CTA-warp count +// to match the hardware's TCU BLOCK_SIZE (= ISSUE_WIDTH), so it's not a +// user-facing knob. +uint32_t warps = 0; + +vx_device_h device = nullptr; +vx_buffer_h A_buffer = nullptr; +vx_buffer_h B_buffer = nullptr; +vx_buffer_h C_buffer = nullptr; +vx_buffer_h meta_buffer = nullptr; +vx_queue_h queue = nullptr; +vx_module_h module_ = nullptr; +vx_kernel_h kernel = nullptr; +kernel_arg_t kernel_arg = {}; +constexpr uint32_t kDescA = 0; +constexpr uint32_t kDescB = 1; +[[maybe_unused]] constexpr uint32_t kDescMeta = 2; + +static void show_usage() { + std::cout << "Vortex SGEMM TCU WGMMA+DXA Test." << std::endl; + std::cout << "Usage: [-m M] [-n N] [-k K] [-h help]" << std::endl; +} + +static void parse_args(int argc, char **argv) { + int c; + while ((c = getopt(argc, argv, "m:n:k:h")) != -1) { + switch (c) { + case 'm': xm = atoi(optarg); break; + case 'n': xn = atoi(optarg); break; + case 'k': xk = atoi(optarg); break; + case 'h': show_usage(); exit(0); break; + default: show_usage(); exit(-1); + } + } +} + +void cleanup() { + if (device) { + if (A_buffer) vx_buffer_release(A_buffer); + if (B_buffer) vx_buffer_release(B_buffer); + if (C_buffer) vx_buffer_release(C_buffer); + if (meta_buffer) vx_buffer_release(meta_buffer); + if (kernel) vx_kernel_release(kernel); + if (module_) vx_module_release(module_); + if (queue) vx_queue_release(queue); + vx_device_dump_perf(device, stdout); + vx_device_release(device); + } +} + +int main(int argc, char *argv[]) { + parse_args(argc, argv); + + std::srand(50); + + std::cout << "open device connection" << std::endl; + RT_CHECK(vx_device_open(0, &device)); + + vx_queue_info_t qi = { sizeof(qi), nullptr, VX_QUEUE_PRIORITY_NORMAL, 0 }; + RT_CHECK(vx_queue_create(device, &qi, &queue)); + + // Check TCU extension + uint64_t isa_flags; + RT_CHECK(vx_device_query(device, VX_CAPS_ISA_FLAGS, &isa_flags)); + if (!(isa_flags & VX_ISA_EXT_TCU)) { + std::cout << "TCU extension not supported!" << std::endl; + cleanup(); + return -1; + } + + // Check DXA extension + if ((isa_flags & VX_ISA_EXT_DXA) == 0) { + std::cerr << "Error: DXA ISA extension is disabled." << std::endl; + cleanup(); + return -1; + } + + uint64_t NT; + RT_CHECK(vx_device_query(device, VX_CAPS_NUM_THREADS, &NT)); + if (NT != VX_CFG_NUM_THREADS) { + std::cout << "Error: device thread count (" << NT + << ") must match VX_CFG_NUM_THREADS=" << VX_CFG_NUM_THREADS << std::endl; + return -1; + } + + uint64_t num_warps; + RT_CHECK(vx_device_query(device, VX_CAPS_NUM_WARPS, &num_warps)); + + // WGMMA group size = ISSUE_WIDTH. The hardware lockstep gate dispatches + // BLOCK_SIZE = ISSUE_WIDTH warps in parallel per uop, so the CTA must + // launch exactly that many active warps. Derived here, not user-tunable. + uint64_t issue_width; + RT_CHECK(vx_device_query(device, VX_CAPS_ISSUE_WIDTH, &issue_width)); + warps = (uint32_t)issue_width; + if (warps > num_warps) { + std::cout << "Error: WGMMA group size (" << warps + << " = VX_CFG_ISSUE_WIDTH) exceeds device's per-core warp count (" + << num_warps << ")" << std::endl; + return -1; + } + + uint32_t M = xm; + uint32_t N = xn; + uint32_t K = xk; + + g_float_ulp = float_ulp(K); + +#ifdef WARP_SPEC + // One of the `warps` launched warps is a dedicated DXA producer (never + // computes), so only (warps-1) warps contribute an M-row band. + if (warps < 2) { + std::cout << "Error: WARP_SPEC needs at least 2 warps (1 producer + >=1 consumer)" << std::endl; + return -1; + } + uint32_t cta_M = (warps - 1) * cfg::xtileM; +#else + uint32_t cta_M = warps * cfg::xtileM; +#endif + + if ((M % cta_M) != 0) { + std::cout << "Error: M (" << M << ") must be a multiple of cta_M=" << cta_M << std::endl; + return -1; + } + const uint32_t tile_n = cfg::xtileN * TMEM_NCHUNK; + if ((N % tile_n) != 0) { + std::cout << "Error: N (" << N << ") must be a multiple of tileN=" << tile_n << std::endl; + return -1; + } + if ((K % kTileK) != 0) { + std::cout << "Error: K (" << K << ") must be a multiple of tileK=" << kTileK << std::endl; + return -1; + } + // DEEP_BUF stages hold KB K-tiles (kernel.cpp: kBK); other paths use one. +#if defined(DEEP_BUF) + const uint32_t stage_k = KB * kTileK; +#else + const uint32_t stage_k = kTileK; +#endif + const uint32_t stage_ka = kSparse ? (stage_k / 2) : stage_k; + if ((K % stage_k) != 0) { + std::cout << "Error: K (" << K << ") must be a multiple of KB*tileK=" << stage_k << std::endl; + return -1; + } + + size_t sizeA = M * K; + size_t sizeA_dev = kSparse ? (size_t(M) * (K / 2)) : sizeA; + size_t sizeB = K * N; + size_t sizeC = M * N; + + // Grid: one block per CTA output tile. Block: warps * NT threads. + uint32_t grid_dim[2] = {N / tile_n, M / cta_M}; + uint32_t block_dim[2] = {warps * (uint32_t)NT, 1}; + + // SMEM: A tile [cta_M x tileK] + B tile [tileK x tileN] + uint32_t smem_size = ((kATmem ? 0 : cta_M * stage_ka) + stage_k * tile_n) * sizeof(itype_t); + smem_size *= PIPE_N; // N-stage pipeline (common.h) + const uint32_t meta_words = (K / kTileK) * kFragCols; + const uint32_t meta_pitch = (meta_words + NT - 1) / NT * NT; + // kernel.cpp stages the CTA's metadata rows at the window base, each padded + // to NT words (meta_pitch), and the + // TMEM copy reads up to one store past their end. + if (kSparse) { + smem_size = std::max(smem_size, (cta_M * meta_pitch + kStoreCols) * uint32_t(sizeof(uint32_t))); + } + smem_size += TMEM_SLOT_BYTES; + + // The CTA's TMEM budget, as kernel.cpp allocates it: D, then A (TMEM_A), + // then the metadata, each rounded to whole tmem::store fragments. + auto round_store = [](uint32_t cols) { return (cols + kStoreCols - 1) / kStoreCols * kStoreCols; }; + const uint32_t k_steps_total = (K / kTileK) * (kSparse ? 1 : cfg::k_steps); + uint32_t tmem_cols = tile_n + (kATmem ? round_store(k_steps_total * cfg::fedpK) : 0) + + (kSparse ? round_store(meta_words) : 0); + { + uint32_t n = 32; + while (n < tmem_cols) n <<= 1; + tmem_cols = n; + } + + std::cout << "input type: " << vt::ITYPE::name << ", output type: " << vt::OTYPE::name << std::endl; + std::cout << "warp tile: M=" << cfg::xtileM << ", N=" << tile_n << ", K=" << cfg::tileK << std::endl; + std::cout << "CTA tile: M=" << cta_M << " (warps=" << warps << ")" << std::endl; + std::cout << "grid: " << grid_dim[0] << "x" << grid_dim[1] << std::endl; + std::cout << "block: " << block_dim[0] << "x" << block_dim[1] << std::endl; + std::cout << "matrix A: " << M << "x" << K << std::endl; + std::cout << "matrix B: " << K << "x" << N << std::endl; + std::cout << "smem: " << smem_size << " bytes" << std::endl; + + kernel_arg.M = M; + kernel_arg.N = N; + kernel_arg.K = K; + + std::cout << "allocate device memory" << std::endl; + RT_CHECK(vx_buffer_create(device, sizeA_dev * sizeof(itype_t), VX_MEM_READ, &A_buffer)); + RT_CHECK(vx_buffer_address(A_buffer, &kernel_arg.A_addr)); + RT_CHECK(vx_buffer_create(device, sizeB * sizeof(itype_t), VX_MEM_READ, &B_buffer)); + RT_CHECK(vx_buffer_address(B_buffer, &kernel_arg.B_addr)); + RT_CHECK(vx_buffer_create(device, sizeC * sizeof(otype_t), VX_MEM_WRITE, &C_buffer)); + RT_CHECK(vx_buffer_address(C_buffer, &kernel_arg.C_addr)); + + std::cout << "A_addr=0x" << std::hex << kernel_arg.A_addr << std::dec << std::endl; + std::cout << "B_addr=0x" << std::hex << kernel_arg.B_addr << std::dec << std::endl; + std::cout << "C_addr=0x" << std::hex << kernel_arg.C_addr << std::dec << std::endl; + + // Generate source data + std::vector h_A(sizeA); + std::vector h_B(sizeB); + for (uint32_t i = 0; i < sizeA; ++i) { + h_A[i] = Comparator::generate(); + } + for (uint32_t i = 0; i < sizeB; ++i) { + h_B[i] = Comparator::generate(); + } + + // Sparse: h_A becomes the pruned operand the CPU reference uses; the device + // holds its compressed form and the metadata. Must outlive the async writes. + std::vector h_A_dev = h_A; + std::vector h_meta; +#ifdef TMEM_SPARSE + if (!vt::prune_2to4_matrix(h_A.data(), M, K)) { + std::cerr << "prune_2to4_matrix failed" << std::endl; + cleanup(); + return -1; + } + h_A_dev.resize(sizeA_dev); + std::vector masks; + if (!vt::compress_2to4_matrix(h_A_dev.data(), h_A.data(), masks, M, K)) { + std::cerr << "compress_2to4_matrix failed" << std::endl; + cleanup(); + return -1; + } + h_meta = pack_tmem_metadata(masks, M, K); +#ifdef TMEM_CP + h_meta = pack_tmem_storage_order(h_meta, M, (K / kTileK) * kFragCols, cta_M); +#endif + RT_CHECK(vx_buffer_create(device, h_meta.size() * sizeof(uint32_t), VX_MEM_READ, &meta_buffer)); + RT_CHECK(vx_buffer_address(meta_buffer, &kernel_arg.meta_addr)); + RT_CHECK(vx_enqueue_write(queue, meta_buffer, 0, h_meta.data(), h_meta.size() * sizeof(uint32_t), 0, nullptr, nullptr)); +#endif + + // The device holds B^T ([N][K], K contiguous). h_B stays the logical [K][N] + // operand the CPU reference uses. h_BT must outlive the async write below. + std::vector h_BT(sizeB); + for (uint32_t k = 0; k < K; ++k) { + for (uint32_t n = 0; n < N; ++n) { + h_BT[(size_t)n * K + k] = h_B[(size_t)k * N + n]; + } + } + const itype_t* b_upload = h_BT.data(); + + std::cout << "upload source data" << std::endl; + RT_CHECK(vx_enqueue_write(queue, A_buffer, 0, h_A_dev.data(), sizeA_dev * sizeof(itype_t), 0, nullptr, nullptr)); + RT_CHECK(vx_enqueue_write(queue, B_buffer, 0, b_upload, sizeB * sizeof(itype_t), 0, nullptr, nullptr)); + + // Program DXA descriptors. + // Descriptor A: fetches tileK columns x cta_M rows from A[row, k]. + // dim0 = K-axis (tile0 = tileK), dim1 = M-axis (tile1 = cta_M) + // stride0_bytes = row stride of A = K * sizeof(itype_t) + RT_CHECK(vortex::dxa::program_2d(device, kDescA, kernel_arg.A_addr, + /*size0=*/uint32_t(sizeA_dev / M), /*size1=*/M, + /*stride0_bytes=*/uint32_t(sizeA_dev / M) * sizeof(itype_t), + /*tile0=*/stage_ka, /*tile1=*/cta_M, + /*elem_bytes=*/sizeof(itype_t))); + + // Descriptor B: B^T[N][K] in memory; a plain row-major copy of a + // [tileN][tileK] tile (dim0 = K, dim1 = N). + RT_CHECK(vortex::dxa::program_2d(device, kDescB, kernel_arg.B_addr, + /*size0=*/K, /*size1=*/N, + /*stride0_bytes=*/K * sizeof(itype_t), + /*tile0=*/stage_k, /*tile1=*/tile_n, + /*elem_bytes=*/sizeof(itype_t))); + RT_CHECK(vortex::dxa::set_layout(device, kDescB, + vortex::dxa::Layout::RowMajor, /*rank=*/2, /*elem_bytes=*/sizeof(itype_t))); + +#ifdef TMEM_SPARSE + // Descriptor Meta: a CTA's metadata, all K steps at once: for tc.cp its band's + // storage-order blob as one row, else its cta_M rows. +#ifdef TMEM_CP + RT_CHECK(vortex::dxa::program_2d(device, kDescMeta, kernel_arg.meta_addr, + /*size0=*/cta_M * meta_words, /*size1=*/M / cta_M, + /*stride0_bytes=*/cta_M * meta_words * sizeof(uint32_t), + /*tile0=*/cta_M * meta_words, /*tile1=*/1, + /*elem_bytes=*/sizeof(uint32_t))); +#else + RT_CHECK(vortex::dxa::program_2d(device, kDescMeta, kernel_arg.meta_addr, + /*size0=*/meta_words, /*size1=*/M, + /*stride0_bytes=*/meta_words * sizeof(uint32_t), + /*tile0=*/meta_pitch, /*tile1=*/cta_M, + /*elem_bytes=*/sizeof(uint32_t))); +#endif +#endif + + std::cout << "load kernel module" << std::endl; + RT_CHECK(vx_module_load_file(device, kernel_file, &module_)); + RT_CHECK(vx_module_get_kernel(module_, "main", &kernel)); + + // Host result buffer — must outlive the async read enqueued below. + std::vector h_C(sizeC); + + auto time_start = std::chrono::high_resolution_clock::now(); + + std::cout << "start device" << std::endl; + vx_event_h launch_ev = nullptr; + { + vx_launch_info_t li = {}; + li.struct_size = sizeof(li); + li.kernel = kernel; + li.args_host = &kernel_arg; + li.args_size = sizeof(kernel_arg); + li.ndim = 2; + li.grid_dim[0] = grid_dim[0]; + li.grid_dim[1] = grid_dim[1]; + li.block_dim[0] = block_dim[0]; + li.block_dim[1] = block_dim[1]; + li.lmem_size = smem_size; + li.tmem_cols = tmem_cols; + RT_CHECK(vx_enqueue_launch(queue, &li, 0, nullptr, &launch_ev)); + } + + // Download result — chained after the launch on the same queue + std::cout << "download result" << std::endl; + vx_event_h read_ev = nullptr; + RT_CHECK(vx_enqueue_read(queue, h_C.data(), C_buffer, 0, sizeC * sizeof(otype_t), 1, &launch_ev, &read_ev)); + + std::cout << "wait for completion" << std::endl; + RT_CHECK(vx_event_wait_value(read_ev, 1, VX_TIMEOUT_INFINITE)); + vx_event_release(read_ev); + vx_event_release(launch_ev); + + auto time_end = std::chrono::high_resolution_clock::now(); + double elapsed = std::chrono::duration_cast(time_end - time_start).count(); + printf("Elapsed time: %lg ms\n", elapsed); + + std::cout << "verify result" << std::endl; + int errors = 0; + { + std::vector h_ref(sizeC); + matmul_cpu(h_ref.data(), h_A.data(), h_B.data(), M, N, K); + for (uint32_t i = 0; i < h_ref.size(); ++i) { + if (!Comparator::compare(h_C[i], h_ref[i], i, errors)) { + ++errors; + } + } + } + + // std::dec: an earlier dump leaves the stream in hex. + std::cout << std::dec << "reference drift: max=" << g_max_ulp << " ULP, bound=" + << g_float_ulp << " ULP (K=" << K << ")" << std::endl; + + cleanup(); + + if (errors != 0) { + std::cout << "Found " << std::dec << errors << " / " << sizeC << " errors!" << std::endl; + std::cout << "FAILED!" << std::endl; + return 1; + } + + std::cout << "PASSED!" << std::endl; + return 0; +} diff --git a/tests/regression/sgemm_tcu_tmem_mx/Makefile b/tests/regression/sgemm_tcu_tmem_mx/Makefile new file mode 100644 index 0000000000..b19d2d7a90 --- /dev/null +++ b/tests/regression/sgemm_tcu_tmem_mx/Makefile @@ -0,0 +1,23 @@ +ROOT_DIR := $(realpath ../../..) +include $(ROOT_DIR)/config.mk + +CONFIGS := $(if $(findstring -DVX_CFG_EXT_TCU_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_EXT_TCU_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_TCU_MX_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_TCU_MX_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_TCU_FP8_ENABLE,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_TCU_FP8_ENABLE) +CONFIGS := $(if $(findstring -DVX_CFG_NUM_WARPS=,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_NUM_WARPS=4) +CONFIGS := $(if $(findstring -DVX_CFG_ISSUE_WIDTH=,$(CONFIGS)),$(CONFIGS),$(CONFIGS) -DVX_CFG_ISSUE_WIDTH=4) +CONFIGS += -DVX_CFG_TCU_WGMMA_ENABLE -DVX_CFG_TCU_TMEM_ENABLE -DVX_CFG_EXT_DXA_ENABLE + +PROJECT := sgemm_tcu_tmem_mx +SRC_DIR := $(VORTEX_HOME)/tests/regression/$(PROJECT) +SRCS := $(SRC_DIR)/main.cpp $(SW_COMMON_DIR)/rvfloats.cpp $(SW_COMMON_DIR)/softfloat_ext.cpp +VX_SRCS := $(SRC_DIR)/kernel.cpp + +OPTS := $(OPTS) $(if $(findstring -m,$(OPTS)),,-m 64) +OPTS := $(OPTS) $(if $(findstring -n,$(OPTS)),,-n 64) +OPTS := $(OPTS) $(if $(findstring -k,$(OPTS)),,-k 64) +CXXFLAGS += -I$(THIRD_PARTY_DIR)/softfloat/source/include +LDFLAGS += $(THIRD_PARTY_DIR)/softfloat/build/Linux-x86_64-GCC/softfloat.a +KERNEL_LIB := vortex2 + +include ../common.mk diff --git a/tests/regression/sgemm_tcu_tmem_mx/common.h b/tests/regression/sgemm_tcu_tmem_mx/common.h new file mode 100644 index 0000000000..04bdd91018 --- /dev/null +++ b/tests/regression/sgemm_tcu_tmem_mx/common.h @@ -0,0 +1,30 @@ +#ifndef _SGEMM_TCU_TMEM_MX_COMMON_H_ +#define _SGEMM_TCU_TMEM_MX_COMMON_H_ + +#include + +#ifndef WGMMA_NRC +#define WGMMA_NRC 8 +#endif +#ifndef ITYPE +#define ITYPE mxfp8 +#endif +#ifndef OTYPE +#define OTYPE fp32 +#endif + +// Shared memory starts with the CTA's TMEM column, padded to keep the tiles aligned. +#define TMEM_SLOT_BYTES 64 + +typedef struct { + uint32_t M, N, K; // K in storage bytes + uint32_t sf_cols; // TMEM columns of one K step's scales + uint32_t img_words; // words of one CTA's scale image + uint64_t A_addr, B_addr, C_addr; + uint64_t SF_addr; // the CTAs' scale images, tc.cp storage order +#ifdef TCU_MX_TLS + uint64_t A_tensor_scale_addr, B_tensor_scale_addr; +#endif +} kernel_arg_t; + +#endif diff --git a/tests/regression/sgemm_tcu_tmem_mx/kernel.cpp b/tests/regression/sgemm_tcu_tmem_mx/kernel.cpp new file mode 100644 index 0000000000..0f3e82d7b7 --- /dev/null +++ b/tests/regression/sgemm_tcu_tmem_mx/kernel.cpp @@ -0,0 +1,115 @@ +#include "common.h" +#include +#include +#include +#include +#include + +// MX GEMM with the accumulator in TMEM. One warp per TCU block; warp 0's +// thread 0 issues one tc.mma per K step with the step's A and B scales in +// TMEM (vx_tmem.h, MX scales), copied in once with tc.cp. + +namespace vt = vortex::tensor; +namespace tm = vortex::tmem; +using ctx = vt::wgmma_context; +using wg_cfg = vt::wgmma_config_t; + +static constexpr uint32_t kTileN = ctx::xtileN; +static constexpr uint32_t kStepB = wg_cfg::fedpK * 4; // bytes of K per tc.mma + +__kernel void kernel_main(kernel_arg_t* __UNIFORM__ arg) { + static_assert(sizeof(ctx::input_t) == 1, "MX inputs use byte storage"); + auto pA = reinterpret_cast(arg->A_addr); + auto pB = reinterpret_cast(arg->B_addr); + auto pC = reinterpret_cast(arg->C_addr); + auto pSF = reinterpret_cast(arg->SF_addr); + + const uint32_t N = arg->N; + const uint32_t K = arg->K; + const uint32_t tid = threadIdx.x; + const uint32_t num_threads = blockDim.x; + const uint32_t warp_rank = tid / VX_CFG_NUM_THREADS; + const uint32_t num_warps = num_threads / VX_CFG_NUM_THREADS; + const uint32_t cta_m = num_warps * ctx::xtileM; + const uint32_t tile_row = blockIdx.y * cta_m; + const uint32_t tile_col = blockIdx.x * kTileN; + const uint32_t ksteps = K / kStepB; + + auto lmem = reinterpret_cast(__local_mem()); + auto tmem_slot = reinterpret_cast(lmem); + auto img_smem = reinterpret_cast(lmem + TMEM_SLOT_BYTES); + auto A_smem = reinterpret_cast(img_smem + arg->img_words); + auto B_smem = A_smem + cta_m * ctx::tileK; + + const uint32_t cta_id = get_local_group_id(); + const uint32_t load_bar = cta_id | (0u << 8); + const uint32_t mma_bar = cta_id | (1u << 8); + + // TMEM: D, then every K step's scales. + const uint32_t tmem_cols = tm::alloc_cols(kTileN + ksteps * arg->sf_cols); + if (warp_rank == 0) { + uint32_t col = tm::alloc(tmem_cols); + if (vx_thread_id() == 0) { + *tmem_slot = col; + } + } + // The CTA's scale image, staged for tc.cp. + auto pImg = pSF + (blockIdx.y * gridDim.x + blockIdx.x) * arg->img_words; + for (uint32_t i = tid; i < arg->img_words; i += num_threads) { + img_smem[i] = pImg[i]; + } + vx_barrier(load_bar, num_warps); + const uint32_t taddr = *tmem_slot; + const uint32_t sf_col = taddr + kTileN; + if (warp_rank == 0 && vx_thread_id() == 0) { + tm::cp(sf_col, img_smem, ksteps * arg->sf_cols); + } + + const uint32_t n_frag = kTileN / wg_cfg::tcN; + for (uint32_t k = 0; k < K; k += ctx::tileK) { + for (uint32_t idx = tid; idx < cta_m * ctx::tileK; idx += num_threads) { + uint32_t row = idx / ctx::tileK; + uint32_t col = idx % ctx::tileK; + A_smem[idx] = pA[(tile_row + row) * K + k + col]; + } + for (uint32_t idx = tid; idx < kTileN * ctx::tileK; idx += num_threads) { + uint32_t col = idx / ctx::tileK; + uint32_t kb = idx % ctx::tileK; + B_smem[idx] = pB[(tile_col + col) * K + k + kb]; + } + vx_barrier(load_bar, num_warps); + if (warp_rank == 0 && vx_thread_id() == 0) { + const uint32_t a_off = tm::smem_offset(A_smem); + const uint32_t b_off = tm::smem_offset(B_smem); + for (uint32_t kt = 0; kt < ctx::tileK / kStepB; ++kt) { + const uint32_t gk = k / kStepB + kt; + const auto idesc = tm::make_idesc(n_frag, taddr, gk == 0, false, + sf_col + gk * arg->sf_cols); + tm::mma(idesc, tm::smem_desc(a_off + kt * kStepB, ctx::tileK), + tm::smem_desc(b_off + kt * kStepB, ctx::tileK)); + } + // The tiles are refilled only once these MMAs have read them. + tm::commit(mma_bar, num_warps + 1); + } + vx_barrier(mma_bar, num_warps + 1); + } + + ctx::fragment_acc fragC; + tm::load(fragC, tm::make_taddr(tm::warp_lane(), taddr)); +#ifdef TCU_MX_TLS + if constexpr (std::is_same::value) { + auto pAts = reinterpret_cast(arg->A_tensor_scale_addr); + auto pBts = reinterpret_cast(arg->B_tensor_scale_addr); + float tensor_scale = (*pAts) * (*pBts); + for (uint32_t r = 0; r < ctx::fragment_acc::NR; ++r) + fragC.data[r] *= tensor_scale; + } +#endif + ctx::store_matrix_sync(pC + (tile_row + warp_rank * ctx::xtileM) * N + tile_col, fragC, N); + + vx_barrier(load_bar, num_warps); + if (warp_rank == 0) { + tm::dealloc(taddr, tmem_cols); + } +} diff --git a/tests/regression/sgemm_tcu_tmem_mx/main.cpp b/tests/regression/sgemm_tcu_tmem_mx/main.cpp new file mode 100644 index 0000000000..0f65e20558 --- /dev/null +++ b/tests/regression/sgemm_tcu_tmem_mx/main.cpp @@ -0,0 +1,433 @@ +#include "common.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_ERRORS 100 + +#define RT_CHECK(_expr) \ + do { \ + int _ret = _expr; \ + if (0 == _ret) \ + break; \ + printf("Error: '%s' returned %d!\n", #_expr, (int)_ret); \ + cleanup(); \ + exit(-1); \ + } while (false) + +using namespace vortex; +namespace vt = tensor; + +using cfg = vt::wgmma_config_t; +static constexpr uint32_t kTileM = cfg::xtileM; +static constexpr uint32_t kTileN = cfg::xtileN; +using itype_t = typename vt::ITYPE::dtype; +using otype_t = typename vt::OTYPE::dtype; + +static_assert(vt::tcu_output_valid(vt::ITYPE::id, vt::OTYPE::id), + "TCU output type must be fp32 (int32 for integer inputs)"); + +static constexpr uint32_t kElemsPerByte = (vt::ITYPE::bits < 8) ? (8 / vt::ITYPE::bits) : 1; +// MX scales per A row / B column of a K step (one tc.mma: fedpK words). +static constexpr uint32_t kSf = vt::mx_max_fedp_sf(cfg::fedpK); +static constexpr uint32_t kStepElems = cfg::fedpK * 4 * kElemsPerByte; +static_assert(kSf <= 4 * cfg::tcN, "a row's scales fit one fragment group"); + +static uint8_t read_nibble(const uint8_t *ptr, uint32_t offset) { + uint8_t value = ptr[offset / 2]; + return (offset & 1) ? (value >> 4) : (value & 0x0f); +} + +// TMEM scale image of one CTA (rows [row0, row0 + cta_m), columns +// [col0, col0 + tile_n)), every K step, in tc.cp storage order. Per K step +// (sf_cols TMEM columns from step * sf_cols), as vx_tmem.h lays it out: +// A: lane l, column s/4, byte s%4 = scale s of row l. B: byte +// q = col * SF + s of a dense stream of NT*4-byte rows; row r is M step 1 of +// block r % BLOCKS at group 1 + r / BLOCKS. Scale s of a step covers its K +// elements from s * step_elems / SF. +static std::vector build_sf_image(const std::vector &scale_a, + const std::vector &scale_b, + uint32_t row0, uint32_t col0, uint32_t cta_m, + uint32_t tile_n, uint32_t N, uint32_t K_logical, + uint32_t sf_cols, uint32_t ksteps) { + constexpr uint32_t NT = VX_CFG_NUM_THREADS; + constexpr uint32_t BLOCKS = VX_CFG_NUM_TCU_BLOCKS; + constexpr uint32_t XM = cfg::xtileM; + constexpr uint32_t TCM = cfg::tcM; + constexpr uint32_t TCN = cfg::tcN; + constexpr uint32_t SF = kSf; + const uint32_t step_elems = kStepElems; + const uint32_t sbk = K_logical / vt::ITYPE::ele_block; + const uint32_t lanes = BLOCKS * XM; + const uint32_t cols = ksteps * sf_cols; + std::vector img(size_t(lanes) * cols, 0); // [lane][col] + auto put = [&](uint32_t lane, uint32_t col, uint32_t byte, uint8_t v) { + img[size_t(lane) * cols + col] |= uint32_t(v) << (8 * byte); + }; + for (uint32_t kk = 0; kk < ksteps; ++kk) { + uint32_t c0 = kk * sf_cols; + for (uint32_t s = 0; s < SF; ++s) { + uint32_t kb = (kk * step_elems + s * step_elems / SF) / vt::ITYPE::ele_block; + for (uint32_t l = 0; l < cta_m; ++l) { + put(l, c0 + s / 4, s % 4, scale_a[(row0 + l) * sbk + kb]); + } + for (uint32_t c = 0; c < tile_n; ++c) { + uint32_t q = c * SF + s; + uint32_t r = q / (NT * 4), o = q % (NT * 4); + uint32_t w = o / 4; + uint32_t lane = (r % BLOCKS) * XM + TCM + w / TCN; + uint32_t col = c0 + (1 + r / BLOCKS) * TCN + w % TCN; + put(lane, col, o % 4, scale_b[kb * N + col0 + c]); + } + } + } + // storage order: group by group, block by block, M step by M step, NT words + std::vector out; + out.reserve(img.size()); + for (uint32_t g = 0; g < cols / TCN; ++g) + for (uint32_t b = 0; b < BLOCKS; ++b) + for (uint32_t m = 0; m < cfg::m_steps; ++m) + for (uint32_t i = 0; i < TCM; ++i) + for (uint32_t j = 0; j < TCN; ++j) + out.push_back(img[size_t(b * XM + m * TCM + i) * cols + g * TCN + j]); + return out; +} + +static float dequantize_mx_value(const itype_t *data, + const std::vector &scales, + uint32_t offset, + uint32_t scale_index, + float tensor_scale) { + uint8_t sf = scales[scale_index]; + switch (vt::ITYPE::id) { + case vt::mxfp8::id: + return bit_cast(rv_mxfp8tof_s(data[offset], sf, 0, nullptr)); + case vt::mxbf8::id: + return bit_cast(rv_mxbf8tof_s(data[offset], sf, 0, nullptr)); + case vt::mxfp4::id: + { + uint8_t q = read_nibble(reinterpret_cast(data), offset); + return bit_cast(rv_mxfp4tof_s(q, sf, 0, nullptr)); + } + case vt::nvfp4::id: + { + uint8_t q = read_nibble(reinterpret_cast(data), offset); + return bit_cast(rv_nvfp4tof_s(q, sf, 0, nullptr)) * tensor_scale; + } + default: + std::abort(); + } +} + +static void matmul_cpu(otype_t *C, + const itype_t *A, + const itype_t *B, + const std::vector &scale_a, + const std::vector &scale_b, + float tensor_scale_a, + float tensor_scale_b, + uint32_t M, + uint32_t N, + uint32_t K_logical) { + uint32_t scale_blocks_k = K_logical / vt::ITYPE::ele_block; + for (uint32_t m = 0; m < M; ++m) { + for (uint32_t n = 0; n < N; ++n) { + float sum = 0.0f; + for (uint32_t k = 0; k < K_logical; ++k) { + uint32_t scale_k = k / vt::ITYPE::ele_block; + auto a = dequantize_mx_value(A, scale_a, m * K_logical + k, + m * scale_blocks_k + scale_k, tensor_scale_a); + auto b = dequantize_mx_value(B, scale_b, n * K_logical + k, + scale_k * N + n, tensor_scale_b); + sum += a * b; + } + C[m * N + n] = sum; + } + } +} + +template +static bool quantize_inputs(typename FormatT::dtype *A, + typename FormatT::dtype *B, + std::vector &scale_a, + std::vector &scale_b, + float &A_tensor_scale, + float &B_tensor_scale, + const float *A_dense, + const float *B_dense, + uint32_t M, + uint32_t N, + uint32_t K_logical) { + if constexpr (std::is_same::value) { + return vt::quantize_mx_a_rowmajor( + reinterpret_cast(A), scale_a, A_tensor_scale, + A_dense, M, K_logical) + && vt::quantize_mx_b_colmajor( + reinterpret_cast(B), scale_b, B_tensor_scale, + B_dense, K_logical, N); + } else { + return vt::quantize_mx_a_rowmajor( + A, scale_a, A_dense, M, K_logical) + && vt::quantize_mx_b_colmajor( + B, scale_b, B_dense, K_logical, N); + } +} + +const char *kernel_file = "kernel.vxbin"; + +uint32_t xm = 32; +uint32_t xn = 32; +uint32_t xk = 32; + +vx_device_h device = nullptr; +vx_queue_h queue = nullptr; +vx_module_h module_ = nullptr; +vx_kernel_h kernel = nullptr; +vx_buffer_h A_buffer = nullptr; +vx_buffer_h B_buffer = nullptr; +vx_buffer_h C_buffer = nullptr; +vx_buffer_h SF_buffer = nullptr; +#ifdef TCU_MX_TLS +vx_buffer_h A_tensor_scale_buffer = nullptr; +vx_buffer_h B_tensor_scale_buffer = nullptr; +#endif +kernel_arg_t kernel_arg = {}; + +static void show_usage() { + std::cout << "Vortex SGEMM TCU TMEM MX Test." << std::endl; + std::cout << "Usage: [-m M] [-n N] [-k K] [-h]" << std::endl; +} + +static void parse_args(int argc, char **argv) { + int c; + while ((c = getopt(argc, argv, "m:n:k:h")) != -1) { + switch (c) { + case 'm': xm = atoi(optarg); break; + case 'n': xn = atoi(optarg); break; + case 'k': xk = atoi(optarg); break; + case 'h': + show_usage(); + exit(0); + default: + show_usage(); + exit(-1); + } + } +} + +void cleanup() { + if (device) { + vx_mem_free(A_buffer); + vx_mem_free(B_buffer); + vx_mem_free(C_buffer); + vx_mem_free(SF_buffer); +#ifdef TCU_MX_TLS + vx_mem_free(A_tensor_scale_buffer); + vx_mem_free(B_tensor_scale_buffer); +#endif + if (kernel) vx_kernel_release(kernel); + if (module_) vx_module_release(module_); + if (queue) vx_queue_release(queue); + vx_dump_perf(device, stdout); + vx_dev_close(device); + } +} + +int main(int argc, char *argv[]) { + parse_args(argc, argv); + std::srand(50); + + RT_CHECK(vx_dev_open(&device)); + vx_queue_info_t qi = {sizeof(qi), nullptr, VX_QUEUE_PRIORITY_NORMAL, 0}; + RT_CHECK(vx_queue_create(device, &qi, &queue)); + + uint64_t isa_flags; + RT_CHECK(vx_dev_caps(device, VX_CAPS_ISA_FLAGS, &isa_flags)); + if ((isa_flags & VX_ISA_EXT_TCU) == 0) { + std::cout << "TCU extension not supported!" << std::endl; + cleanup(); + return -1; + } + + uint64_t NT; + RT_CHECK(vx_dev_caps(device, VX_CAPS_NUM_THREADS, &NT)); + if (NT != VX_CFG_NUM_THREADS) { + std::cout << "Error: device warp size (" << NT << ") must match VX_CFG_NUM_THREADS=" << VX_CFG_NUM_THREADS << "!" << std::endl; + return -1; + } + + uint32_t M = xm; + uint32_t N = xn; + uint32_t K_logical = xk; + uint32_t logical_tileK = cfg::tileK * kElemsPerByte; + uint32_t K_storage = K_logical / kElemsPerByte; + + uint32_t warps_per_cta = VX_CFG_ISSUE_WIDTH; + uint32_t cta_m = warps_per_cta * kTileM; + if ((M % cta_m) != 0 || (N % kTileN) != 0 || (K_logical % logical_tileK) != 0) { + std::cout << "Error: M/N/K must be multiples of CTA M=" << cta_m + << " N=" << kTileN << " K=" << logical_tileK << std::endl; + return -1; + } + if ((K_logical % vt::ITYPE::ele_block) != 0) { + std::cout << "Error: K must be a multiple of MX block size=" << vt::ITYPE::ele_block << std::endl; + return -1; + } + + size_t sizeA = M * K_storage; + size_t sizeB = K_storage * N; + size_t sizeC = M * N; + uint32_t grid_dim[2] = {N / kTileN, M / cta_m}; + uint32_t block_dim[2] = {warps_per_cta * (uint32_t)NT, 1}; + + std::cout << "input data type: " << vt::ITYPE::name << " (id=" << vt::ITYPE::id << ")" << std::endl; + std::cout << "output data type: " << vt::OTYPE::name << " (id=" << vt::OTYPE::id << ")" << std::endl; + std::cout << "MMA Tile Dimension: M=" << kTileM << ", N=" << kTileN + << ", K(logical)=" << logical_tileK << ", K(storage)=" << cfg::tileK << std::endl; + + kernel_arg.M = M; + kernel_arg.N = N; + kernel_arg.K = K_storage; +#ifdef TCU_MX_TLS + kernel_arg.A_tensor_scale_addr = 0; + kernel_arg.B_tensor_scale_addr = 0; +#endif + float A_tensor_scale = 1.0f; + float B_tensor_scale = 1.0f; + + RT_CHECK(vx_mem_alloc(device, sizeA * sizeof(itype_t), VX_MEM_READ, &A_buffer)); + RT_CHECK(vx_mem_address(A_buffer, &kernel_arg.A_addr)); + RT_CHECK(vx_mem_alloc(device, sizeB * sizeof(itype_t), VX_MEM_READ, &B_buffer)); + RT_CHECK(vx_mem_address(B_buffer, &kernel_arg.B_addr)); + RT_CHECK(vx_mem_alloc(device, sizeC * sizeof(otype_t), VX_MEM_WRITE, &C_buffer)); + RT_CHECK(vx_mem_address(C_buffer, &kernel_arg.C_addr)); + + std::vector h_A_dense(M * K_logical); + std::vector h_B_dense(K_logical * N); + for (auto &v : h_A_dense) { + v = (static_cast(std::rand()) / RAND_MAX) * 2.0f - 1.0f; + } + for (auto &v : h_B_dense) { + v = (static_cast(std::rand()) / RAND_MAX) * 2.0f - 1.0f; + } + + std::vector h_A(sizeA); + std::vector h_B(sizeB); + std::vector scale_a; + std::vector scale_b; + + bool ok = quantize_inputs( + h_A.data(), h_B.data(), scale_a, scale_b, A_tensor_scale, B_tensor_scale, + h_A_dense.data(), h_B_dense.data(), M, N, K_logical); + if (!ok) { + std::cout << "Error: MX quantization failed!" << std::endl; + return -1; + } + + // Per K step: one fragment group of A scales, then the B-scale groups. + const uint32_t ksteps = K_storage / (cfg::fedpK * 4); + const uint32_t sf_rows = (kTileN * kSf + NT * 4 - 1) / (NT * 4); + const uint32_t sf_cols = (1 + (sf_rows + VX_CFG_NUM_TCU_BLOCKS - 1) / VX_CFG_NUM_TCU_BLOCKS) * cfg::tcN; + std::vector h_sf; + for (uint32_t by = 0; by < grid_dim[1]; ++by) { + for (uint32_t bx = 0; bx < grid_dim[0]; ++bx) { + auto img = build_sf_image(scale_a, scale_b, by * cta_m, bx * kTileN, cta_m, kTileN, + N, K_logical, sf_cols, ksteps); + kernel_arg.img_words = img.size(); + h_sf.insert(h_sf.end(), img.begin(), img.end()); + } + } + kernel_arg.sf_cols = sf_cols; + RT_CHECK(vx_mem_alloc(device, h_sf.size() * sizeof(uint32_t), VX_MEM_READ, &SF_buffer)); + RT_CHECK(vx_mem_address(SF_buffer, &kernel_arg.SF_addr)); +#ifdef TCU_MX_TLS + if constexpr (std::is_same::value) { + RT_CHECK(vx_mem_alloc(device, sizeof(float), VX_MEM_READ, &A_tensor_scale_buffer)); + RT_CHECK(vx_mem_address(A_tensor_scale_buffer, &kernel_arg.A_tensor_scale_addr)); + RT_CHECK(vx_mem_alloc(device, sizeof(float), VX_MEM_READ, &B_tensor_scale_buffer)); + RT_CHECK(vx_mem_address(B_tensor_scale_buffer, &kernel_arg.B_tensor_scale_addr)); + } +#endif + + RT_CHECK(vx_copy_to_dev(A_buffer, h_A.data(), 0, sizeA * sizeof(itype_t))); + RT_CHECK(vx_copy_to_dev(B_buffer, h_B.data(), 0, sizeB * sizeof(itype_t))); + RT_CHECK(vx_copy_to_dev(SF_buffer, h_sf.data(), 0, h_sf.size() * sizeof(uint32_t))); +#ifdef TCU_MX_TLS + if constexpr (std::is_same::value) { + RT_CHECK(vx_copy_to_dev(A_tensor_scale_buffer, &A_tensor_scale, 0, sizeof(float))); + RT_CHECK(vx_copy_to_dev(B_tensor_scale_buffer, &B_tensor_scale, 0, sizeof(float))); + } +#endif + + RT_CHECK(vx_module_load_file(device, kernel_file, &module_)); + RT_CHECK(vx_module_get_kernel(module_, "main", &kernel)); + + auto time_start = std::chrono::high_resolution_clock::now(); + vx_launch_info_t li = {}; + li.struct_size = sizeof(li); + li.kernel = kernel; + li.args_host = &kernel_arg; + li.args_size = sizeof(kernel_arg); + li.ndim = 2; + li.grid_dim[0] = grid_dim[0]; + li.grid_dim[1] = grid_dim[1]; + li.block_dim[0] = block_dim[0]; + li.block_dim[1] = block_dim[1]; + li.lmem_size = TMEM_SLOT_BYTES + kernel_arg.img_words * sizeof(uint32_t) + + (cta_m + kTileN) * cfg::tileK * sizeof(itype_t); + uint32_t tmem_cols = 32; // the CTA's allocation: a power of two + while (tmem_cols < kTileN + ksteps * sf_cols) tmem_cols <<= 1; + li.tmem_cols = tmem_cols; + + vx_event_h launch_ev = nullptr; + RT_CHECK(vx_enqueue_launch(queue, &li, 0, nullptr, &launch_ev)); + RT_CHECK(vx_event_wait_value(launch_ev, 1, VX_TIMEOUT_INFINITE)); + vx_event_release(launch_ev); + auto time_end = std::chrono::high_resolution_clock::now(); + double elapsed = std::chrono::duration_cast(time_end - time_start).count(); + printf("Elapsed time: %lg ms\n", elapsed); + + std::vector h_C(sizeC); + RT_CHECK(vx_copy_from_dev(h_C.data(), C_buffer, 0, sizeC * sizeof(otype_t))); + + std::vector h_ref(sizeC); + matmul_cpu(h_ref.data(), h_A.data(), h_B.data(), scale_a, scale_b, + A_tensor_scale, B_tensor_scale, M, N, K_logical); + + int errors = 0; + float rel_tol = (std::is_same::value || std::is_same::value) ? 0.25f : 0.05f; + for (uint32_t i = 0; i < h_ref.size(); ++i) { + float actual = static_cast(h_C[i]); + float expected = static_cast(h_ref[i]); + float diff = std::abs(actual - expected); + float tol = std::max(1.0e-3f, std::abs(expected) * rel_tol); + if (!std::isfinite(actual) || !std::isfinite(expected) || !std::isfinite(diff) || diff > tol) { + if (errors < MAX_ERRORS) { + printf("*** error: [%d] expected=%f, actual=%f, diff=%f, tol=%f\n", + i, expected, actual, diff, tol); + } + ++errors; + } + } + + cleanup(); + if (errors != 0) { + std::cout << "Found " << errors << " / " << sizeC << " errors!" << std::endl; + std::cout << "FAILED!" << std::endl; + return errors != 0; + } + + std::cout << "PASSED!" << std::endl; + return 0; +}