• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daisytuner / docc / 27981272983

22 Jun 2026 08:18PM UTC coverage: 61.754% (-0.03%) from 61.782%
27981272983

Pull #781

github

web-flow
Merge bddaa3724 into fe87d162b
Pull Request #781: Extend Segformer benchmarks setup

987 of 1432 new or added lines in 62 files covered. (68.92%)

9 existing lines in 7 files now uncovered.

38121 of 61730 relevant lines covered (61.75%)

993.19 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

45.71
/sdfg/src/data_flow/library_nodes/math/tensor/matmul_node.cpp
1
#include "sdfg/data_flow/library_nodes/math/tensor/matmul_node.h"
2
#include <cstddef>
3
#include <string>
4

5
#include "sdfg/builder/structured_sdfg_builder.h"
6
#include "sdfg/data_flow/library_nodes/math/blas/blas_node.h"
7
#include "sdfg/data_flow/library_nodes/math/blas/gemm_node.h"
8
#include "sdfg/data_flow/library_nodes/stdlib/free.h"
9
#include "sdfg/data_flow/tasklet.h"
10
#include "sdfg/element.h"
11
#include "sdfg/exceptions.h"
12
#include "sdfg/structured_control_flow/control_flow_node.h"
13
#include "sdfg/structured_control_flow/map.h"
14
#include "sdfg/structured_control_flow/sequence.h"
15
#include "sdfg/symbolic/symbolic.h"
16
#include "sdfg/types/pointer.h"
17
#include "sdfg/types/scalar.h"
18
#include "sdfg/types/tensor.h"
19
#include "sdfg/types/type.h"
20
#include "sdfg/types/utils.h"
21

