src/jit/trace_compiler_cpu.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "trace_compiler.h" | ||
| 2 | #include "trace_dag.h" | ||
| 3 | #include "trace_cache.h" | ||
| 4 | #include "kernel_disk_cache.h" | ||
| 5 | #include <brotensor/trace_autodiff.h> | ||
| 6 | #include "../cpu/cpu_jit.h" | ||
| 7 | #include <brotensor/detail/cpu/thread_pool.h> | ||
| 8 | |||
| 9 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 10 | #include <brass/codegen/kernel_jit.hpp> | ||
| 11 | #include <brass/codegen/trace_builder.hpp> | ||
| 12 | #include <brass/mir/builder.hpp> | ||
| 13 | #include <brass/mir/module.hpp> | ||
| 14 | #include <brass/mir/function.hpp> | ||
| 15 | #include <brass/mir/types.hpp> | ||
| 16 | #endif | ||
| 17 | |||
| 18 | #include <chrono> | ||
| 19 | #include <cmath> | ||
| 20 | #include <string> | ||
| 21 | #include <vector> | ||
| 22 | #include <algorithm> | ||
| 23 | #include <stdexcept> | ||
| 24 | #include <iostream> | ||
| 25 | |||
| 26 | namespace brotensor::jit { | ||
| 27 | |||
| 28 | 47 | FusionPattern TraceCompiler::classify_dag(const TraceDAG& dag) { | |
| 29 | 47 | const auto& nodes = dag.nodes(); | |
| 30 | |||
| 31 | // Check for Fused Residual + RMSNorm: in-place Add followed by RMSNorm consuming it | ||
| 32 | 954 | for (const auto& n : nodes) { | |
| 33 | 908 | if (n.op == TraceOpKind::RMSNorm && !n.inputs.empty()) { | |
| 34 | 4 | int in_id = n.inputs[0]; | |
| 35 | 4 | if (in_id >= 0 && in_id < static_cast<int>(nodes.size())) { | |
| 36 | 4 | const auto& prev = nodes[in_id]; | |
| 37 | 4 | if (prev.op == TraceOpKind::Add && prev.is_inplace) { | |
| 38 | 1 | return FusionPattern::ResidualRMSNorm; | |
| 39 | } | ||
| 40 | 3 | } | |
| 41 | 3 | } | |
| 42 | } | ||
| 43 | |||
| 44 | // Check for Fused LayerNorm + Modulate: LayerNorm followed by Modulate / Affine | ||
| 45 | 932 | for (const auto& n : nodes) { | |
| 46 | 889 | if (n.op == TraceOpKind::LayerNorm) { | |
| 47 | 3 | for (int out_id : n.outputs) { | |
| 48 | 3 | if (out_id >= 0 && out_id < static_cast<int>(nodes.size())) { | |
| 49 | 3 | if (nodes[out_id].op == TraceOpKind::Modulate || nodes[out_id].op == TraceOpKind::Mul) { | |
| 50 | 3 | return FusionPattern::LayerNormModulate; | |
| 51 | } | ||
| 52 | ✗ | } | |
| 53 | } | ||
| 54 | ✗ | } | |
| 55 | } | ||
| 56 | |||
| 57 | 43 | return FusionPattern::Elementwise; | |
| 58 | 47 | } | |
| 59 | |||
| 60 | static CudaTraceCompilerFn s_cuda_trace_compiler_fn = nullptr; | ||
| 61 | |||
| 62 | ✗ | CudaTraceCompilerFn get_cuda_trace_compiler_hook() { | |
| 63 | ✗ | return s_cuda_trace_compiler_fn; | |
| 64 | } | ||
| 65 | |||
| 66 | ✗ | void register_cuda_trace_compiler(CudaTraceCompilerFn fn) { | |
| 67 | ✗ | s_cuda_trace_compiler_fn = fn; | |
| 68 | ✗ | } | |
| 69 | |||
| 70 | static VulkanTraceCompilerFn s_vulkan_trace_compiler_fn = nullptr; | ||
| 71 | |||
| 72 | ✗ | VulkanTraceCompilerFn get_vulkan_trace_compiler_hook() { | |
| 73 | ✗ | return s_vulkan_trace_compiler_fn; | |
| 74 | } | ||
| 75 | |||
| 76 | ✗ | void register_vulkan_trace_compiler(VulkanTraceCompilerFn fn) { | |
| 77 | ✗ | s_vulkan_trace_compiler_fn = fn; | |
| 78 | ✗ | } | |
| 79 | |||
| 80 | static MetalTraceCompilerFn s_metal_trace_compiler_fn = nullptr; | ||
| 81 | |||
| 82 | 7 | MetalTraceCompilerFn get_metal_trace_compiler_hook() { | |
| 83 | 7 | return s_metal_trace_compiler_fn; | |
| 84 | } | ||
| 85 | |||
| 86 | 380 | void register_metal_trace_compiler(MetalTraceCompilerFn fn) { | |
| 87 | 380 | s_metal_trace_compiler_fn = fn; | |
| 88 | 380 | } | |
| 89 | |||
| 90 | 53 | TraceHandle TraceCompiler::compile_and_cache(const TraceDAG& raw_dag) { | |
| 91 | 53 | bool has_ext_ops = false; | |
| 92 | 1042 | for (const auto& n : raw_dag.nodes()) { | |
| 93 | 1978 | if (n.op == TraceOpKind::Const || n.op == TraceOpKind::Neg || | |
| 94 | 989 | n.op == TraceOpKind::Abs || n.op == TraceOpKind::Exp || | |
| 95 | 989 | n.op == TraceOpKind::Log || n.op == TraceOpKind::Sqrt || | |
| 96 | 989 | n.op == TraceOpKind::Rsqrt) { | |
| 97 | ✗ | has_ext_ops = true; | |
| 98 | ✗ | break; | |
| 99 | } | ||
| 100 | } | ||
| 101 | 53 | TraceDAG lowered_holder; | |
| 102 | 53 | if (has_ext_ops) { | |
| 103 | ✗ | lowered_holder = canonicalize_trace_dag_for_codegen(raw_dag); | |
| 104 | ✗ | } | |
| 105 | 53 | const TraceDAG& dag = has_ext_ops ? lowered_holder : raw_dag; | |
| 106 | 53 | uint64_t hash = dag.compute_hash(); | |
| 107 | |||
| 108 | // Check trace cache for previously compiled kernel | ||
| 109 | 53 | auto cached = TraceCache::instance().lookup(hash); | |
| 110 | 53 | if (cached && cached->rebind_fn) { | |
| 111 | 6 | std::vector<void*> input_ptrs; | |
| 112 | 6 | std::vector<void*> output_ptrs; | |
| 113 | 87 | for (const auto& node : dag.nodes()) { | |
| 114 | 81 | if (node.op == TraceOpKind::Input) { | |
| 115 | 13 | input_ptrs.push_back(node.buffer); | |
| 116 | 13 | } | |
| 117 | 81 | if (node.is_live_at_end) { | |
| 118 | 6 | output_ptrs.push_back(node.buffer); | |
| 119 | 6 | } | |
| 120 | } | ||
| 121 | 6 | auto re_bound = cached->rebind_fn(input_ptrs, output_ptrs); | |
| 122 | 6 | re_bound->signature_hash = hash; | |
| 123 | 6 | re_bound->is_cache_hit = true; | |
| 124 | 6 | re_bound->node_count = dag.node_count(); | |
| 125 | 6 | re_bound->execute(); | |
| 126 | 6 | return TraceHandle(re_bound); | |
| 127 | 6 | } | |
| 128 | |||
| 129 | 47 | FusionPattern pattern = classify_dag(dag); | |
| 130 | |||
| 131 | // Which compiler gets the DAG. CUDA has the PTX compiler and Vulkan the | ||
| 132 | // SPIR-V one (brass MIR); a Vulkan DAG must never reach the CPU compiler | ||
| 133 | // (host code over device addresses, unordered against the device | ||
| 134 | // stream), so what the Vulkan compiler cannot fuse is replayed op by op | ||
| 135 | // instead. Everything else is the CPU compiler's. | ||
| 136 | 47 | bool is_cuda = false; | |
| 137 | 47 | bool is_vulkan = false; | |
| 138 | 47 | bool is_metal = false; | |
| 139 | 955 | for (const auto& n : dag.nodes()) { | |
| 140 | 908 | if (n.device.is_cuda()) is_cuda = true; | |
| 141 | 908 | if (n.device.is_vulkan()) is_vulkan = true; | |
| 142 | 908 | if (n.device.is_metal()) is_metal = true; | |
| 143 | } | ||
| 144 | |||
| 145 | 47 | const auto compile_t0 = std::chrono::steady_clock::now(); | |
| 146 | 47 | std::shared_ptr<TraceHandleImpl> handle; | |
| 147 | 47 | if (is_cuda) { | |
| 148 | ✗ | auto cuda_fn = get_cuda_trace_compiler_hook(); | |
| 149 | ✗ | if (!cuda_fn) { | |
| 150 | ✗ | throw std::runtime_error("brotensor::jit: CUDA JIT compiler hook is not registered or CUDA is unavailable"); | |
| 151 | } | ||
| 152 | ✗ | handle = cuda_fn(dag, pattern); | |
| 153 | 47 | } else if (is_vulkan) { | |
| 154 | ✗ | if (auto vk_fn = get_vulkan_trace_compiler_hook()) handle = vk_fn(dag, pattern); | |
| 155 | ✗ | if (!handle) handle = eager::compile_eager(dag); | |
| 156 | 47 | } else if (is_metal) { | |
| 157 | 7 | if (auto mtl_fn = get_metal_trace_compiler_hook()) handle = mtl_fn(dag, pattern); | |
| 158 | 7 | if (!handle) handle = eager::compile_eager(dag); | |
| 159 | 7 | } else { | |
| 160 | 40 | handle = cpu::compile_cpu(dag, pattern); | |
| 161 | } | ||
| 162 | |||
| 163 | 47 | handle->signature_hash = hash; | |
| 164 | 47 | handle->is_cuda = is_cuda; | |
| 165 | 47 | handle->node_count = dag.node_count(); | |
| 166 | 47 | handle->is_cache_hit = false; | |
| 167 | // The CUDA, Vulkan, and Metal compilers name their own fusion and time their | ||
| 168 | // own builds, the eager replay counts its own launches; the CPU path is | ||
| 169 | // always one fused call through brass's host codegen. | ||
| 170 | 47 | if (handle->launch_count == 0) handle->launch_count = 1; | |
| 171 | 47 | if (!is_cuda && !is_vulkan && !is_metal) { | |
| 172 | 40 | if (handle->fusion_name == nullptr || handle->fusion_name[0] == '\0') { | |
| 173 | ✗ | handle->fusion_name = "cpu-avx2-fused"; | |
| 174 | ✗ | } | |
| 175 | 80 | handle->compile_us = std::chrono::duration<double, std::micro>( | |
| 176 | 40 | std::chrono::steady_clock::now() - compile_t0).count(); | |
| 177 | 40 | } | |
| 178 | |||
| 179 | 47 | TraceCache::instance().insert(hash, handle); | |
| 180 | |||
| 181 | // Initial execution to populate outputs | ||
| 182 | 47 | handle->execute(); | |
| 183 | |||
| 184 | 47 | return TraceHandle(handle); | |
| 185 | 53 | } | |
| 186 | |||
| 187 | 27 | TraceHandle end_trace() { | |
| 188 | 27 | TraceDAG dag = TraceContext::current().end(); | |
| 189 | 27 | return TraceCompiler::compile_and_cache(dag); | |
| 190 | 27 | } | |
| 191 | |||
| 192 | namespace cpu { | ||
| 193 | |||
| 194 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 195 | |||
| 196 | using ElementwiseFn = void (*)(float* const* out_ptrs, const float* const* in_ptrs, int64_t n); | ||
| 197 | |||
| 198 | // What the host codegen below can actually be handed. | ||
| 199 | // | ||
| 200 | // It walks every operand as a flat run of `total_numel` FP32 values. A (1, D) | ||
| 201 | // broadcast row or a half-precision buffer would be read past the end of its | ||
| 202 | // allocation — a crash, or worse, silently wrong numbers — so anything that is | ||
| 203 | // not the trace's full shape in FP32 is refused here. end_trace() then throws | ||
| 204 | // and the caller falls back to its eager path, which is the contract the CUDA | ||
| 205 | // compiler already follows for expressions it cannot fuse. | ||
| 206 | 34 | static void require_cpu_fusable(const TraceDAG& dag) { | |
| 207 | 34 | int rows = 0, cols = 0; | |
| 208 | 34 | dag.dominant_shape(rows, cols); | |
| 209 | 34 | const int64_t dom_numel = static_cast<int64_t>(rows) * cols; | |
| 210 | 864 | for (const TraceNode& n : dag.nodes()) { | |
| 211 | 830 | if (n.dtype != Dtype::FP32) { | |
| 212 | ✗ | throw std::runtime_error( | |
| 213 | "brotensor::jit: the CPU trace compiler is FP32 only"); | ||
| 214 | } | ||
| 215 | 830 | const BroadcastKind bk = broadcast_of(n.rows, n.cols, rows, cols); | |
| 216 | 830 | const int64_t numel = static_cast<int64_t>(n.rows) * n.cols; | |
| 217 | 830 | if (bk == BroadcastKind::Full && numel != dom_numel) { | |
| 218 | ✗ | throw std::runtime_error( | |
| 219 | ✗ | "brotensor::jit: operand shape (" + std::to_string(n.rows) + ", " + | |
| 220 | ✗ | std::to_string(n.cols) + ") cannot broadcast to dominant shape (" + | |
| 221 | ✗ | std::to_string(rows) + ", " + std::to_string(cols) + ")"); | |
| 222 | } | ||
| 223 | 830 | if (n.is_live_at_end && bk != BroadcastKind::Full) { | |
| 224 | ✗ | throw std::runtime_error( | |
| 225 | "brotensor::jit: a traced output must have the trace's full (rows, cols) shape"); | ||
| 226 | } | ||
| 227 | } | ||
| 228 | 34 | } | |
| 229 | |||
| 230 | // The emitted code dereferences every buffer on the host. CUDA device | ||
| 231 | // pointers and Vulkan buffer device addresses are not host addresses (and | ||
| 232 | // even where one happened to be readable, the host code would be unordered | ||
| 233 | // against the device stream that produces its inputs). Metal storage is | ||
| 234 | // MTLResourceStorageModeShared, whose contents pointer is a host address. | ||
| 235 | 40 | static void require_host_addressable(const TraceDAG& dag) { | |
| 236 | 909 | for (const TraceNode& n : dag.nodes()) { | |
| 237 | 869 | if (n.device.is_cuda() || n.device.is_vulkan() || n.device.is_metal()) { | |
| 238 | ✗ | throw std::runtime_error( | |
| 239 | ✗ | "brotensor::jit: the CPU trace compiler was handed a " + | |
| 240 | ✗ | to_string(n.device) + " tensor; it only runs host-addressable memory"); | |
| 241 | } | ||
| 242 | } | ||
| 243 | 40 | } | |
| 244 | |||
| 245 | 34 | static std::shared_ptr<TraceHandleImpl> compile_cpu_elementwise(const TraceDAG& dag) { | |
| 246 | 34 | require_cpu_fusable(dag); | |
| 247 | 34 | const auto& nodes = dag.nodes(); | |
| 248 | |||
| 249 | 34 | int dom_rows = 0, dom_cols = 0; | |
| 250 | 34 | dag.dominant_shape(dom_rows, dom_cols); | |
| 251 | |||
| 252 | 34 | std::vector<int> input_node_ids; | |
| 253 | 34 | std::vector<BroadcastKind> input_bcast; | |
| 254 | 34 | std::vector<int> output_node_ids; | |
| 255 | 34 | std::unordered_map<int, int> node_to_in_idx; | |
| 256 | 34 | std::unordered_map<int, int> node_to_out_idx; | |
| 257 | |||
| 258 | 34 | bool any_bcast = false; | |
| 259 | 34 | bool any_row_bcast = false; | |
| 260 | 34 | bool any_col_bcast = false; | |
| 261 | 34 | bool has_where = false; | |
| 262 | |||
| 263 | 864 | for (const auto& n : nodes) { | |
| 264 | 830 | if (n.op == TraceOpKind::Input) { | |
| 265 | 117 | node_to_in_idx[n.id] = static_cast<int>(input_node_ids.size()); | |
| 266 | 117 | input_node_ids.push_back(n.id); | |
| 267 | 117 | const BroadcastKind bk = broadcast_of(n.rows, n.cols, dom_rows, dom_cols); | |
| 268 | 117 | input_bcast.push_back(bk); | |
| 269 | 117 | if (bk != BroadcastKind::Full) any_bcast = true; | |
| 270 | 117 | if (bk == BroadcastKind::Row) any_row_bcast = true; | |
| 271 | 117 | if (bk == BroadcastKind::Col) any_col_bcast = true; | |
| 272 | 117 | } | |
| 273 | 830 | if (n.op == TraceOpKind::Where) { | |
| 274 | 29 | has_where = true; | |
| 275 | 29 | } | |
| 276 | 830 | if (n.is_live_at_end) { | |
| 277 | 47 | node_to_out_idx[n.id] = static_cast<int>(output_node_ids.size()); | |
| 278 | 47 | output_node_ids.push_back(n.id); | |
| 279 | 47 | } | |
| 280 | } | ||
| 281 | |||
| 282 | 34 | const int64_t total_numel = static_cast<int64_t>(dom_rows) * static_cast<int64_t>(dom_cols); | |
| 283 | 34 | const bool use_vec_loop = !any_row_bcast && !any_col_bcast && !has_where; | |
| 284 | |||
| 285 | using namespace brass; | ||
| 286 | using namespace brass::codegen; | ||
| 287 | |||
| 288 | 65 | auto build_fn = [&](Module& mod) { | |
| 289 | 124 | Function* fn = mod.create_function("trace_elementwise_kernel", Type::void_type(), { | |
| 290 | 31 | Type::ptr(), // float* const* out_ptrs | |
| 291 | 31 | Type::ptr(), // const float* const* in_ptrs | |
| 292 | 31 | Type::i64() // int64_t n | |
| 293 | }); | ||
| 294 | |||
| 295 | 31 | TraceBuilder tb(mod, fn); | |
| 296 | |||
| 297 | 31 | BasicBlock* entry = tb.builder().append_block("entry"); | |
| 298 | 31 | Value* p_out_ptrs = tb.builder().add_block_param(entry, Type::ptr()); | |
| 299 | 31 | Value* p_in_ptrs = tb.builder().add_block_param(entry, Type::ptr()); | |
| 300 | 31 | Value* n_val = tb.builder().add_block_param(entry, Type::i64()); | |
| 301 | |||
| 302 | 31 | BasicBlock* shead = tb.builder().create_block("shead"); | |
| 303 | 31 | BasicBlock* sbody = tb.builder().create_block("sbody"); | |
| 304 | 31 | BasicBlock* exit_bb = tb.builder().create_block("exit"); | |
| 305 | |||
| 306 | 31 | tb.position_at_end(entry); | |
| 307 | |||
| 308 | // Load input and output base pointers into local SSA values | ||
| 309 | 31 | std::vector<Value*> in_ptrs_val; | |
| 310 | 142 | for (size_t k = 0; k < input_node_ids.size(); ++k) { | |
| 311 | 111 | Value* p = tb.builder().build_load(Type::ptr(), p_in_ptrs, static_cast<int32_t>(k * 8)); | |
| 312 | 111 | in_ptrs_val.push_back(p); | |
| 313 | 111 | } | |
| 314 | 31 | std::vector<Value*> out_ptrs_val; | |
| 315 | 75 | for (size_t m = 0; m < output_node_ids.size(); ++m) { | |
| 316 | 44 | Value* p = tb.builder().build_load(Type::ptr(), p_out_ptrs, static_cast<int32_t>(m * 8)); | |
| 317 | 44 | out_ptrs_val.push_back(p); | |
| 318 | 44 | } | |
| 319 | |||
| 320 | 31 | Value* zero_i64 = tb.builder().build_iconst_i64(0); | |
| 321 | 31 | Value* one_i64 = tb.builder().build_iconst_i64(1); | |
| 322 | |||
| 323 | 31 | if (use_vec_loop) { | |
| 324 | 15 | BasicBlock* vhead = tb.builder().create_block("vhead"); | |
| 325 | 15 | BasicBlock* vbody = tb.builder().create_block("vbody"); | |
| 326 | |||
| 327 | 15 | Value* two_i64 = tb.builder().build_iconst_i64(2); | |
| 328 | 15 | Value* eight_i64 = tb.builder().build_iconst_i64(8); | |
| 329 | 15 | Value* mask_eight = tb.builder().build_iconst_i64(~int64_t(7)); | |
| 330 | 15 | Value* vec_n = tb.builder().build_and(n_val, mask_eight); | |
| 331 | 15 | Value* has_vec = tb.builder().build_sge(n_val, eight_i64); | |
| 332 | |||
| 333 | 15 | tb.builder().build_br_if(has_vec, vhead, {zero_i64}, shead, {zero_i64}); | |
| 334 | |||
| 335 | // ── Vector AVX2 Loop (8-wide) ───────────────────────────────────────── | ||
| 336 | 15 | fn->append_block(vhead); | |
| 337 | 15 | Value* iv_v = tb.builder().add_block_param(vhead, Type::i64()); | |
| 338 | 15 | tb.position_at_end(vhead); | |
| 339 | 15 | Value* cond_v = tb.builder().build_slt(iv_v, vec_n); | |
| 340 | 15 | tb.builder().build_br_if(cond_v, vbody, {}, shead, {iv_v}); | |
| 341 | |||
| 342 | 15 | fn->append_block(vbody); | |
| 343 | 15 | tb.position_at_end(vbody); | |
| 344 | 15 | Value* byte_off_v = tb.builder().build_shl(iv_v, two_i64); | |
| 345 | |||
| 346 | 15 | std::unordered_map<int, Value*> v_node_vals; | |
| 347 | 67 | for (size_t k = 0; k < input_node_ids.size(); ++k) { | |
| 348 | 52 | int nid = input_node_ids[k]; | |
| 349 | 52 | if (input_bcast[k] == BroadcastKind::Scalar) { | |
| 350 | 1 | Value* sv = tb.load_f32(in_ptrs_val[k], 0); | |
| 351 | 1 | v_node_vals[nid] = tb.vbroadcast(Type::f32x8(), sv); | |
| 352 | 1 | } else { | |
| 353 | 51 | Value* addr = tb.builder().build_add(in_ptrs_val[k], byte_off_v); | |
| 354 | 51 | v_node_vals[nid] = tb.vload_f32x8(addr); | |
| 355 | } | ||
| 356 | 52 | } | |
| 357 | |||
| 358 | 182 | for (const auto& n : nodes) { | |
| 359 | 167 | if (n.op == TraceOpKind::Input) continue; | |
| 360 | |||
| 361 | 115 | Value* res = nullptr; | |
| 362 | 115 | if (n.op == TraceOpKind::Add) { | |
| 363 | 14 | res = tb.vadd(v_node_vals[n.inputs[0]], v_node_vals[n.inputs[1]]); | |
| 364 | 115 | } else if (n.op == TraceOpKind::Sub) { | |
| 365 | 1 | res = tb.vsub(v_node_vals[n.inputs[0]], v_node_vals[n.inputs[1]]); | |
| 366 | 101 | } else if (n.op == TraceOpKind::Mul) { | |
| 367 | 44 | res = tb.vmul(v_node_vals[n.inputs[0]], v_node_vals[n.inputs[1]]); | |
| 368 | 100 | } else if (n.op == TraceOpKind::Div) { | |
| 369 | ✗ | res = tb.vdiv(v_node_vals[n.inputs[0]], v_node_vals[n.inputs[1]]); | |
| 370 | 56 | } else if (n.op == TraceOpKind::AddScalar) { | |
| 371 | 6 | Value* c = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(n.scalar)); | |
| 372 | 6 | res = tb.vadd(v_node_vals[n.inputs[0]], c); | |
| 373 | 56 | } else if (n.op == TraceOpKind::SubScalar) { | |
| 374 | ✗ | Value* c = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(n.scalar)); | |
| 375 | ✗ | res = tb.vsub(v_node_vals[n.inputs[0]], c); | |
| 376 | 50 | } else if (n.op == TraceOpKind::MulScalar) { | |
| 377 | 11 | Value* c = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(n.scalar)); | |
| 378 | 11 | res = tb.vmul(v_node_vals[n.inputs[0]], c); | |
| 379 | 50 | } else if (n.op == TraceOpKind::DivScalar) { | |
| 380 | ✗ | Value* c = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(n.scalar)); | |
| 381 | ✗ | res = tb.vdiv(v_node_vals[n.inputs[0]], c); | |
| 382 | 39 | } else if (n.op == TraceOpKind::ScalarSub) { | |
| 383 | 6 | Value* c = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(n.scalar)); | |
| 384 | 6 | res = tb.vsub(c, v_node_vals[n.inputs[0]]); | |
| 385 | 39 | } else if (n.op == TraceOpKind::ScalarDiv) { | |
| 386 | ✗ | Value* c = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(n.scalar)); | |
| 387 | ✗ | res = tb.vdiv(c, v_node_vals[n.inputs[0]]); | |
| 388 | 33 | } else if (n.op == TraceOpKind::FMA) { | |
| 389 | ✗ | res = tb.vfma(v_node_vals[n.inputs[0]], v_node_vals[n.inputs[1]], v_node_vals[n.inputs[2]]); | |
| 390 | 33 | } else if (n.op == TraceOpKind::Modulate) { | |
| 391 | ✗ | Value* c1 = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(1.0f)); | |
| 392 | ✗ | res = tb.vfma(v_node_vals[n.inputs[0]], tb.vadd(v_node_vals[n.inputs[1]], c1), v_node_vals[n.inputs[2]]); | |
| 393 | 33 | } else if (n.op == TraceOpKind::Clamp) { | |
| 394 | ✗ | Value* lo_v = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(n.scalar)); | |
| 395 | ✗ | Value* hi_v = tb.vbroadcast(Type::f32x8(), tb.builder().build_fconst_f32(n.scalar2)); | |
| 396 | ✗ | res = tb.vmin(tb.vmax(v_node_vals[n.inputs[0]], lo_v), hi_v); | |
| 397 | 33 | } else if (n.op == TraceOpKind::SiLU) { | |
| 398 | 10 | res = tb.vsilu_f32x8(v_node_vals[n.inputs[0]]); | |
| 399 | 33 | } else if (n.op == TraceOpKind::GELU) { | |
| 400 | 1 | res = tb.vgelu_f32x8(v_node_vals[n.inputs[0]]); | |
| 401 | 23 | } else if (n.op == TraceOpKind::ReLU) { | |
| 402 | 1 | res = tb.vmax(v_node_vals[n.inputs[0]], tb.vzero(Type::f32x8())); | |
| 403 | 22 | } else if (n.op == TraceOpKind::Tanh) { | |
| 404 | 4 | res = tb.vtanh_f32x8(v_node_vals[n.inputs[0]]); | |
| 405 | 21 | } else if (n.op == TraceOpKind::Sigmoid) { | |
| 406 | 4 | res = tb.vsigmoid_f32x8(v_node_vals[n.inputs[0]]); | |
| 407 | 17 | } else if (n.op == TraceOpKind::Copy || n.op == TraceOpKind::Cast) { | |
| 408 | 13 | res = v_node_vals[n.inputs[0]]; | |
| 409 | 13 | } else { | |
| 410 | ✗ | throw std::runtime_error( | |
| 411 | ✗ | std::string("brotensor::jit: op '") + op_kind_name(n.op) + | |
| 412 | "' has no CPU elementwise form"); | ||
| 413 | } | ||
| 414 | 115 | v_node_vals[n.id] = res; | |
| 415 | |||
| 416 | 115 | if (n.is_live_at_end) { | |
| 417 | 20 | int out_idx = node_to_out_idx[n.id]; | |
| 418 | 20 | Value* addr = tb.builder().build_add(out_ptrs_val[out_idx], byte_off_v); | |
| 419 | 20 | tb.vstore_f32x8(addr, res); | |
| 420 | 20 | } | |
| 421 | } | ||
| 422 | |||
| 423 | 15 | Value* next_iv_v = tb.builder().build_add(iv_v, eight_i64); | |
| 424 | 15 | tb.builder().build_br(vhead, {next_iv_v}); | |
| 425 | 15 | } else { | |
| 426 | 16 | tb.builder().build_br(shead, {zero_i64}); | |
| 427 | } | ||
| 428 | |||
| 429 | // ── Scalar Loop ────────────────────────────────────────────────────────── | ||
| 430 | 31 | fn->append_block(shead); | |
| 431 | 31 | Value* iv_s = tb.builder().add_block_param(shead, Type::i64()); | |
| 432 | 31 | tb.position_at_end(shead); | |
| 433 | 31 | Value* cond_s = tb.builder().build_slt(iv_s, n_val); | |
| 434 | 31 | tb.builder().build_br_if(cond_s, sbody, {}, exit_bb, {}); | |
| 435 | |||
| 436 | 31 | fn->append_block(sbody); | |
| 437 | 31 | tb.position_at_end(sbody); | |
| 438 | |||
| 439 | 43 | Value* cols_i64 = (any_row_bcast || any_col_bcast) | |
| 440 | 12 | ? tb.builder().build_iconst_i64(dom_cols) | |
| 441 | : nullptr; | ||
| 442 | 31 | Value* col_s = any_row_bcast ? tb.builder().build_umod(iv_s, cols_i64) : nullptr; | |
| 443 | 31 | Value* row_s = any_col_bcast ? tb.builder().build_udiv(iv_s, cols_i64) : nullptr; | |
| 444 | |||
| 445 | 31 | std::unordered_map<int, Value*> s_node_vals; | |
| 446 | 142 | for (size_t k = 0; k < input_node_ids.size(); ++k) { | |
| 447 | 111 | int nid = input_node_ids[k]; | |
| 448 | 111 | if (input_bcast[k] == BroadcastKind::Scalar) { | |
| 449 | 2 | s_node_vals[nid] = tb.load_f32(in_ptrs_val[k], 0); | |
| 450 | 111 | } else if (input_bcast[k] == BroadcastKind::Row) { | |
| 451 | 14 | s_node_vals[nid] = tb.load_f32_indexed(in_ptrs_val[k], col_s, 4, 0); | |
| 452 | 109 | } else if (input_bcast[k] == BroadcastKind::Col) { | |
| 453 | 16 | s_node_vals[nid] = tb.load_f32_indexed(in_ptrs_val[k], row_s, 4, 0); | |
| 454 | 16 | } else { | |
| 455 | 79 | s_node_vals[nid] = tb.load_f32_indexed(in_ptrs_val[k], iv_s, 4, 0); | |
| 456 | } | ||
| 457 | 111 | } | |
| 458 | |||
| 459 | 849 | for (const auto& n : nodes) { | |
| 460 | 818 | if (n.op == TraceOpKind::Input) continue; | |
| 461 | |||
| 462 | 707 | Value* res = nullptr; | |
| 463 | 707 | if (n.op == TraceOpKind::Add) { | |
| 464 | 86 | res = tb.add(s_node_vals[n.inputs[0]], s_node_vals[n.inputs[1]]); | |
| 465 | 707 | } else if (n.op == TraceOpKind::Sub) { | |
| 466 | 8 | res = tb.sub(s_node_vals[n.inputs[0]], s_node_vals[n.inputs[1]]); | |
| 467 | 621 | } else if (n.op == TraceOpKind::Mul) { | |
| 468 | 120 | res = tb.mul(s_node_vals[n.inputs[0]], s_node_vals[n.inputs[1]]); | |
| 469 | 613 | } else if (n.op == TraceOpKind::Div) { | |
| 470 | 56 | res = tb.div(s_node_vals[n.inputs[0]], s_node_vals[n.inputs[1]]); | |
| 471 | 493 | } else if (n.op == TraceOpKind::AddScalar) { | |
| 472 | 106 | Value* c = tb.builder().build_fconst_f32(n.scalar); | |
| 473 | 106 | res = tb.add(s_node_vals[n.inputs[0]], c); | |
| 474 | 437 | } else if (n.op == TraceOpKind::SubScalar) { | |
| 475 | 7 | Value* c = tb.builder().build_fconst_f32(n.scalar); | |
| 476 | 7 | res = tb.sub(s_node_vals[n.inputs[0]], c); | |
| 477 | 331 | } else if (n.op == TraceOpKind::MulScalar) { | |
| 478 | 108 | Value* c = tb.builder().build_fconst_f32(n.scalar); | |
| 479 | 108 | res = tb.mul(s_node_vals[n.inputs[0]], c); | |
| 480 | 324 | } else if (n.op == TraceOpKind::DivScalar) { | |
| 481 | ✗ | Value* c = tb.builder().build_fconst_f32(n.scalar); | |
| 482 | ✗ | res = tb.div(s_node_vals[n.inputs[0]], c); | |
| 483 | 216 | } else if (n.op == TraceOpKind::ScalarSub) { | |
| 484 | 23 | Value* c = tb.builder().build_fconst_f32(n.scalar); | |
| 485 | 23 | res = tb.sub(c, s_node_vals[n.inputs[0]]); | |
| 486 | 216 | } else if (n.op == TraceOpKind::ScalarDiv) { | |
| 487 | ✗ | Value* c = tb.builder().build_fconst_f32(n.scalar); | |
| 488 | ✗ | res = tb.div(c, s_node_vals[n.inputs[0]]); | |
| 489 | 193 | } else if (n.op == TraceOpKind::FMA) { | |
| 490 | ✗ | res = tb.fma(s_node_vals[n.inputs[0]], s_node_vals[n.inputs[1]], s_node_vals[n.inputs[2]]); | |
| 491 | 193 | } else if (n.op == TraceOpKind::Modulate) { | |
| 492 | ✗ | Value* c1 = tb.builder().build_fconst_f32(1.0f); | |
| 493 | ✗ | res = tb.fma(s_node_vals[n.inputs[0]], tb.add(s_node_vals[n.inputs[1]], c1), s_node_vals[n.inputs[2]]); | |
| 494 | 193 | } else if (n.op == TraceOpKind::Clamp) { | |
| 495 | 7 | Value* lo_c = tb.builder().build_fconst_f32(n.scalar); | |
| 496 | 7 | Value* hi_c = tb.builder().build_fconst_f32(n.scalar2); | |
| 497 | 14 | res = tb.builder().build_fmin_f32( | |
| 498 | 7 | tb.builder().build_fmax_f32(s_node_vals[n.inputs[0]], lo_c), hi_c); | |
| 499 | 193 | } else if (n.op == TraceOpKind::Where) { | |
| 500 | 29 | Value* c_bits = tb.builder().build_bitcast_i32_f32(s_node_vals[n.inputs[0]]); | |
| 501 | 29 | Value* mag_bits = tb.builder().build_and(c_bits, tb.builder().build_iconst_i32(0x7FFFFFFF)); | |
| 502 | 29 | Value* nz = tb.builder().build_ne(mag_bits, tb.builder().build_iconst_i32(0)); | |
| 503 | 29 | res = tb.builder().build_select(nz, s_node_vals[n.inputs[1]], s_node_vals[n.inputs[2]]); | |
| 504 | 186 | } else if (n.op == TraceOpKind::SiLU) { | |
| 505 | 11 | res = tb.silu_f32(s_node_vals[n.inputs[0]]); | |
| 506 | 157 | } else if (n.op == TraceOpKind::GELU) { | |
| 507 | 1 | res = tb.gelu_f32(s_node_vals[n.inputs[0]]); | |
| 508 | 146 | } else if (n.op == TraceOpKind::ReLU) { | |
| 509 | 103 | res = tb.builder().build_fmax_f32(s_node_vals[n.inputs[0]], tb.builder().build_fconst_f32(0.0f)); | |
| 510 | 145 | } else if (n.op == TraceOpKind::Tanh) { | |
| 511 | 8 | res = tb.tanh_f32(s_node_vals[n.inputs[0]]); | |
| 512 | 42 | } else if (n.op == TraceOpKind::Sigmoid) { | |
| 513 | 8 | res = tb.sigmoid_f32(s_node_vals[n.inputs[0]]); | |
| 514 | 34 | } else if (n.op == TraceOpKind::Copy || n.op == TraceOpKind::Cast) { | |
| 515 | 26 | res = s_node_vals[n.inputs[0]]; | |
| 516 | 26 | } else { | |
| 517 | ✗ | throw std::runtime_error( | |
| 518 | ✗ | std::string("brotensor::jit: op '") + op_kind_name(n.op) + | |
| 519 | "' has no CPU elementwise form"); | ||
| 520 | } | ||
| 521 | 707 | s_node_vals[n.id] = res; | |
| 522 | |||
| 523 | 707 | if (n.is_live_at_end) { | |
| 524 | 44 | int out_idx = node_to_out_idx[n.id]; | |
| 525 | 44 | tb.store_f32_indexed(out_ptrs_val[out_idx], iv_s, res, 4, 0); | |
| 526 | 44 | } | |
| 527 | } | ||
| 528 | |||
| 529 | 31 | Value* next_iv_s = tb.builder().build_add(iv_s, one_i64); | |
| 530 | 31 | tb.builder().build_br(shead, {next_iv_s}); | |
| 531 | |||
| 532 | 31 | fn->append_block(exit_bb); | |
| 533 | 31 | tb.position_at_end(exit_bb); | |
| 534 | 31 | tb.builder().build_ret_void(); | |
| 535 | 31 | }; | |
| 536 | |||
| 537 | // The whole DAG, not its 64-bit digest: a digest collision on disk would | ||
| 538 | // be another trace's kernel. | ||
| 539 | 34 | const std::string sig_key = "cpu_trace_ew/" + dag.key_material(); | |
| 540 | 34 | KernelDiskCache::CpuCompileOptions c_opts; | |
| 541 | 34 | c_opts.enable_unroll = false; | |
| 542 | 34 | c_opts.enable_fp_reassociation = false; | |
| 543 | |||
| 544 | 68 | auto kernel_ptr = KernelDiskCache::instance().compile_or_load_cpu_fn<ElementwiseFn>( | |
| 545 | 34 | sig_key, "trace_elementwise_kernel", build_fn, c_opts); | |
| 546 | 34 | if (!kernel_ptr) { | |
| 547 | ✗ | throw std::runtime_error("brotensor::jit: Failed to JIT compile CPU elementwise trace kernel"); | |
| 548 | } | ||
| 549 | |||
| 550 | 107 | auto make_bound_handle = [kernel_ptr, total_numel, any_bcast, input_node_ids, output_node_ids] | |
| 551 | (const std::vector<void*>& in_buffers, const std::vector<void*>& out_buffers) { | ||
| 552 | 39 | auto h = std::make_shared<TraceHandleImpl>(); | |
| 553 | |||
| 554 | 39 | std::vector<const float*> in_f(in_buffers.size()); | |
| 555 | 164 | for (size_t k = 0; k < in_buffers.size(); ++k) in_f[k] = static_cast<const float*>(in_buffers[k]); | |
| 556 | 39 | std::vector<float*> out_f(out_buffers.size()); | |
| 557 | 91 | for (size_t m = 0; m < out_buffers.size(); ++m) out_f[m] = static_cast<float*>(out_buffers[m]); | |
| 558 | |||
| 559 | 630 | h->execute_fn = [kernel_ptr, total_numel, any_bcast, in_f, out_f]() { | |
| 560 | 591 | if (!any_bcast && total_numel >= 262144) { | |
| 561 | 2 | auto& pool = detail::cpu::ThreadPool::instance(); | |
| 562 | 2 | int n_threads = pool.num_threads(); | |
| 563 | 2 | int64_t chunk = (total_numel + n_threads - 1) / n_threads; | |
| 564 | 2 | chunk = (chunk + 7) & ~int64_t(7); // Align to 8-wide AVX2 | |
| 565 | |||
| 566 | 8 | detail::cpu::parallel_for(n_threads, [&](std::size_t tid_sz) { | |
| 567 | 6 | int64_t tid = static_cast<int64_t>(tid_sz); | |
| 568 | 6 | int64_t start = tid * chunk; | |
| 569 | 6 | if (start >= total_numel) return; | |
| 570 | 6 | int64_t count = std::min(chunk, total_numel - start); | |
| 571 | |||
| 572 | 6 | std::vector<const float*> chunk_in(in_f.size()); | |
| 573 | 18 | for (size_t k = 0; k < in_f.size(); ++k) { | |
| 574 | 12 | chunk_in[k] = in_f[k] + start; | |
| 575 | 12 | } | |
| 576 | 6 | std::vector<float*> chunk_out(out_f.size()); | |
| 577 | 12 | for (size_t m = 0; m < out_f.size(); ++m) { | |
| 578 | 6 | chunk_out[m] = out_f[m] + start; | |
| 579 | 6 | } | |
| 580 | 6 | kernel_ptr(chunk_out.data(), chunk_in.data(), count); | |
| 581 | 6 | }); | |
| 582 | 2 | } else { | |
| 583 | 589 | kernel_ptr(out_f.data(), in_f.data(), total_numel); | |
| 584 | } | ||
| 585 | 591 | }; | |
| 586 | 39 | return h; | |
| 587 | 39 | }; | |
| 588 | |||
| 589 | 34 | std::vector<void*> initial_in_buffers; | |
| 590 | 151 | for (int nid : input_node_ids) initial_in_buffers.push_back(nodes[nid].buffer); | |
| 591 | 34 | std::vector<void*> initial_out_buffers; | |
| 592 | 81 | for (int nid : output_node_ids) initial_out_buffers.push_back(nodes[nid].buffer); | |
| 593 | |||
| 594 | 34 | auto handle = make_bound_handle(initial_in_buffers, initial_out_buffers); | |
| 595 | 39 | handle->rebind_fn = [make_bound_handle](const std::vector<void*>& in_b, const std::vector<void*>& out_b) { | |
| 596 | 5 | return make_bound_handle(in_b, out_b); | |
| 597 | }; | ||
| 598 | |||
| 599 | 34 | return handle; | |
| 600 | 34 | } | |
| 601 | |||
| 602 | 40 | std::shared_ptr<TraceHandleImpl> compile_cpu(const TraceDAG& dag, FusionPattern pattern) { | |
| 603 | 40 | const auto& nodes = dag.nodes(); | |
| 604 | 40 | require_host_addressable(dag); | |
| 605 | |||
| 606 | 906 | for (const auto& n : nodes) { | |
| 607 | 868 | if (n.dtype != Dtype::FP32) { | |
| 608 | 2 | return eager::compile_eager(dag); | |
| 609 | } | ||
| 610 | } | ||
| 611 | |||
| 612 | 50 | auto in_idx_of = [&nodes](int node_id) -> int { | |
| 613 | 12 | int idx = 0; | |
| 614 | 46 | for (const auto& n : nodes) { | |
| 615 | 46 | if (n.op == TraceOpKind::Input) { | |
| 616 | 35 | if (n.id == node_id) return idx; | |
| 617 | 23 | ++idx; | |
| 618 | 23 | } | |
| 619 | } | ||
| 620 | ✗ | return -1; | |
| 621 | 12 | }; | |
| 622 | 42 | auto out_idx_of = [&nodes](int node_id) -> int { | |
| 623 | 4 | int idx = 0; | |
| 624 | 26 | for (const auto& n : nodes) { | |
| 625 | 26 | if (n.is_live_at_end) { | |
| 626 | 5 | if (n.id == node_id) return idx; | |
| 627 | 1 | ++idx; | |
| 628 | 1 | } | |
| 629 | } | ||
| 630 | ✗ | return -1; | |
| 631 | 4 | }; | |
| 632 | |||
| 633 | 38 | if (pattern == FusionPattern::ResidualRMSNorm && nodes.size() == 5) { | |
| 634 | 1 | const TraceNode* node_rms = nullptr; | |
| 635 | 1 | const TraceNode* node_add = nullptr; | |
| 636 | 1 | const TraceNode* node_res = nullptr; | |
| 637 | 1 | const TraceNode* node_gamma = nullptr; | |
| 638 | |||
| 639 | 5 | for (const auto& n : nodes) { | |
| 640 | 5 | if (n.op != TraceOpKind::RMSNorm || n.inputs.empty()) continue; | |
| 641 | 1 | const TraceNode& add = nodes[n.inputs[0]]; | |
| 642 | // The hand kernel below is exactly `x += res; rms_norm(x, gamma)`. | ||
| 643 | // Anything else — no residual, no gain, or downstream ops — is not | ||
| 644 | // this pattern. | ||
| 645 | 1 | if (add.op != TraceOpKind::Add || !add.is_inplace || add.inputs.size() < 2) continue; | |
| 646 | 1 | if (n.inputs.size() < 2 || !n.outputs.empty() || !n.is_live_at_end || !add.is_live_at_end) continue; | |
| 647 | 2 | if (nodes[add.inputs[0]].op != TraceOpKind::Input || | |
| 648 | 1 | nodes[add.inputs[1]].op != TraceOpKind::Input || | |
| 649 | 1 | nodes[n.inputs[1]].op != TraceOpKind::Input) continue; | |
| 650 | 1 | node_rms = &n; | |
| 651 | 1 | node_add = &add; | |
| 652 | 1 | node_res = &nodes[add.inputs[1]]; | |
| 653 | 1 | node_gamma = &nodes[n.inputs[1]]; | |
| 654 | 1 | break; | |
| 655 | } | ||
| 656 | |||
| 657 | 1 | if (node_rms && node_add && node_res && node_gamma) { | |
| 658 | 1 | int B = node_add->rows; | |
| 659 | 1 | int D = node_add->cols; | |
| 660 | 1 | float eps = node_rms->scalar > 0.0f ? node_rms->scalar : 1e-5f; | |
| 661 | |||
| 662 | 2 | auto make_handle = [B, D, eps](void* x_buf, const void* res_buf, const void* gamma_buf, void* y_buf) { | |
| 663 | 1 | auto h = std::make_shared<TraceHandleImpl>(); | |
| 664 | 3 | h->execute_fn = [x_buf, res_buf, gamma_buf, y_buf, B, D, eps]() { | |
| 665 | 2 | detail::cpu::jit::fused_residual_rmsnorm( | |
| 666 | 2 | static_cast<float*>(x_buf), | |
| 667 | 2 | static_cast<const float*>(res_buf), | |
| 668 | 2 | static_cast<const float*>(gamma_buf), | |
| 669 | 2 | eps, | |
| 670 | 2 | static_cast<float*>(y_buf), | |
| 671 | 2 | B, D | |
| 672 | ); | ||
| 673 | 2 | }; | |
| 674 | 1 | return h; | |
| 675 | 1 | }; | |
| 676 | |||
| 677 | 1 | void* x_buf = node_add->buffer; | |
| 678 | 1 | const void* res_buf = node_res->buffer; | |
| 679 | 1 | const void* gamma_buf = node_gamma->buffer; | |
| 680 | 1 | void* y_buf = node_rms->buffer; | |
| 681 | |||
| 682 | 1 | const int in_res = in_idx_of(node_res->id); | |
| 683 | 1 | const int in_gamma = in_idx_of(node_gamma->id); | |
| 684 | 1 | const int out_x = out_idx_of(node_add->id); | |
| 685 | 1 | const int out_y = out_idx_of(node_rms->id); | |
| 686 | |||
| 687 | 1 | auto handle = make_handle(x_buf, res_buf, gamma_buf, y_buf); | |
| 688 | 1 | handle->rebind_fn = [make_handle, in_res, in_gamma, out_x, out_y]( | |
| 689 | const std::vector<void*>& in_b, const std::vector<void*>& out_b) { | ||
| 690 | ✗ | const void* res_p = (in_res >= 0 && static_cast<size_t>(in_res) < in_b.size()) ? in_b[in_res] : nullptr; | |
| 691 | ✗ | const void* gamma_p = (in_gamma >= 0 && static_cast<size_t>(in_gamma) < in_b.size()) ? in_b[in_gamma] : nullptr; | |
| 692 | ✗ | void* x_p = (out_x >= 0 && static_cast<size_t>(out_x) < out_b.size()) ? out_b[out_x] : nullptr; | |
| 693 | ✗ | void* y_p = (out_y >= 0 && static_cast<size_t>(out_y) < out_b.size()) ? out_b[out_y] : nullptr; | |
| 694 | ✗ | return make_handle(x_p, res_p, gamma_p, y_p); | |
| 695 | }; | ||
| 696 | 1 | return handle; | |
| 697 | 1 | } | |
| 698 | 37 | } else if (pattern == FusionPattern::LayerNormModulate) { | |
| 699 | 3 | const TraceNode* node_ln = nullptr; | |
| 700 | 3 | const TraceNode* node_x = nullptr; | |
| 701 | 3 | const TraceNode* node_gamma = nullptr; | |
| 702 | 3 | const TraceNode* node_beta = nullptr; | |
| 703 | 3 | const TraceNode* node_scale = nullptr; | |
| 704 | 3 | const TraceNode* node_shift = nullptr; | |
| 705 | 3 | const TraceNode* node_out = nullptr; | |
| 706 | |||
| 707 | 31 | for (const auto& n : nodes) { | |
| 708 | 28 | if (n.op == TraceOpKind::LayerNorm && !n.is_live_at_end && n.outputs.size() == 1 && n.inputs.size() >= 3) { | |
| 709 | 6 | if (nodes[n.inputs[0]].op == TraceOpKind::Input && | |
| 710 | 3 | nodes[n.inputs[1]].op == TraceOpKind::Input && | |
| 711 | 3 | nodes[n.inputs[2]].op == TraceOpKind::Input) { | |
| 712 | 3 | node_ln = &n; | |
| 713 | 3 | node_x = &nodes[n.inputs[0]]; | |
| 714 | 3 | node_gamma = &nodes[n.inputs[1]]; | |
| 715 | 3 | node_beta = &nodes[n.inputs[2]]; | |
| 716 | 3 | } | |
| 717 | 3 | } | |
| 718 | } | ||
| 719 | |||
| 720 | 3 | if (node_ln && nodes.size() == 7) { | |
| 721 | ✗ | const TraceNode& mod = nodes[node_ln->outputs[0]]; | |
| 722 | ✗ | if (mod.op == TraceOpKind::Modulate && mod.is_live_at_end && mod.outputs.empty() && | |
| 723 | ✗ | mod.inputs.size() >= 3 && mod.inputs[0] == node_ln->id && | |
| 724 | ✗ | nodes[mod.inputs[1]].op == TraceOpKind::Input && | |
| 725 | ✗ | nodes[mod.inputs[2]].op == TraceOpKind::Input) { | |
| 726 | ✗ | node_scale = &nodes[mod.inputs[1]]; | |
| 727 | ✗ | node_shift = &nodes[mod.inputs[2]]; | |
| 728 | ✗ | node_out = &mod; | |
| 729 | ✗ | } | |
| 730 | 3 | } else if (node_ln && nodes.size() == 9) { | |
| 731 | 2 | const TraceNode& mul = nodes[node_ln->outputs[0]]; | |
| 732 | 2 | if (mul.op == TraceOpKind::Mul && !mul.is_live_at_end && mul.outputs.size() == 1 && mul.inputs.size() == 2) { | |
| 733 | 2 | int other_mul_in = (mul.inputs[0] == node_ln->id) ? mul.inputs[1] : mul.inputs[0]; | |
| 734 | 2 | const TraceNode& add_sc = nodes[other_mul_in]; | |
| 735 | 2 | const TraceNode& add_sh = nodes[mul.outputs[0]]; | |
| 736 | 4 | if (add_sc.op == TraceOpKind::AddScalar && !add_sc.is_live_at_end && | |
| 737 | 2 | add_sc.scalar == 1.0f && add_sc.inputs.size() == 1 && | |
| 738 | 2 | nodes[add_sc.inputs[0]].op == TraceOpKind::Input && | |
| 739 | 2 | add_sh.op == TraceOpKind::Add && add_sh.is_live_at_end && | |
| 740 | 2 | add_sh.outputs.empty() && add_sh.inputs.size() == 2) { | |
| 741 | 2 | int shift_in = (add_sh.inputs[0] == mul.id) ? add_sh.inputs[1] : add_sh.inputs[0]; | |
| 742 | 2 | if (nodes[shift_in].op == TraceOpKind::Input) { | |
| 743 | 2 | node_scale = &nodes[add_sc.inputs[0]]; | |
| 744 | 2 | node_shift = &nodes[shift_in]; | |
| 745 | 2 | node_out = &add_sh; | |
| 746 | 2 | } | |
| 747 | 2 | } | |
| 748 | 2 | } | |
| 749 | 2 | } | |
| 750 | |||
| 751 | // The hand kernel dereferences all five operands, so a trace missing | ||
| 752 | // any of them (a non-affine LayerNorm, a modulate with no shift) is | ||
| 753 | // not this pattern and falls through to the generic path. | ||
| 754 | 3 | if (node_ln && node_x && node_out && node_gamma && node_beta && node_scale && node_shift) { | |
| 755 | 2 | int R = node_ln->rows; | |
| 756 | 2 | int D = node_ln->cols; | |
| 757 | 2 | float eps = node_ln->scalar > 0.0f ? node_ln->scalar : 1e-5f; | |
| 758 | |||
| 759 | 5 | auto make_handle = [R, D, eps](const void* x, const void* g, const void* b, | |
| 760 | const void* scale, const void* shift, void* y) { | ||
| 761 | 3 | auto h = std::make_shared<TraceHandleImpl>(); | |
| 762 | 7 | h->execute_fn = [x, g, b, scale, shift, y, R, D, eps]() { | |
| 763 | 4 | detail::cpu::jit::fused_layernorm_modulate( | |
| 764 | 4 | static_cast<const float*>(x), | |
| 765 | 4 | static_cast<const float*>(g), | |
| 766 | 4 | static_cast<const float*>(b), | |
| 767 | 4 | static_cast<const float*>(scale), | |
| 768 | 4 | static_cast<const float*>(shift), | |
| 769 | 4 | eps, | |
| 770 | 4 | static_cast<float*>(y), | |
| 771 | 4 | R, D | |
| 772 | ); | ||
| 773 | 4 | }; | |
| 774 | 3 | return h; | |
| 775 | 3 | }; | |
| 776 | |||
| 777 | 2 | const void* x_buf = node_x->buffer; | |
| 778 | 2 | const void* g_buf = node_gamma->buffer; | |
| 779 | 2 | const void* b_buf = node_beta->buffer; | |
| 780 | 2 | const void* s_buf = node_scale->buffer; | |
| 781 | 2 | const void* sh_buf = node_shift->buffer; | |
| 782 | 2 | void* y_buf = node_out->buffer; | |
| 783 | |||
| 784 | 2 | const int in_x = in_idx_of(node_x->id); | |
| 785 | 2 | const int in_g = in_idx_of(node_gamma->id); | |
| 786 | 2 | const int in_b_idx = in_idx_of(node_beta->id); | |
| 787 | 2 | const int in_s = in_idx_of(node_scale->id); | |
| 788 | 2 | const int in_sh = in_idx_of(node_shift->id); | |
| 789 | 2 | const int out_y = out_idx_of(node_out->id); | |
| 790 | |||
| 791 | 2 | auto handle = make_handle(x_buf, g_buf, b_buf, s_buf, sh_buf, y_buf); | |
| 792 | 3 | handle->rebind_fn = [make_handle, in_x, in_g, in_b_idx, in_s, in_sh, out_y]( | |
| 793 | const std::vector<void*>& in_b, const std::vector<void*>& out_b) { | ||
| 794 | 1 | const void* x = (in_x >= 0 && static_cast<size_t>(in_x) < in_b.size()) ? in_b[in_x] : nullptr; | |
| 795 | 1 | const void* g = (in_g >= 0 && static_cast<size_t>(in_g) < in_b.size()) ? in_b[in_g] : nullptr; | |
| 796 | 1 | const void* b = (in_b_idx >= 0 && static_cast<size_t>(in_b_idx) < in_b.size()) ? in_b[in_b_idx] : nullptr; | |
| 797 | 1 | const void* sc = (in_s >= 0 && static_cast<size_t>(in_s) < in_b.size()) ? in_b[in_s] : nullptr; | |
| 798 | 1 | const void* sh = (in_sh >= 0 && static_cast<size_t>(in_sh) < in_b.size()) ? in_b[in_sh] : nullptr; | |
| 799 | 1 | void* y = (out_y >= 0 && static_cast<size_t>(out_y) < out_b.size()) ? out_b[out_y] : nullptr; | |
| 800 | 1 | return make_handle(x, g, b, sc, sh, y); | |
| 801 | }; | ||
| 802 | 2 | return handle; | |
| 803 | 2 | } | |
| 804 | 1 | } | |
| 805 | |||
| 806 | 868 | for (const auto& n : nodes) { | |
| 807 | 834 | if (n.op == TraceOpKind::RMSNorm || n.op == TraceOpKind::LayerNorm) { | |
| 808 | 1 | return eager::compile_eager(dag); | |
| 809 | } | ||
| 810 | } | ||
| 811 | |||
| 812 | 34 | return compile_cpu_elementwise(dag); | |
| 813 | 40 | } | |
| 814 | |||
| 815 | #else // !BROTENSOR_HAS_BRASS_JIT | ||
| 816 | |||
| 817 | std::shared_ptr<TraceHandleImpl> compile_cpu(const TraceDAG& /*dag*/, FusionPattern /*pattern*/) { | ||
| 818 | throw std::runtime_error("brotensor::jit: Brass CPU JIT compiler is not enabled in this build"); | ||
| 819 | } | ||
| 820 | |||
| 821 | #endif // BROTENSOR_HAS_BRASS_JIT | ||
| 822 | |||
| 823 | } // namespace cpu | ||
| 824 | } // namespace brotensor::jit | ||
| 825 |