From 8bebb1119b9607b840a196eba4b26bff6b83a163 Mon Sep 17 00:00:00 2001 From: Digant Desai Date: Sat, 21 Nov 2026 20:42:56 -0800 Subject: [PATCH] Update [ghstack-poisoned] --- .../native/runtime/engine/ggml/GgmlEngine.h | 4 + .../runtime/engine/ggml/GgmlEngineFlags.cpp | 7 + .../runtime/engine/ggml/GgmlExecutor.cpp | 227 +++++++++++++++++- .../runtime/engine/ggml/GgmlGraphBuilder.cpp | 47 +++- .../runtime/engine/ggml/GgmlGraphBuilder.h | 16 ++ .../test/runtime/ggml/test_ggml_engine.cpp | 73 +++++- .../native/test/runtime/ggml/test_ggml_ops.py | 109 ++++++++- 7 files changed, 457 insertions(+), 26 deletions(-) diff --git a/backends/native/runtime/engine/ggml/GgmlEngine.h b/backends/native/runtime/engine/ggml/GgmlEngine.h index fb419b6df2b..09acffadcaf 100644 --- a/backends/native/runtime/engine/ggml/GgmlEngine.h +++ b/backends/native/runtime/engine/ggml/GgmlEngine.h @@ -98,6 +98,10 @@ struct GgmlEngineOptions { // read by scaled_dot_product_attention and the custom SDPA; CUDA and HIP // only. bool f32_gpu_kv_cache_for_testing = false; + // Default (true): nodes that read only unquantized constants are computed + // once, when the executable is compiled, and every call reads their + // results. False (testing only): they are computed on every call. + bool fold_constants = true; }; class GgmlEngineContext; diff --git a/backends/native/runtime/engine/ggml/GgmlEngineFlags.cpp b/backends/native/runtime/engine/ggml/GgmlEngineFlags.cpp index 8b30a3dc2eb..cf05baabd61 100644 --- a/backends/native/runtime/engine/ggml/GgmlEngineFlags.cpp +++ b/backends/native/runtime/engine/ggml/GgmlEngineFlags.cpp @@ -44,6 +44,12 @@ DEFINE_bool( "in F16 on CUDA, as in llama.cpp. Set: they accumulate in F32, at 2-3x " "prefill and 4x decode GEMM time. Ops: F16 linear, matmul, mm, bmm and " "convolution; CUDA only."); +DEFINE_bool( + fold_constants, + true, + "Default: nodes that read only unquantized constants are computed once, " + "at compile, and every call reads their results. False (testing only): " + "they are computed on every call."); namespace ptn { // cppcheck-suppress unusedFunction ; called by the ggml runners @@ -66,6 +72,7 @@ GgmlEngineOptions ggml_engine_options_from_flags() { options.exact_gelu_for_testing = FLAGS_exact_gelu_for_testing; options.cuda_f32_accumulation_for_testing = FLAGS_cuda_f32_accumulation_for_testing; + options.fold_constants = FLAGS_fold_constants; return options; } diff --git a/backends/native/runtime/engine/ggml/GgmlExecutor.cpp b/backends/native/runtime/engine/ggml/GgmlExecutor.cpp index 02e4a312119..a8e4b84d043 100644 --- a/backends/native/runtime/engine/ggml/GgmlExecutor.cpp +++ b/backends/native/runtime/engine/ggml/GgmlExecutor.cpp @@ -147,6 +147,7 @@ class GgmlExecutable final : public EngineExecutable { index_rope_frequencies(); index_mask_extents(); index_offgraph_attention(); + fold_constants(materialized_constant_bytes); if (heap_copied_constant_bytes != nullptr) { *heap_copied_constant_bytes += heap_copied_constant_bytes_; } @@ -1461,6 +1462,192 @@ class GgmlExecutable final : public EngineExecutable { } } + // Ops that compute a pure function of their tensor arguments, which the + // executable may run once when all of those are constants. + static bool is_foldable_op(const std::string& key) { + static const std::unordered_set kOps = { + "aten._to_copy.default", "aten._unsafe_view.default", + "aten.abs.default", "aten.add.Tensor", + "aten.alias.default", "aten.clamp.default", + "aten.clone.default", "aten.contiguous.default", + "aten.cos.default", "aten.div.Tensor", + "aten.exp.default", "aten.expand.default", + "aten.expand_copy.default", "aten.hardtanh.default", + "aten.log.default", "aten.mul.Tensor", + "aten.neg.default", "aten.permute.default", + "aten.permute_copy.default", "aten.relu.default", + "aten.reshape.default", "aten.select.int", + "aten.select_copy.int", "aten.sigmoid.default", + "aten.silu.default", "aten.sin.default", + "aten.slice.Tensor", "aten.slice_copy.Tensor", + "aten.sqrt.default", "aten.squeeze.dims", + "aten.squeeze_copy.dims", "aten.sub.Tensor", + "aten.tanh.default", "aten.transpose_copy.int", + "aten.unsqueeze.default", "aten.unsqueeze_copy.default", + "aten.view.default", "aten.view_copy.default", + }; + return kOps.contains(key); + } + + // Unquantized constants no method writes: packed and int4 weights stay as + // they are for mul_mat, and state may change between calls. + std::unordered_set immutable_constants() const { + std::unordered_set constants; + for (const DataBinding& binding : method_.data_bindings) { + if (persistent_.contains(binding.value_id) && !binding.mutated && + constant_binding(binding.value_id) != nullptr && + !method_.graph.value(binding.value_id).tensor_meta().quant) { + constants.insert(binding.value_id); + } + } + return constants; + } + + // Whether `node` computes a float result no larger than its inputs (or + // small), from `constants` alone, with static arguments, writing nothing. + bool is_foldable( + const Node& node, + const std::unordered_set& constants, + const std::unordered_set& excluded) const { + constexpr size_t kSmallResultBytes = size_t{1} << 20; + const std::vector outputs = output_ids(node); + if (!node.is_call() || !is_foldable_op(op_key(node.target)) || + outputs.size() != 1 || excluded.contains(outputs.front())) { + return false; + } + const TensorMeta& meta = method_.graph.value(outputs.front()).tensor_meta(); + if ((meta.dtype != ScalarType::Float && meta.dtype != ScalarType::Half && + meta.dtype != ScalarType::BFloat16) || + !meta.lower_bounds.empty() || checked_numel(meta.sizes) == 0) { + return false; + } + size_t input_bytes = 0; + for (const NamedArgument& input : node.inputs) { + const Argument& arg = input.arg; + const bool symbolic = + (arg.kind() == ArgKind::Int && valid(arg.as_int().id)) || + (arg.kind() == ArgKind::Float && valid(arg.as_float().id)) || + (arg.kind() == ArgKind::Bool && valid(arg.as_bool().id)) || + (arg.kind() == ArgKind::IntList && + std::ranges::any_of(arg.as_int_list().ids, valid)); + if (input.mutated || symbolic || arg.kind() == ArgKind::TensorList || + arg.kind() == ArgKind::OptionalTensorList || + arg.kind() == ArgKind::Graph) { + return false; + } + if (arg.kind() == ArgKind::Tensor) { + const ValueId id = arg.as_tensor().id; + if (!constants.contains(id)) { + return false; + } + const TensorMeta& source = method_.graph.value(id).tensor_meta(); + input_bytes += checked_nbytes(source.sizes, source.dtype); + } + } + const size_t bytes = checked_nbytes(meta.sizes, meta.dtype); + const auto writes_result = [&](NodeId consumer) { + return std::ranges::any_of( + method_.graph.node(consumer).inputs, [&](const NamedArgument& in) { + return in.mutated && in.arg.kind() == ArgKind::Tensor && + in.arg.as_tensor().id == outputs.front(); + }); + }; + return input_bytes > 0 && + (bytes <= input_bytes || bytes <= kSmallResultBytes) && + std::ranges::none_of( + method_.graph.value(outputs.front()).consumer_ids, + writes_result); + } + + // Computes once the nodes that read only immutable constants (directly or + // through other such nodes), in their own lowering, so every call's graph + // reads the same bits it would have computed. Results that other nodes read + // join the persistent tensors; graph outputs and attention-mask chains, + // whose lowering depends on the call, are left alone. + void fold_constants(size_t* materialized_constant_bytes) { + if (!options_.fold_constants) { + return; + } + std::unordered_set constants = immutable_constants(); + std::unordered_set excluded( + method_.graph.output_ids.begin(), method_.graph.output_ids.end()); + for (const MaskExtent& mask : mask_extents_) { + excluded.insert(mask.chain.begin(), mask.chain.end()); + } + std::vector nodes; + std::unordered_set folded; + for (const NodeId id : method_.graph.schedule) { + const Node& node = method_.graph.node(id); + if (is_foldable(node, constants, excluded)) { + nodes.push_back(id); + folded.insert(id); + constants.insert(output_ids(node).front()); + } + } + std::vector results; + for (const NodeId id : nodes) { + const ValueId result = output_ids(method_.graph.node(id)).front(); + if (std::ranges::any_of( + method_.graph.value(result).consumer_ids, + [&](NodeId consumer) { return !folded.contains(consumer); })) { + results.push_back(result); + } + } + if (results.empty()) { + return; + } + FoldGraph fold = graph_builder({}).build_folds(nodes, results); + if (fold.values.empty()) { + return; + } + ggml_backend_sched_ptr scheduler = + make_scheduler(scheduler_size(fold.instance)); + if (!ggml_backend_sched_alloc_graph(scheduler.get(), fold.instance.graph) || + ggml_backend_sched_graph_compute( + scheduler.get(), fold.instance.graph) != GGML_STATUS_SUCCESS) { + throw std::runtime_error("ggml: failed to compute constant results"); + } + ggml_init_params params{ + .mem_size = ggml_tensor_overhead() * fold.values.size(), + .mem_buffer = nullptr, + .no_alloc = true, + }; + fold_context_.reset(ggml_init(params)); + if (!fold_context_) { + throw std::runtime_error( + "ggml: failed to create constant result context"); + } + std::vector tensors; + for (size_t i = 0; i < fold.values.size(); ++i) { + const TensorRef& result = fold.instance.outputs[i]; + tensors.push_back( + new_tensor(fold_context_.get(), result.tensor->type, result.sizes)); + ggml_set_name( + tensors.back(), method_.graph.value(fold.values[i]).name.c_str()); + } + fold_buffer_.reset( + ggml_backend_alloc_ctx_tensors(fold_context_.get(), primary_backend_)); + if (!fold_buffer_) { + throw std::runtime_error("ggml: failed to allocate constant results"); + } + size_t loaded = 0; + std::vector bytes; + for (size_t i = 0; i < fold.values.size(); ++i) { + bytes.resize(ggml_nbytes(tensors[i])); + ggml_backend_tensor_get( + fold.instance.outputs[i].tensor, bytes.data(), 0, bytes.size()); + ggml_backend_tensor_set(tensors[i], bytes.data(), 0, bytes.size()); + persistent_.emplace(fold.values[i], tensors[i]); + loaded += bytes.size(); + } + ggml_backend_sched_synchronize(scheduler.get()); + ggml_backend_buffer_set_usage( + fold_buffer_.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS); + if (materialized_constant_bytes != nullptr) { + *materialized_constant_bytes += loaded; + } + } + void index_rope_frequencies() { for (const NodeId id : method_.graph.schedule) { const Node& node = method_.graph.node(id); @@ -1544,6 +1731,9 @@ class GgmlExecutable final : public EngineExecutable { "ggml: unsupported output dtype conversion to Float"); } + GraphBuilder graph_builder( + std::unordered_map truncated, + const OffGraphCacheBinding* offgraph_cache = nullptr); GraphInstance build_graph(const std::vector& key_extents); static std::optional static_dim(const TensorMeta& meta, size_t i) { @@ -2155,8 +2345,31 @@ class GgmlExecutable final : public EngineExecutable { FoldedBatchNorms batch_norms_; ggml_context_ptr batch_norm_context_; ggml_backend_buffer_ptr batch_norm_buffer_; + // Results computed once from constants (fold_constants). + ggml_context_ptr fold_context_; + ggml_backend_buffer_ptr fold_buffer_; }; +GraphBuilder GgmlExecutable::graph_builder( + std::unordered_map truncated, + const OffGraphCacheBinding* offgraph_cache) { + return GraphBuilder( + method_, + inputs_, + outputs_, + persistent_, + row_scales_, + rope_freq_factors_, + batch_norms_, + std::move(truncated), + options_.graph_size, + options_.device == GgmlDevice::Gpu, + options_.exact_topk_for_testing, + options_.exact_gelu_for_testing, + f32_accumulation_, + offgraph_cache); +} + GraphInstance GgmlExecutable::build_graph( const std::vector& key_extents) { std::unordered_map truncated; @@ -2172,20 +2385,8 @@ GraphInstance GgmlExecutable::build_graph( offgraph_cache.keys = key_extents.back(); } GraphInstance instance = - GraphBuilder( - method_, - inputs_, - outputs_, - persistent_, - row_scales_, - rope_freq_factors_, - batch_norms_, + graph_builder( std::move(truncated), - options_.graph_size, - options_.device == GgmlDevice::Gpu, - options_.exact_topk_for_testing, - options_.exact_gelu_for_testing, - f32_accumulation_, valid(offgraph_position_) ? &offgraph_cache : nullptr) .build(); // Boundability without a per-run check: shapes are part of a graph's key, diff --git a/backends/native/runtime/engine/ggml/GgmlGraphBuilder.cpp b/backends/native/runtime/engine/ggml/GgmlGraphBuilder.cpp index d4b0f4b0c64..5a9d4b8e1fd 100644 --- a/backends/native/runtime/engine/ggml/GgmlGraphBuilder.cpp +++ b/backends/native/runtime/engine/ggml/GgmlGraphBuilder.cpp @@ -308,7 +308,7 @@ size_t graph_capacity(const Method& method, size_t graph_size) { return std::max(graph_size, metadata_budget(method)); } -GraphInstance GraphBuilder::build() { +void GraphBuilder::begin() { const size_t capacity = graph_capacity(method_, graph_size_); ggml_init_params params{ .mem_size = ggml_tensor_overhead() * metadata_budget(method_) + @@ -325,12 +325,15 @@ GraphInstance GraphBuilder::build() { if (instance_.graph == nullptr) { throw std::runtime_error("ggml: failed to create cgraph"); } +} +GraphInstance GraphBuilder::build() { + begin(); seed_values(); index_written_values(); for (const NodeId id : method_.graph.schedule) { const Node& node = method_.graph.node(id); - if (node.is_call()) { + if (node.is_call() && !folded(node)) { copy_required_ = touches_written_value(node); lower(node); } @@ -370,6 +373,46 @@ GraphInstance GraphBuilder::build() { return std::move(instance_); } +// Whether the executable computed `node`'s results once from constants and +// holds them as persistent tensors. +bool GraphBuilder::folded(const Node& node) const { + const std::vector outputs = output_ids(node); + return !outputs.empty() && + std::ranges::all_of(outputs, [this](ValueId output) { + return persistent_.contains(output); + }); +} + +FoldGraph GraphBuilder::build_folds( + const std::vector& nodes, + const std::vector& values) { + begin(); + seed_values(); + index_written_values(); + for (const NodeId id : nodes) { + lower(method_.graph.node(id)); + } + FoldGraph fold; + for (const ValueId id : values) { + TensorRef value = view(id); + const ggml_tensor* source = value.tensor; + while (source->op == GGML_OP_VIEW || source->op == GGML_OP_RESHAPE || + source->op == GGML_OP_PERMUTE || source->op == GGML_OP_TRANSPOSE) { + source = source->src[0]; + } + if (source->op == GGML_OP_NONE) { + continue; + } + value.tensor = contiguous(value.tensor); + ggml_set_output(value.tensor); + ggml_build_forward_expand(instance_.graph, value.tensor); + instance_.outputs.push_back(std::move(value)); + fold.values.push_back(id); + } + fold.instance = std::move(instance_); + return fold; +} + // Outputs leave through a byte copy, so they must be contiguous and of the // declared type. int64 is widened on the host. ggml_tensor* GraphBuilder::as_output( diff --git a/backends/native/runtime/engine/ggml/GgmlGraphBuilder.h b/backends/native/runtime/engine/ggml/GgmlGraphBuilder.h index fea709b3443..65b0d4835e8 100644 --- a/backends/native/runtime/engine/ggml/GgmlGraphBuilder.h +++ b/backends/native/runtime/engine/ggml/GgmlGraphBuilder.h @@ -142,6 +142,13 @@ struct GraphInstance { std::vector host_integer_checks; }; +// Results of nodes that read only constants, computed once: `instance` outputs +// `values` in order. +struct FoldGraph { + GraphInstance instance; + std::vector values; +}; + // Inference batch norm is the per-channel map x * scale + shift of its // constants, computed once at load. A convolution read only by the batch norm // absorbs it: its weight is scaled at load and its bias replaced, leaving the @@ -224,7 +231,16 @@ class GraphBuilder { GraphInstance build(); + // A graph of `nodes` alone, which read only persistent tensors, whose + // outputs are those of `values` that compute something; a value that only + // views a persistent tensor costs nothing per call and is left out. + FoldGraph build_folds( + const std::vector& nodes, + const std::vector& values); + private: + void begin(); + bool folded(const Node& node) const; ggml_tensor* as_output(ggml_tensor* result, const TensorMeta& meta); void expand_write(ggml_tensor* write); ggml_tensor* write_back(ValueId value_id, ValueId target_id); diff --git a/backends/native/test/runtime/ggml/test_ggml_engine.cpp b/backends/native/test/runtime/ggml/test_ggml_engine.cpp index e1b9c6084b3..db7b366c97f 100644 --- a/backends/native/test/runtime/ggml/test_ggml_engine.cpp +++ b/backends/native/test/runtime/ggml/test_ggml_engine.cpp @@ -375,12 +375,13 @@ class TestProgram { } // A parameter whose data is the package's constant `name`, packed with - // `packed_codec` if given. + // `packed_codec` if given; a buffer the graph writes if `mutated`. void constant( const std::string& name, fbs::ScalarType dtype, const std::vector& shape, - const char* packed_codec = nullptr) { + const char* packed_codec = nullptr, + bool mutated = false) { const auto quant = packed_codec == nullptr ? flatbuffers::Offset() : fbs::CreateQuantSpec( @@ -390,7 +391,12 @@ class TestProgram { const auto meta = create_tensor_meta(builder_, dtype, shape, quant); placeholder(name, meta); bindings_.push_back(fbs::CreateNamedTensorRefDirect( - builder_, name.c_str(), name.c_str(), meta, fbs::InputKind::PARAMETER)); + builder_, + name.c_str(), + name.c_str(), + meta, + mutated ? fbs::InputKind::BUFFER : fbs::InputKind::PARAMETER, + mutated)); } // Symmetric int4 AffineGroup weights `weight` with float scales @@ -4421,6 +4427,67 @@ TEST(GgmlEngineTest, IndexRefusesInnerDimsAndSeveralIndexTensors) { } } +// exp(bias) reads only a constant and is computed once; exp(state) reads a +// buffer each call writes, so it sees each call's state. +TEST(GgmlEngineTest, FoldsConstantsButNotWrittenBuffers) { + TestProgram program; + program.input("x", fbs::ScalarType::FLOAT, {4}); + program.constant( + "state", fbs::ScalarType::FLOAT, {4}, nullptr, /*mutated=*/true); + program.constant("bias", fbs::ScalarType::FLOAT, {4}); + const auto exp = [&](const char* name, const char* source) { + program.call( + name, + "torch.ops.aten.exp.default", + {{"self", std::string(source)}}, + fbs::ScalarType::FLOAT, + {4}); + }; + const auto add = [&](const char* name, const char* left, const char* right) { + program.call( + name, + "torch.ops.aten.add.Tensor", + {{"self", std::string(left)}, {"other", std::string(right)}}, + fbs::ScalarType::FLOAT, + {4}); + }; + exp("decay", "state"); + exp("scale", "bias"); + add("sum", "decay", "scale"); + add("y", "sum", "x"); + add("next", "state", "x"); + program.mutate("state", "next"); + const std::vector bytes = program.finish("y"); + const std::vector constants = { + {.key = "state", + .bytes = std::vector(4 * sizeof(float)), + .dtype = "F32", + .shape = {4}}, + {.key = "bias", + .bytes = std::vector(4 * sizeof(float)), + .dtype = "F32", + .shape = {4}}}; + for (const bool fold : {true, false}) { + SCOPED_TRACE(fold); + auto host = + GgmlEngineHost::create(GgmlEngineOptions{.fold_constants = fold}); + auto context = make_constants_context(*host, bytes, constants); + auto executable = context->compile("forward"); + // exp(bias) is held beside the two constants when folded. + EXPECT_EQ( + context->materialized_constant_bytes(), + (fold ? 3 : 2) * 4 * sizeof(float)); + const std::vector x(4, 1.0f); + for (const float expected : {3.0f, (std::exp(1.0f) + 1.0f) + 1.0f}) { + executable->set_input(0, x.data(), x.size(), ScalarType::Float); + executable->execute(); + std::vector y(4); + executable->get_output(0, y.data(), y.size(), ScalarType::Float); + EXPECT_EQ(y, std::vector(4, expected)); + } + } +} + TEST(GgmlEngineTest, GpuUnavailableOnCpuVariant) { GgmlEngineOptions options; options.device = GgmlDevice::Gpu; diff --git a/backends/native/test/runtime/ggml/test_ggml_ops.py b/backends/native/test/runtime/ggml/test_ggml_ops.py index f11c9814ef6..54f3967beaf 100644 --- a/backends/native/test/runtime/ggml/test_ggml_ops.py +++ b/backends/native/test/runtime/ggml/test_ggml_ops.py @@ -474,6 +474,7 @@ def _run_ggml( # noqa: C901 exact_topk_for_testing: bool = False, exact_gelu_for_testing: bool = False, f32_gpu_kv_cache_for_testing: bool = False, + fold_constants: bool = True, ): """Runs each step's inputs in order on one executable and returns each step's outputs as (bytes, shape) pairs. `graph_ops`, if given, collects @@ -513,6 +514,8 @@ def _run_ggml( # noqa: C901 command.append("--exact_gelu_for_testing") if f32_gpu_kv_cache_for_testing: command.append("--f32_gpu_kv_cache_for_testing") + if not fold_constants: + command.append("--nofold_constants") with as_file(files(__package__) / "ggml_ptn_runner") as runner: result = subprocess.run( [str(runner), *command], @@ -535,6 +538,26 @@ def _run_ggml( # noqa: C901 return [outputs[i : i + num_outputs] for i in range(0, len(outputs), num_outputs)] +def _assert_same_as_unfolded(test, folded, unfolded): + """Float32 outputs computed with constants folded are bitwise those of an + unfolded run on the CPU. GPU backends fuse a graph's ops by its shape, and + a folded constant changes that shape, which can move a result by an ulp.""" + if os.environ.get("GGML_PTN_DEVICE", "cpu") == "cpu": + test.assertEqual(folded, unfolded) + return + for step_folded, step_unfolded in zip(folded, unfolded, strict=True): + for (raw, shape), (raw_unfolded, shape_unfolded) in zip( + step_folded, step_unfolded, strict=True + ): + test.assertEqual(shape, shape_unfolded) + torch.testing.assert_close( + torch.frombuffer(bytearray(raw), dtype=torch.float32), + torch.frombuffer(bytearray(raw_unfolded), dtype=torch.float32), + rtol=1e-5, + atol=1e-6, + ) + + def _hip_accumulates_half_gemms_in_f32() -> bool: """ggml-hip accumulates F16 GEMMs in F32 on CDNA and RDNA4 GPUs only.""" try: @@ -1593,6 +1616,48 @@ def forward(self, ids): with self.subTest(shape=shape): self._check(Gather(shape), (torch.tensor([[3, 0], [1, 3]]),)) + def test_constant_subgraphs_are_computed_once(self): + class ConstantMath(torch.nn.Module): + def __init__(self): + super().__init__() + self.log_decay = torch.nn.Parameter(torch.randn(16)) + self.weight = torch.nn.Parameter(torch.randn(16) * 0.1) + + def forward(self, x): + decay = -torch.exp(self.log_decay.float()) + norm = F.rms_norm(x, (16,), eps=1e-6) * (self.weight + 1.0) + return decay * x + norm + + model = ConstantMath().eval() + x = torch.randn(3, 16) + with torch.no_grad(): + expected = model(x) + ep = torch.export.export(model, (x,)) + ops = {fold: collections.Counter() for fold in (True, False)} + with tempfile.TemporaryDirectory() as tmp: + outdir = Path(tmp) + package = outdir / "model.ptn" + to_native(ep).save(str(package)) + folded, unfolded = ( + _run_ggml( + package, + [(x,)], + outdir, + 1, + graph_ops=ops[fold], + fold_constants=fold, + ) + for fold in (True, False) + ) + _assert_same_as_unfolded(self, folded, unfolded) + (((raw, shape),),) = folded + actual = torch.frombuffer(bytearray(raw), dtype=torch.float32) + torch.testing.assert_close(actual.reshape(shape), expected) + self.assertGreater(ops[False]["EXP"], 0) + for op in ("EXP", "NEG"): + self.assertEqual(ops[True][op], 0, op) + self.assertLess(ops[True].total(), ops[False].total()) + def test_matmul(self): self._check( Lambda(torch.matmul), @@ -2813,12 +2878,13 @@ def forward(self, values, positions, row): return self.cache * 1.0 values, positions = torch.randn(1, 2, 3, 4), torch.tensor([5, 1, 6]) - # Per graph build (two MULs each): the cast of the F16 output, plus the - # F32 -> F16 cast of the cache rows when it is kept. + # Per graph build (two MULs each): the F32 -> F16 cast of the cache + # rows when it is kept. Casts of constants, the buffer and the scalar + # factors export lifts to tensors, are computed once, at compile. cases = { - "fresh": (FreshSource(), (values, positions), 1), - "buffer": (BufferSource(), (values, positions), 2), - "written": (WrittenSource(), (values, positions, torch.tensor([0])), 2), + "fresh": (FreshSource(), (values, positions), 0), + "buffer": (BufferSource(), (values, positions), 0), + "written": (WrittenSource(), (values, positions, torch.tensor([0])), 1), } for source, (model, inputs, casts) in cases.items(): with self.subTest(source=source): @@ -3339,13 +3405,27 @@ def test_prefill_and_one_token_calls_share_state(self): } eager = copy.deepcopy(wrapper) expected = [eager(*inputs) for inputs in steps] + ops = {fold: collections.Counter() for fold in (True, False)} with tempfile.TemporaryDirectory() as tmp: outdir = Path(tmp) package = outdir / "tiny_qwen35.ptn" to_native(programs).save(str(package)) - outputs = _run_ggml( - package, steps, outdir, 1, resize=True, method=";".join(methods) + outputs, unfolded = ( + _run_ggml( + package, + steps, + outdir, + 1, + resize=True, + method=";".join(methods), + graph_ops=ops[fold], + fold_constants=fold, + ) + for fold in (True, False) ) + # Every method computes its constants once, prefill as well as decode. + _assert_same_as_unfolded(self, outputs, unfolded) + self.assertLess(ops[True].total(), ops[False].total()) self.assertEqual(len(outputs), len(steps)) # GPUs multiply 8-row F32 linears in TF32 or XF32 (README: Known ggml # GPU numerics). @@ -3411,11 +3491,24 @@ def _check(self, native: bool): self.assertEqual(targets.count(gated_delta_rule_op), 3 if native else 0) eager = copy.deepcopy(wrapper) expected = [eager(*inputs) for inputs in steps] + ops = {fold: collections.Counter() for fold in (True, False)} with tempfile.TemporaryDirectory() as tmp: outdir = Path(tmp) package = outdir / "tiny_qwen35.ptn" to_native(ep).save(str(package)) - outputs = _run_ggml(package, steps, outdir, 1) + outputs, unfolded = ( + _run_ggml( + package, + steps, + outdir, + 1, + graph_ops=ops[fold], + fold_constants=fold, + ) + for fold in (True, False) + ) + _assert_same_as_unfolded(self, outputs, unfolded) + self.assertLess(ops[True].total(), ops[False].total()) self.assertEqual(len(outputs), len(steps)) for step, (step_outputs, reference) in enumerate(zip(outputs, expected)): ((raw, shape),) = step_outputs