22
namespace sdfg {
23
namespace math {
24
namespace tensor {
25

26
bool MatMulNode::has_basic_strides(symbolic::MultiExpression shape, symbolic::MultiExpression strides) {
×
27
    auto basic_strides = types::Tensor::strides_from_shape(shape);
×
28
    if (basic_strides.size() != strides.size()) {
×
29
        return false;
×
30
    }
×
31
    for (size_t i = 0; i < strides.size(); i++) {
×
32
        if (!symbolic::eq(basic_strides[i], strides[i])) {
×
33
            return false;
×
34
        }
×
35
    }
×
36
    return true;
×
37
}
×
38

39
bool MatMulNode::has_transposed_strides(symbolic::MultiExpression shape, symbolic::MultiExpression strides) {
×
40
    if (shape.size() < 2) {
×
41
        return false;
×
42
    }
×
43
    symbolic::MultiExpression new_shape;
×
44
    new_shape.reserve(shape.size());
×
45
    for (size_t i = 0; i < shape.size() - 2; i++) {
×
46
        new_shape.push_back(shape[i]);
×
47
    }
×
48
    new_shape.push_back(shape[shape.size() - 1]);
×
49
    new_shape.push_back(shape[shape.size() - 2]);
×
50
    symbolic::MultiExpression transposed_strides(strides);
×
51
    transposed_strides[strides.size() - 2] = strides[strides.size() - 1];
×
52
    transposed_strides[strides.size() - 1] = strides[strides.size() - 2];
×
53
    return MatMulNode::has_basic_strides(new_shape, transposed_strides);
×
54
}
×
55

56
MatMulNode::MatMulNode(
57
    size_t element_id,
58
    const DebugInfo& debug_info,
59
    const graph::Vertex vertex,
60
    data_flow::DataFlowGraph& parent,
61
    const TensorLayout& layout_a,
62
    const TensorLayout& layout_b,
63
    QuantizationType quantization,
64
    const data_flow::ImplementationType& impl_type
65
)
66
    : TensorNode(element_id, debug_info, vertex, parent, LibraryNodeType_MatMul, {}, {"Y", "A", "B"}, impl_type),
5✔
67
      fixed_quantization_(quantization), layout_a_(layout_a), layout_b_(layout_b) {
5✔
68
    if (layout_a.dims() < 2) {
5✔
69
        throw std::invalid_argument("MatMulNode: Input A must have at least 2 dimensions");
×
70
    }
×
71
    if (layout_b.dims() < 2) {
5✔
72
        throw std::invalid_argument("MatMulNode: Input B must have at least 2 dimensions");
×
73
    }
×
74
}
5✔
75

76
symbolic::Expression MatMulNode::m() const {
8✔
77
    // M is the second-to-last dimension of A
78
    return layout_a_.get_dim_innermost(1);
8✔
79
}
8✔
80

81
symbolic::Expression MatMulNode::n() const {
12✔
82
    // N is the last dimension of B
83
    return layout_b_.get_dim_innermost(0);
12✔
84
}
12✔
85

86
symbolic::Expression MatMulNode::k() const {
7✔
87
    // K is the last dimension of A (and second-to-last of B)
88
    return layout_a_.get_dim_innermost(0);
7✔
89
}
7✔
90

91
const TensorLayout& MatMulNode::layout_a() const { return layout_a_; }
×
92

93
const TensorLayout& MatMulNode::layout_b() const { return layout_b_; }
×
94

95
void MatMulNode::validate(const Function& function) const {
5✔
96
    TensorNode::validate(function);
5✔
97

98
    auto& graph = this->get_parent();
5✔
99

100
    // Check that we have exactly 2 inputs and 1 output
101
    if (graph.in_degree(*this) != 3) {
5✔
102
        throw InvalidSDFGException("MatMulNode: Expected exactly 3 inputs (Y, A, B)");
×
103
    }
×
104
    if (graph.out_degree(*this) != 0) {
5✔
105
        throw InvalidSDFGException("MatMulNode: Expected no outputs");
×
106
    }
×
107

108
    // Validate K dimension matches between A and B
109
    auto k_a = layout_a_.get_dim_innermost(0);
5✔
110
    auto k_b = layout_b_.get_dim_innermost(1);
5✔
111
    if (!symbolic::eq(k_a, k_b)) {
5✔
112
        throw InvalidSDFGException(
×
113
            "MatMulNode: K dimension mismatch. A has K=" + k_a->__str__() + ", B has K=" + k_b->__str__()
×
114
        );
×
115
    }
×
116
}
5✔
117

118
symbolic::SymbolSet MatMulNode::symbols() const {
1✔
119
    symbolic::SymbolSet syms;
1✔
120
    layout_a_.collect_symbols(syms);
1✔
121
    layout_b_.collect_symbols(syms);
1✔
122
    return syms;
1✔
123
}
1✔
124

125
void MatMulNode::replace(const symbolic::Expression old_expression, const symbolic::Expression new_expression) {
×
126
    layout_a_.replace_symbols(old_expression, new_expression);
×
127
    layout_b_.replace_symbols(old_expression, new_expression);
×
128
}
×
129

NEW
130
void MatMulNode::replace(const symbolic::ExpressionMapping& replacements) {
×
NEW
131
    layout_a_.replace_symbols(replacements);
×
NEW
132
    layout_b_.replace_symbols(replacements);
×
NEW
133
}
×
134

135
std::unique_ptr<data_flow::DataFlowNode> MatMulNode::
136
    clone(size_t element_id, const graph::Vertex vertex, data_flow::DataFlowGraph& parent) const {
×
137
    return std::unique_ptr<data_flow::DataFlowNode>(new MatMulNode(
×
138
        element_id, debug_info(), vertex, parent, layout_a_, layout_b_, fixed_quantization_, implementation_type_
×
139
    ));
×
140
}
×
141

142
types::PrimitiveType MatMulNode::fixed_quantization() const { return fixed_quantization_; }
×
143

144
void MatMulNode::set_fixed_quantization(const QuantizationType quant) { fixed_quantization_ = quant; }
×
145

146
types::PrimitiveType MatMulNode::quantization(const data_flow::DataFlowGraph& data_flow_graph) const {
×
147
    if (fixed_quantization_ != QUANTIZATION_MATCH_INPUTS) {
×
148
        return fixed_quantization_;
×
149
    } else {
×
150
        return this->primitive_type(data_flow_graph);
×
151
    }
×
152
}
×
153

154
std::optional<types::PrimitiveType> MatMulNode::uniform_quantization(const data_flow::DataFlowGraph& data_flow_graph
155
) const {
5✔
156
    if (fixed_quantization_ != QUANTIZATION_MATCH_INPUTS) {
5✔
157
        auto inferred = this->primitive_type(data_flow_graph);
×
158
        if (inferred == fixed_quantization_) {
×
159
            return fixed_quantization_;
×
160
        } else {
×
161
            return std::nullopt;
×
162
        }
×
163
    } else {
5✔
164
        return this->primitive_type(data_flow_graph);
5✔
165
    }
5✔
166
}
5✔
167

168
std::string MatMulNode::toStr() const {
×
169
    std::stringstream ss;
×
170
    ss << "MatMul(";
×
171
    ss << types::primitive_type_to_string(fixed_quantization_) << ", ";
×
172
    ss << "A: " << layout_a_;
×
173
    ss << ", B: " << layout_b_;
×
174
    ss << ")";
×
175
    return ss.str();
×
176
}
×
177

178
symbolic::Expression MatMulNode::flop() const {
×
179
    auto res_elems = symbolic::mul(this->m(), this->n());
×
180
    auto k = this->k();
×
181

182
    auto mm_mul_ops = symbolic::mul(res_elems, k);
×
183
    auto mm_sum_ops = symbolic::mul(res_elems, symbolic::sub(k, symbolic::one()));
×
184

185
    auto mul_ops = mm_mul_ops;
×
186
    auto add_ops = mm_sum_ops;
×
187
    auto per_mat = symbolic::add(mul_ops, add_ops);
×
188
    int a_dims = layout_a_.dims();
×
189
    int b_dims = layout_b_.dims();
×
190
    if (a_dims > 2 || b_dims > 2) {
×
191
        std::vector<symbolic::Expression> factors{per_mat};
×
192
        auto max_dims = std::max(a_dims, b_dims);
×
193
        for (int i = 2; i < max_dims; ++i) {
×
194
            symbolic::Expression dim_a, dim_b;
×
195
            if (i < a_dims) {
×
196
                dim_a = layout_a_.get_dim_innermost(i);
×
197
            }
×
198
            if (i < b_dims) {
×
199
                dim_b = layout_b_.get_dim_innermost(i);
×
200
            }
×
201
            if (dim_a.is_null() & !dim_b.is_null()) {
×
202
                factors.push_back(dim_b);
×
203
            } else if (!dim_a.is_null() & dim_b.is_null()) {
×
204
                factors.push_back(dim_a);
×
205
            } else if (!dim_a.is_null() & !dim_b.is_null()) {
×
206
                if (!symbolic::eq(dim_a, dim_b)) {
×
207
                    throw InvalidSDFGException(
×
208
                        "Batch dimension " + std::to_string(i) + " mismatch between A and B. A has " +
×
209
                        dim_a->__str__() + ", B has " + dim_b->__str__()
×
210
                    );
×
211
                } else {
×
212
                    factors.push_back(dim_a);
×
213
                }
×
214
            } else {
×
215
                return SymEngine::null;
×
216
            }
×
217
        }
×
218
        return SymEngine::mul(factors);
×
219
    } else {
×
220
        return per_mat;
×
221
    }
×
222
}
×
223

224
void free_after_copy(
225
    const std::string& copy_name, builder::StructuredSDFGBuilder& builder, structured_control_flow::Sequence& parent
226
) {
×
227
    auto& block = builder.add_block(parent, {}, DebugInfo());
×
228
    auto& access_in = builder.add_access(block, copy_name);
×
229
    auto& free_node = builder.add_library_node<stdlib::FreeNode>(block, DebugInfo());
×
230
    builder.add_computational_memlet(
×
231
        block, access_in, free_node, "_ptr", {}, types::Pointer(types::Scalar(types::PrimitiveType::Void))
×
232
    );
×
233
}
×
234

235
bool MatMulNode::expand(builder::StructuredSDFGBuilder& builder, analysis::AnalysisManager& analysis_manager) {
5✔
236
    auto& dataflow = this->get_parent();
5✔
237
    auto& block = static_cast<structured_control_flow::Block&>(*dataflow.get_parent());
5✔
238

239
    if (dataflow.in_degree(*this) != 3 || dataflow.out_degree(*this) != 0) {
5✔
240
        return false;
×
241
    }
×
242

243
    auto& parent = static_cast<structured_control_flow::Sequence&>(*block.get_parent());
5✔
244
    int index = parent.index(block);
5✔
245
    auto& transition = parent.at(index).second;
5✔
246

247
    // Get input and output edges
248
    auto iedges = dataflow.in_edges_by_connector(*this);
5✔
249
    if (iedges.size() != 3) {
5✔
250
        return false;
×
251
    }
×
252
    auto* iedge_y = iedges.at(Y_INPUT_IDX);
5✔
253
    auto* iedge_a = iedges.at(A_INPUT_IDX);
5✔
254
    auto* iedge_b = iedges.at(B_INPUT_IDX);
5✔
255

256
    // Check if legal - access nodes must not have other connections
257
    auto& input_node_a = static_cast<data_flow::AccessNode&>(iedge_a->src());
5✔
258
    auto& input_node_b = static_cast<data_flow::AccessNode&>(iedge_b->src());
5✔
259
    auto& output_ptr = static_cast<data_flow::AccessNode&>(iedge_y->src());
5✔
260

261
    if (dataflow.in_degree(input_node_a) != 0 || dataflow.in_degree(input_node_b) != 0 ||
5✔
262
        dataflow.in_degree(output_ptr) != 0) {
5✔
263
        return false;
×
264
    }
×
265

266
    // Determine BLAS precision from primitive type
267
    auto prim_type = this->uniform_quantization(dataflow);
5✔
268
    if (!prim_type) {
5✔
269
        return false;
×
270
    }
×
271
    blas::BLAS_Precision precision;
5✔
272
    switch (prim_type.value()) {
5✔
273
        case types::PrimitiveType::Half:
×
274
            precision = blas::BLAS_Precision::h;
×
275
            break;
×
276
        case types::PrimitiveType::Float:
3✔
277
            precision = blas::BLAS_Precision::s;
3✔
278
            break;
3✔
279
        case types::PrimitiveType::Double:
1✔
280
            precision = blas::BLAS_Precision::d;
1✔
281
            break;
1✔
282
        default:
1✔
283
            // GEMM only supports floating point types, fall back to naive expansion
284
            return false;
1✔
285
    };
5✔
286

287
    // Add new graph after the current block
288
    auto& new_sequence = builder.add_sequence_before(parent, block, transition.assignments(), block.debug_info());
4✔
289

290
    auto copy_name_a = input_node_a.data();
4✔
291
    auto copy_name_b = input_node_b.data();
4✔
292

293
    // Check if A and B have basic strides and whether they are transposed in the last dimension
294
    blas::BLAS_Transpose trans_a, trans_b;
4✔
295
    if (layout_a_.has_linear_accesses_no_padding()) {
4✔
296
        trans_a = blas::BLAS_Transpose::No;
4✔
297
    } else if (layout_a_.has_transposed_strides_no_padding()) {
4✔
298
        trans_a = blas::BLAS_Transpose::Trans;
×
299
    } else {
×
300
        trans_a = blas::BLAS_Transpose::No;
×
301
        throw InvalidSDFGException("A must be in c-order");
×
302
    }
×
303
    if (layout_b_.has_linear_accesses_no_padding()) {
4✔
304
        trans_b = blas::BLAS_Transpose::No;
4✔
305
    } else if (layout_b_.has_transposed_strides_no_padding()) {
4✔
306
        trans_b = blas::BLAS_Transpose::Trans;
×
307
    } else {
×
308
        trans_b = blas::BLAS_Transpose::No;
×
309
        throw InvalidSDFGException("B must be in c-order");
×
310
    }
×
311

312
    // Create maps for batch dimensions and M, N dimensions
313
    structured_control_flow::Sequence* last_scope = &new_sequence;
4✔
314
    structured_control_flow::Map* last_map = nullptr;
4✔
315
    symbolic::MultiExpression batch_vars;
4✔
316

317
    // Compute batch dimensions (all except last 2)
318
    size_t batch_dims_a = layout_a_.dims() - 2;
4✔
319
    size_t batch_dims_b = layout_b_.dims() - 2;
4✔
320
    size_t max_batch_dims = std::max(batch_dims_a, batch_dims_b);
4✔
321

322
    // Create maps for batch dimensions (using broadcasting)
323
    for (size_t i = 0; i < max_batch_dims; ++i) {
5✔
324
        std::string indvar_str = builder.find_new_name("_b");
1✔
325
        builder.add_container(indvar_str, types::Scalar(types::PrimitiveType::UInt64));
1✔
326

327
        auto indvar = symbolic::symbol(indvar_str);
1✔
328
        auto init = symbolic::zero();
1✔
329
        auto update = symbolic::add(indvar, symbolic::one());
1✔
330

331
        // Determine the bound for this batch dimension (max of A and B for broadcasting)
332
        symbolic::Expression bound;
1✔
333
        size_t a_idx = batch_dims_a >= (max_batch_dims - i) ? i - (max_batch_dims - batch_dims_a) : SIZE_MAX;
1✔
334
        size_t b_idx = batch_dims_b >= (max_batch_dims - i) ? i - (max_batch_dims - batch_dims_b) : SIZE_MAX;
1✔
335

336
        if (a_idx != SIZE_MAX && b_idx != SIZE_MAX) {
1✔
337
            // Both have this dimension - they should be equal or one should be 1 (broadcasting)
338
            bound = layout_a_.get_dim(a_idx); // Assume they match or broadcasting is handled
1✔
339
        } else if (a_idx != SIZE_MAX) {
1✔
340
            bound = layout_a_.get_dim(a_idx);
×
341
        } else {
×
342
            bound = layout_b_.get_dim(b_idx);
×
343
        }
×
344

345
        auto condition = symbolic::Lt(indvar, bound);
1✔
346
        last_map = &builder.add_map(
1✔
347
            *last_scope,
1✔
348
            indvar,
1✔
349
            condition,
1✔
350
            init,
1✔
351
            update,
1✔
352
            structured_control_flow::ScheduleType_Sequential::create(),
1✔
353
            {},
1✔
354
            block.debug_info()
1✔
355
        );
1✔
356
        last_scope = &last_map->root();
1✔
357
        batch_vars.push_back(indvar);
1✔
358
    }
1✔
359

360
    auto& ref_block = builder.add_block(*last_scope, {}, block.debug_info());
4✔
361

362
    auto scalar_type = types::Scalar(prim_type.value());
4✔
363

364
    // Compute offsets for this batch iteration
365
    // For A: base_offset_a = offset_a + sum_i(batch_idx_i * batch_stride_a_i)
366
    symbolic::Expression a_batch_offset = layout_a_.offset();
4✔
367
    for (size_t i = 0; i < batch_dims_a; ++i) {
5✔
368
        size_t batch_idx = max_batch_dims - batch_dims_a + i;
1✔
369
        a_batch_offset = symbolic::add(a_batch_offset, symbolic::mul(batch_vars[batch_idx], layout_a_.get_stride(i)));
1✔
370
    }
1✔
371

372
    // For B: base_offset_b = offset_b + sum_i(batch_idx_i * batch_stride_b_i)
373
    symbolic::Expression b_batch_offset = layout_b_.offset();
4✔
374
    for (size_t i = 0; i < batch_dims_b; ++i) {
5✔
375
        size_t batch_idx = max_batch_dims - batch_dims_b + i;
1✔
376
        b_batch_offset = symbolic::add(b_batch_offset, symbolic::mul(batch_vars[batch_idx], layout_b_.get_stride(i)));
1✔
377
    }
1✔
378

379
    // Compute output batch offset (same as batch_vars pattern for Y)
380
    symbolic::Expression c_batch_offset = symbolic::integer(0);
4✔
381
    for (size_t i = 0; i < batch_vars.size(); ++i) {
5✔
382
        // Output has shape [batch..., M, N] with row-major strides
383
        // Stride for batch dim i is: M * N * product of remaining batch dims
384
        symbolic::Expression c_stride = symbolic::mul(this->m(), this->n());
1✔
385
        for (size_t j = i + 1; j < batch_vars.size(); ++j) {
1✔
386
            // Multiply by subsequent batch dimensions
387
            if (j < batch_dims_a) {
×
388
                c_stride = symbolic::mul(c_stride, layout_a_.get_dim(j));
×
389
            } else if (j - batch_dims_a < batch_dims_b) {
×
390
                c_stride = symbolic::mul(c_stride, layout_b_.get_dim(j - batch_dims_a));
×
391
            }
×
392
        }
×
393
        c_batch_offset = symbolic::add(c_batch_offset, symbolic::mul(batch_vars[i], c_stride));
1✔
394
    }
1✔
395

396
    // Create access nodes
397
    auto& a_access = builder.add_access(ref_block, copy_name_a, debug_info());
4✔
398
    auto& b_access = builder.add_access(ref_block, copy_name_b, debug_info());
4✔
399
    auto& c_access_in = builder.add_access(ref_block, output_ptr.data(), debug_info());
4✔
400

401
    std::string ref_name_a = builder.find_new_name(copy_name_a + "_ref");
4✔
402
    builder.add_container(ref_name_a, types::Pointer(types::Scalar(types::PrimitiveType::Void)));
4✔
403
    auto& a_access_ref = builder.add_access(ref_block, ref_name_a, debug_info());
4✔
404
    std::string ref_name_b = builder.find_new_name(copy_name_b + "_ref");
4✔
405
    builder.add_container(ref_name_b, types::Pointer(types::Scalar(types::PrimitiveType::Void)));
4✔
406
    auto& b_access_ref = builder.add_access(ref_block, ref_name_b, debug_info());
4✔
407
    std::string ref_name_c = builder.find_new_name(output_ptr.data() + "_ref");
4✔
408
    builder.add_container(ref_name_c, types::Pointer(types::Scalar(types::PrimitiveType::Void)));
4✔
409
    auto& c_access_ref_in = builder.add_access(ref_block, ref_name_c, debug_info());
4✔
410

411
    builder.add_reference_memlet(
4✔
412
        ref_block, a_access, a_access_ref, {a_batch_offset}, ::sdfg::types::Pointer(scalar_type), debug_info()
4✔
413
    );
4✔
414
    builder.add_reference_memlet(
4✔
415
        ref_block, b_access, b_access_ref, {b_batch_offset}, ::sdfg::types::Pointer(scalar_type), debug_info()
4✔
416
    );
4✔
417
    builder.add_reference_memlet(
4✔
418
        ref_block, c_access_in, c_access_ref_in, {c_batch_offset}, ::sdfg::types::Pointer(scalar_type), debug_info()
4✔
419
    );
4✔
420

421
    // Create block with GEMM library node
422
    auto& gemm_block = builder.add_block(*last_scope, {}, block.debug_info());
4✔
423

424
    // Leading dimensions: stride of the row dimension (second-to-last dim)
425
    symbolic::Expression lda, ldb;
4✔
426
    if (trans_a == blas::BLAS_Transpose::No) {
4✔
427
        // For row-major A [m * k] -> lda = k
428
        lda = layout_a_.get_stride_innermost(1);
4✔
429
    } else {
4✔
430
        // For row-major A [m * k] -> lda = m
431
        lda = layout_a_.get_stride_innermost(0);
×
432
    }
×
433
    if (trans_b == blas::BLAS_Transpose::No) {
4✔
434
        // For row-major B [k * n] -> ldb = n
435
        ldb = layout_b_.get_stride_innermost(1);
4✔
436
    } else {
4✔
437
        // For row-major B [k * n] -> ldb = k
438
        ldb = layout_b_.get_stride_innermost(0);
×
439
    }
×
440
    // For row-major C [m * n] -> ldc = n
441
    auto ldc = this->n();
4✔
442

443
    // Add GEMM node: C = alpha * A * B + beta * C
444
    // With alpha = 1.0, beta = 0.0: C = A * B
445
    auto& gemm_node = builder.add_library_node<blas::GEMMNode>(
4✔
446
        gemm_block,
4✔
447
        debug_info(),
4✔
448
        blas::ImplementationType_BLAS,
4✔
449
        precision,
4✔
450
        blas::BLAS_Layout::RowMajor,
4✔
451
        trans_a,
4✔
452
        trans_b,
4✔
453
        this->m(),
4✔
454
        this->n(),
4✔
455
        this->k(),
4✔
456
        lda,
4✔
457
        ldb,
4✔
458
        ldc
4✔
459
    );
4✔
460

461
    auto& a_access_ref_in_gemm = builder.add_access(gemm_block, ref_name_a, debug_info());
4✔
462
    auto& b_access_ref_in_gemm = builder.add_access(gemm_block, ref_name_b, debug_info());
4✔
463
    auto& c_access_ref_in_gemm = builder.add_access(gemm_block, ref_name_c, debug_info());
4✔
464

465
    // Create alpha and beta constants
466
    auto& alpha_const = builder.add_constant(gemm_block, "1.0", scalar_type, debug_info());
4✔
467
    auto& beta_const = builder.add_constant(gemm_block, "0.0", scalar_type, debug_info());
4✔
468

469
    // Connect memlets with batch offsets
470
    // Input A with offset
471
    builder.add_computational_memlet(
4✔
472
        gemm_block, a_access_ref_in_gemm, gemm_node, "__A", {}, ::sdfg::types::Pointer(scalar_type), debug_info()
4✔
473
    );
4✔
474
    // Input B with offset
475
    builder.add_computational_memlet(
4✔
476
        gemm_block, b_access_ref_in_gemm, gemm_node, "__B", {}, ::sdfg::types::Pointer(scalar_type), debug_info()
4✔
477
    );
4✔
478
    // Input C (for beta * C, but beta=0 so just needs to be connected)
479
    builder.add_computational_memlet(
4✔
480
        gemm_block, c_access_ref_in_gemm, gemm_node, "__C", {}, ::sdfg::types::Pointer(scalar_type), debug_info()
4✔
481
    );
4✔
482
    // Alpha constant
483
    builder.add_computational_memlet(gemm_block, alpha_const, gemm_node, "__alpha", {}, scalar_type, debug_info());
4✔
484
    // Beta constant
485
    builder.add_computational_memlet(gemm_block, beta_const, gemm_node, "__beta", {}, scalar_type, debug_info());
4✔
486

487
    // Free copies if we made them
488
    if (copy_name_a != input_node_a.data()) {
4✔
489
        free_after_copy(copy_name_a, builder, new_sequence);
×
490
    }
×
491
    if (copy_name_b != input_node_b.data()) {
4✔
492
        free_after_copy(copy_name_b, builder, new_sequence);
×
493
    }
×
494

495

496
    builder.clear_code_node_legacy(block, *this);
4✔
497
    // WARNING: this has been deallocated at this point!!
498
    builder.remove_child(parent, index + 1);
4✔
499

500
    return true;
4✔
501
}
4✔
502

503
nlohmann::json MatMulNodeSerializer::serialize(const data_flow::LibraryNode& library_node) {
×
504
    const MatMulNode& matmul_node = static_cast<const MatMulNode&>(library_node);
×
505
    nlohmann::json j;
×
506

507
    j["code"] = matmul_node.code().value();
×
508

509
    serializer::JSONSerializer serializer;
×
510

511
    matmul_node.layout_a().serialize_to_json(j["layout_a"]);
×
512
    matmul_node.layout_b().serialize_to_json(j["layout_b"]);
×
513

514
    j["result_quant"] = matmul_node.fixed_quantization();
×
515

516
    return j;
×
517
}
×
518

519
data_flow::LibraryNode& MatMulNodeSerializer::deserialize(
520
    const nlohmann::json& j, builder::StructuredSDFGBuilder& builder, structured_control_flow::Block& parent
521
) {
×
522
    assert(j.contains("element_id"));
×
523
    assert(j.contains("code"));
×
524
    assert(j.contains("debug_info"));
×
525

526
    std::optional<TensorLayout> layout_a;
×
527
    std::optional<TensorLayout> layout_b;
×
528

529
    auto layout_a_it = j.find("layout_a");
×
530
    if (layout_a_it != j.end()) {
×
531
        layout_a = TensorLayout::deserialize_from_json(*layout_a_it);
×
532
        layout_b = TensorLayout::deserialize_from_json(j.at("layout_b"));
×
533

534
    } else {
×
535
        assert(j.contains("shape_a"));
×
536
        assert(j.contains("shape_b"));
×
537

538
        symbolic::MultiExpression shape_a;
×
539
        for (const auto& dim : j["shape_a"]) {
×
540
            shape_a.push_back(symbolic::parse(dim.get<std::string>()));
×
541
        }
×
542

543
        symbolic::MultiExpression shape_b;
×
544
        for (const auto& dim : j["shape_b"]) {
×
545
            shape_b.push_back(symbolic::parse(dim.get<std::string>()));
×
546
        }
×
547

548
        symbolic::MultiExpression strides_a;
×
549
        if (j.contains("strides_a")) {
×
550
            for (const auto& stride : j["strides_a"]) {
×
551
                strides_a.push_back(symbolic::parse(stride.get<std::string>()));
×
552
            }
×
553
        }
×
554

555
        symbolic::MultiExpression strides_b;
×
556
        if (j.contains("strides_b")) {
×
557
            for (const auto& stride : j["strides_b"]) {
×
558
                strides_b.push_back(symbolic::parse(stride.get<std::string>()));
×
559
            }
×
560
        }
×
561

562
        symbolic::Expression offset_a = symbolic::integer(0);
×
563
        if (j.contains("offset_a")) {
×
564
            offset_a = symbolic::parse(j["offset_a"].get<std::string>());
×
565
        }
×
566

567
        symbolic::Expression offset_b = symbolic::integer(0);
×
568
        if (j.contains("offset_b")) {
×
569
            offset_b = symbolic::parse(j["offset_b"].get<std::string>());
×
570
        }
×
571

572
        layout_a = TensorLayout(shape_a, strides_a, offset_a);
×
573
        layout_b = TensorLayout(shape_b, strides_b, offset_b);
×
574
    }
×
575

576
    auto quantization = deserialize_quantization(j, "result_quant", QUANTIZATION_MATCH_INPUTS);
×
577

578
    sdfg::serializer::JSONSerializer serializer;
×
579
    DebugInfo debug_info = serializer.json_to_debug_info(j["debug_info"]);
×
580

581
    return builder.add_library_node<MatMulNode>(parent, debug_info, layout_a.value(), layout_b.value(), quantization);
×
582
}
×
583

584
} // namespace tensor
585
} // namespace math
586
} // namespace sdfg
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc