Three Problems, One Task: Accelerating Floyd-Warshall

Gnkglow

Gnkgo, A, B, C

Department of Computer Science, ETH Zurich, Switzerland

Abstract Link to heading

The Floyd-Warshall algorithm computes all-pairs path quantities and, in its generic semiring form, applies to many problems beyond shortest paths. Its triple loop and irregular access to large matrices make it both compute- and memory-bound, and therefore an attractive target for optimisation. We study how far the generic Floyd-Warshall structure can be optimised for three instantiations: shortest path (min⁡,+)(\min, +), bottleneck path (max⁡,min⁡)(\max, \min) and transitive closure (∨,∧)(\lor, \land). Starting from a generic triple-loop baseline, we specialise each variant and apply blocking and tiling for cache locality, AVX2 vectorisation for data-level parallelism, and autotuning to select machine-specific block sizes, tile sizes, and unrolling factors. For transitive closure, we further exploit the Boolean semiring through bit-packing and branchless updates. On Intel Core Ultra 7 155H Meteor Lake, our optimised implementations achieve up to 9.19× for the bottleneck path, 14.69× for shortest path and 1278× in the transitive closure over the scalar baseline.

1 Introduction Link to heading

Motivation. Many graph problems require information about all pairs of vertices, not just from a single source. Examples include reachability analysis, dependency propagation, network reliability, and, generally, dynamic programming formulations on graphs such as context-free grammar parsing. Floyd-Warshall is attractive in those cases because it offers a generic version, which can be instantiated with a pair of operations, a so-called semiring, that accommodate a wide range of applications.

Floyd-Warshall, in its generic form, has cubic time complexity, determined by its triple loop implementation. It further accesses large matrices in patterns that stress the memory hierarchy. Thus, for large instances, data layout, cache reuse, and vectorisation become increasingly important.

This project studies how far the generalised Floyd-Warshall structure can be optimised in three concrete problems: Shortest Path, Bottleneck Path, and Transitive Closure.

Contribution. We categorize our optimisations into two groups: general optimisations applied globally, and specialized optimisations tailored to individual semirings. At the global level, we minimize overhead using a flat matrix layout, block-major storage, and a four-phase tiled schedule targeting the fwi_abc phase. At the semiring level, we apply type-specific enhancements: floating-point variants use register-blocked AVX2 and scalar kernels, while the transitive closure semiring relies on bit-packing and branchless masked updates. Finally, we use autotuning to derive optimal, machine-dependent parameters for block size, tile size, and loop unrolling.

2 Background: Generalised Floyd-Warshall Link to heading

The generic form of Floyd-Warshall can be instantiated with an outer operation op1 and an inner operation op2. The ones considered in this report are:

  • Shortest Path: (min⁡,+)(\min, +)
  • Bottleneck Path: (max⁡,min⁡)(\max, \min)
  • Transitive Closure: (∨,∧)(\lor, \land)

The generic update is

D[i,j]←op1(D[i,j],D[i,k] op2 D[k,j]).(1)D[i,j] \leftarrow op1(D[i,j], D[i,k] \ op2 \ D[k,j]). \tag{1}

In this naïve implementation, this generic update is executed with a simple triple loop over kk, ii, and jj. It offers the advantage of being easy to understand. However, it introduces overhead through generic operations and nested matrix storage. This nested layout also gives poor locality.

Loop invariant. To ensure correctness, the loop invariant on the outermost kk loop has to be respected. After finishing iteration kk, every entry D[i,j]D[i,j] contains the optimal path value from ii to jj whose intermediate vertices are drawn only from the set {0,…,k}\lbrace 0,\ldots,k \rbrace. Optimality is defined differently depending on the problem: distance for the shortest path, bottleneck capacity for bottleneck paths, or reachability for transitive closure. This invariant becomes relevant in several optimisation steps, particularly in tiling and blocking, where this invariance has to be upheld.

Cost model. The cost analysis for the Floyd-Warshall algorithm is straightforward. The algorithm contains two floating-point operations within a triple loop, which results in a total cost of 2n32n^3 FLOPs for each algorithm. The types of operations differ for each of the three implementations however each operation is always performed n3n^3 times. In the Transitive Closure case, our optimisations end up removing the floating point operations, which means the cost is measured in ops for these cases. This still allows us to compare the Transitive Closure algorithms with the others.

In all experiments we measure the median number of cycles using the Read Time-Stamp Counter of the CPU. In order to avoid the measurement overhead, we make sure that for all input sizes the algorithm runs for at least 100 million cycles by repeating the calculation if necessary. We then measure the cycles ten times and use the median as the final result.

Finally, we plot the performance of each algorithm by dividing the cost by the number of cycles used.

3 Optimisation Performed Link to heading

In the following section, we describe the main optimisations performed to create the final algorithms. We started by only working on the bottleneck paths algorithm and later used that optimised algorithm as a base for the other algorithms. We group our optimisations as follows:

  • Blocking
  • SIMD Intrinsics
  • Tiling
  • Autotuning
  • Optimisations for Transitive Closure

Assumptions. We assume that the input matrix is given in the form of a flat row-major array. Transforming the input matrix is considered part of the algorithm. So, if optimisations utilise other data structures, the improvement must be significant enough to offset the transformation overhead. In addition, we assume that the input sizes are in the form of powers of two and do not cause any overflow or infinity problems.

Base Implementation. The base implementation used for all baseline measurements takes the form of a triple loop with the inner and outer operations passed as parameters. This means the same algorithm is used for all three variants.

This baseline algorithm has many limitations. The basic triple loop has very poor cache locality and the function pointers passed prevent inlining. After the base implementation, all subsequent algorithms were specialised for a single variant.

Blocking. Blocking is a loop transformation that restructures an algorithm so that it operates on small sub-regions of the data that fit entirely in cache, rather than streaming repeatedly across the whole matrix from main memory. Its purpose is to improve temporal locality. By keeping a working set resident in cache and reusing every loaded element many times before evicting it, blocking converts an algorithm that is bound by memory bandwidth into one that is bound by compute throughput.

To improve cache locality further, we ensured to rearrange the matrix to block-major order. The time taken for this was considered to be a part of the runtime for the algorithm.

SIMD Intrinsics. The scalar block update repeatedly applies

T[i,j]←op1(T[i,j], op2(A[i,k],B[k,j]))T[i,j]\leftarrow \texttt{op1}(T[i,j],\ \texttt{op2}(A[i,k], B[k,j]))

and for a fixed ii and kk the value A[i,k]A[i,k] is reused for many consecutive jj values. Additionally, B[k,j],B[k,j+1],…B[k,j], B[k,j+1],\ldots are stored contiguously in memory inside a block. Consequently, several target entries in the same row of TT can be updated in parallel, which is realised with SIMD instructions. More precisely, instead of applying the update to one entry T[i,j]T[i,j], the SIMD implementation operates on four doubles at once through the vector T[i,j:j+3]\mathbf{T}[i,j:j+3].

As a first step, the target vector T[i,j:j+3]\mathbf{T}[i,j:j+3] is loaded using _mm256_load_pd(&T[i,j]). The source value A[i,k]A[i,k] is then broadcast using _mm256_set1_pd(A[i,k]). This yields the vector

A[i,k]=[A[i,k],A[i,k],A[i,k],A[i,k]]\mathbf{A}[i,k]= \bigl[A[i,k],A[i,k],A[i,k],A[i,k] \bigr]

Lastly, the four consecutive values of BB are loaded through _mm256_load_pd(&B[k,j]), written as follows:

B[k,j:j+3]=[B[k,j],B[k,j+1],B[k,j+2],B[k,j+3]]\mathbf{B}[k, j:j+3] = \bigl[B[k, j],B[k, j+1],B[k, j+2],B[k, j+3]\bigr]

The generalised update becomes:

T[i,j:j+3]←= vop1(T[i,j:j+3],vop2(A[i,k],B[k,j:j+3])).(2)\mathbf{T}[i, j:j+3] \leftarrow{} = \ \texttt{vop1}\bigl(\mathbf{T}[i, j:j+3], \texttt{vop2}\bigl(\mathbf{A}[i,k], \mathbf{B}[k, j:j+3]\bigr)\bigr). \tag{2}

where vop1 and vop2 are the vectorised versions of their scalar counterparts op1 and op2. In AVX2 double precision, these correspond to:

  • Shortest Path: vop1 = _mm256_min_pd and vop2 = _mm256_add_pd
  • Bottleneck Path: vop1 = _mm256_max_pd and vop2 = _mm256_min_pd
  • Transitive Closure: vop1 = _mm256_or_si256 and vop2 = _mm256_and_si256

After the update has been performed, the result is written back through _mm256_store_{pd/si256}(&T[i,j],val) where val is the result of the update, as defined in Equation 2.

The performance impact of these SIMD optimisations are discussed in Section 4. Transitive closure is treated separately because its optimised variant uses bit packing in addition to the AVX2 update described above. This is outlined in Section 3 - Optimisation Transitive Closure.

Tiling. Tiling builds on blocking, and groups multiple blocks into tiles, with the idea to reuse data not just within one block but across multiple block updates. This optimisation was presented in [1] and the implementation follows the same four-phase structure. Ideally, we would like to arbitrarily reorder blocks to optimise data reuse. However, the algorithm has to maintain an invariant on the kk-loop, as introduced in Section 2. The tiled update is done in four distinct phases. Let T←F(T,A,B)T\leftarrow F(T,A,B) denote a block update, where the target block TT is updated using the source blocks AA and BB, in particular:

T[i,j]←op1(T[i,j], op2(A[i,k],B[k,j]))T[i,j]\leftarrow \texttt{op1}(T[i,j],\ \texttt{op2}(A[i,k], B[k,j]))

All four phases benefit from the block-major layout. They proceed as follows:

Phase 1 (active diagonal): In this phase we have

T=A=BT=A=B

and thus the target and source blocks are identical. The update is internal and, since later phases require the diagonal tile to be correct, it has to be computed first.

Phase 2 (active row): In this phase, we update the active row, and thus we have

T≠A but T=BT\ne A \text{ but } T=B

Phase 3 (active column): In this phase, we update the active column, and thus we have

T=A but T≠BT= A \text{ but } T \ne B

Phase 4: In the last phase, we see that all blocks TT, AA, and BB are pairwise distinct. This is the most important phase for optimisation, as the tiles AA and BB can be considered read-only and a significant speed-up can be gained. This phase corresponds to the fwi_abc implementation of [1]. The primary speed-up comes from the fact that the parts of the tile TT can be kept in registers, while repeated updates are performed on it before it is written back to memory.

1 2 3 … K K+1 … l
1 4 4 4 … 3 4 … 4
2 4 4 4 3 4 4
3 4 4 4 3 4 4
⋮ ⋮ ⋱ 3 4 4
K 2 2 2 2 1 2 2
K+1 4 4 4 4 3 4 4
⋮ ⋮ ⋱ 4
l 4 4 4 4 3 4 4 4

Figure 1: Each square represents one tile and contains the number of the phase it is updated in, for an arbitrary but fixed value KK Phases. Phase 1 updates the diagonal tile, whereas Phase 2 and 3 update the row and column, respectively. Lastly, Phase 4 updates all remaining tiles. Since this phase contains (l−1)2(l-1)^2 tiles out of a total of l2l^2 grid, it dominates the computation and is thus a primary target for optimisations.

Aside from the low-latency access granted through efficient register usage, this phase further benefits from its limited number of blocks compared to the other phases.

Fig. 1 shows the relationship between the number of blocks in each phase. In particular, for a round fixed tile KK, Phase 1 contains one tile, while Phases 2 and 3 contain l−1l-1 tiles each, where ll is the number of tiles per matrix dimension. Phase 4, however, updates the remaining (l−1)2(l-1)^2 tiles and, therefore, dominates the total work. In combination with the low-latency access discussed before, this step allowed a significant speedup.

Autotuning. Up until this point, all optimisations were done by hand and parameters such as block size, tile size, and loop unrolling factors were chosen based on intuition and limited experimentation. From lectures and observing the performance of the various algorithms on different machines, we know that the optimal parameters differ greatly depending on the CPU. Therefore, we created an autotuning algorithm that chooses the best possible parameters within a defined search space for the machine it is running on.

To do this, Python scripts were created that can take a base implementation of an algorithm and test different parameter combinations. We chose to implement autotuning for the following parameters:

  • Block size (16, 32, 64)
  • Tile size (1, 2, 4, 8, 16)
  • I loop unrolling (1, 2, 4)
  • J loop unrolling (4, 8, 16)
  • K loop unrolling (1, 2, 4)

Block and tile size were obvious choices, as autotuning could test different sizes by changing one variable inside the algorithm. In a second step, loop unrolling was added, which required dynamic code generation. I, J, and K refer to the variables of the final triple loop of the algorithm inside the process_block_abc function. For the Transitive Closure algorithm, the algorithm differs from the other two. For example, there is no j-direction inner loop to unroll in the given base algorithm. Therefore, autotuning was only implemented for tile size and I and K unrolling.

The ATLAS [2] project introduced in the lecture uses guided descent in order to limit the search space. For our project we were able to reduce the search space significantly by removing options which, through experimentation, were determined to always have bad performance. This allowed us to explore all combinations using exhaustive search. Therefore, an algorithm is generated and tested for every possible combination. This gives 405 combinations for shortest paths and bottleneck paths, 54 for Transitive Closure.

The combinations of parameters found and their effects depend heavily on the platform and are presented in the results section. In general, blocking and tiling improve locality in the different cache levels, and I- and J loop unrolling form a register tile of accumulators, which gets reused across the k-iterations. K unrolling creates independent instructions for Instruction Level Parallelism (ILP). When presenting the results, we try to identify why the found parameters are ideal. However, all parameters affect each other, and additional effects may influence the algorithm’s performance, for example, optimal register usage. Nevertheless, because of our exhaustive search approach, we can be confident that we are optimal in the defined search space for the input sizes tested.

Optimisations for Transitive Closure. Unlike the shortest-path and bottleneck variants, whose semirings operate on real-valued distances, the transitive closure works over the boolean semiring (∨,∧)(\lor, \land). This collapses the per-element arithmetic to logic operations and opens a class of bit-level optimisations that are unavailable to the floating-point variants. The following techniques exploit that structure.

Since each entry only needs to be one bit, 64 entries of a row are bit-packed into a single uint64_t. This yields a 64 times reduction in storage and, more importantly, turns the inner update into word-parallel logic. Additionally, instead of testing each node’s reachability with a data-dependent branch,

if ((col_word >> k) & 1)
    tgt |= kRow;

we use a branchless mask, which eliminates the branch-misprediction stalls:

mask = -((col_word >> k) & 1);
tgt |= kRow & mask;

The branchless update vectorises naturally with AVX2: four packed rows are held in one __m256i, and the rank-1 update for tgt becomes a vpand/vpor pair across all four lanes at once. The only non-trivial step is reproducing the per-lane mask in vector form: each lane must become all-ones when bit kk of its column word is set, and all-zeros otherwise.

The obvious construction shifts bit kk to the least-significant position and negates to broadcast (vpsrlq, vpand, vpsubq). The shift and subtract both compete for ports 0/1, where the surrounding vpor and vpand of the rank-1 update also execute. We replace the three-instruction sequence with a precomputed lookup table: BIT_MASKS_RAW[k] stores (1≪k)(1 \ll k) replicated into all four 64-bit lanes (64 entries, 32-byte aligned so it loads with a single vmovdqa). The mask is then built with one vpand and one vpcmpeqq:

bit_k = BIT_MASKS_RAW[k];
mask  = cmpeq_epi64(vcol & bit_k, bit_k);

Isolating bit kk with vpand and comparing it back against (1≪k)(1 \ll k) yields the same all-ones/all-zeros lane mask, but the table load issues on the dedicated load ports (2/3) rather than the ALU ports, relieving the execution bottleneck at the cost of a 2 KB table that stays resident in L1.

4 Experimental Results Link to heading

Experimental setup. An Intel(R) Core(TM) Ultra 7 155H - Meteor Lake Processor was used to run all the experiments to achieve consistent results. The operating system used was Windows. ThrottleStop [3] was used to disable the turbo boost to ensure that the measurements were correct. With turbo boost, a maximum frequency of 4.8GHz can be achieved. Without turbo boost, the processor ran with 3GHz. In addition, the task was pinned to specific cores to reduce interleaving with other programs. The Core Ultra 7 155H has a 48 KB L1 data cache, a 2 MB L2 cache, and a 24 MB shared L3 cache, holding roughly 6,144, 262,144, and 3,145,728 double-precision elements respectively. These capacities set the vertical dashed lines in the performance plots. The compiler g++ with version 13.2.0 has been used to compile the files. For the vectorised code, -O3 - march=native was used. For the scalar -O3 -fno-tree-vectorise has been used. For calculating the maximum achievable performance, the website www.uops.info has been used with the Meteor-Lake-P data.

Table 1: Maximum achievable performance per kernel on the Intel Core Ultra 7 155H. Peak is a throughput bound (AVX2 port issue rate × 4 doubles, no FMA so 1 flop per element per op); latency is excluded. Port labels use the uops.info notation, e.g. p01 = {0,1}.

Kernel op1 / op2 (ports) Max instr/cyc Peak Measured % peak
Shortest (min, +) min{0,1} / add{1,5} 3 12 flop/c 6.4 53%
Bottleneck (max, min) max{0,1} / min{0,1} 2 8 flop/c 4.8 60%
Transitive (∨, ∧) or{0,1,5} / and{0,1,5} 3 768 ops/c 222 ∼29%

Results. In every plot the horizontal axis is n=log⁡2n = \log_2 of the matrix dimension, and the vertical dashed lines mark the input sizes at which the working set exceeds the L1, L2, and L3 caches. Bottleneck and shortest path are reported in flops/cycle, transitive closure is reported in operations/cycle (Section 2). For each problem we present the best scalar, compiler-vectorised, and hand-written SIMD code, discuss the measured performance and provide the cycle count and speed-up compared to the base.

Shortest Path. The shortest path variant uses the (min⁡,+)(\min, +) semiring. All test results are shown in Fig. 2 as well as Table 2. Our optimisations without using vectorisation achieve of roughly 1.6 flops/cycle while the baseline plateaus near 0.4 flops/cycle.

The compiler-vectorised results are the surprising part: Using compiler auto-vectorisation on our scalar code only results in 1.6 flops/cycle, essentially no better than the best scalar version. The compiler evidently fails to vectorise the min-plus inner loop effectively. Also, when analysing the results from VTune, FPvec256% was for all runs 0%, showing that it could not automatically vectorise.

Because (min⁡,+)(\min, +) map directly onto _mm256_min_pd and _mm256_add_pd, explicit vectorisation, using hand-written intrinsics, recovers the 4-wide parallelism the compiler missed.

In a final step autotuning was performed on the vectorised code, optimising block and tile sizes, as well as loop unrolling factors. This further improved the SIMD intrinsics code’s performance to a roughly 14.69x speed-up over the base code. The final parameters used were block size 16, tile size 8, and loop unrolling factors of 4, 8 and 1 (see also Table 5). The block and tile sizes are very small resulting in a tile size of only 128 KB. This does not fit into L1 cache, but easily into L2. As we used exhaustive search to find these sizes we can be certain these are the optimal choice from all tested sizes and the benefits of the small sizes outweighed the sub-optimal tile size. However, on other CPUs we did not observe the same and these setups chose tile sizes which fill the L2 cache, which is more in line with what we would expect.

The unrolling factors are easier to explain: The choice for II, JJ and KK result in almost perfect register usage inside the loop body (Not more than 16 registers are needed for one iteration of the outer I-loop).

A final thing of note: All our algorithms gain in performance the larger the input size for the sizes we tested. The main reason we found for this is that optimisation like tiling only start working at these larger sizes. At n=7, the best performing code still uses only one tile. Starting with n=8 there are 2 tiles and we start seeing the benefits of tiling.

Shortest Path optimisations showing the best optimisations for each category.

Figure 2: Shortest Path optimisations showing the best optimisations for each category.

Table 2: Cycle counts and speedups for Shortest Path at matrix size n=2048n = 2048.

Implementation Cycles Speedup
Base 40,917,034,154 1.00×
Best scalar 10,844,334,507 3.77×
Best compiler-vectorised 10,528,352,672 3.89×
Best SIMD 2,785,387,362 14.69×

Bottleneck Path. Fig 3 shows the best code from each category and all the significant optimisation steps. Performance rises from the baseline 0.5 flops/cycle, to about 1.2 flops/cycle utilising blocking, tiling as well as other smaller optimisations. This increases further to 3.65 flops/cycle with compiler auto-vectorisation, and 4.8 flops/cycle with hand-written AVX2 intrinsics and autotuning. Again, as in the results for the shortest path algorithms, we see a dip in performance at n=7 and otherwise higher performance for larger input sizes. The cycle counts can be seen in Table 2.

Compared to the shortest path, using compiler auto-vectorisation shows significant improvements. The auto-vectorised scalar code results in code with performance up to 3.65 flops/cycle. We also used auto-vectorisation on the baseline. The performance for that code however, stays near 0.5 flops/cycle, confirming that vectorisation only pays off once blocking has made the access pattern regular and cache-resident. Also, the compiler cannot vectorise the code, if it cannot inline all the functions, as is the case in the baseline code.

With explicit AVX2 intrinsics, the autotuned implementation reaches 4.8 flops/cycle. The difference between the compiler-vectorised result and the hand-written implementation shows that intrinsics still extract parallelism that the compiler alone couldn’t.

The values that the autotuner chose for our machine can be seen in Table 5 and are notable: Despite the code build-up being structurally very similar, a totally different unrolling configuration was found to be the most performant. The chosen values still utilise the registers efficiently. However, a wide J-unroll and additional independent instructions provided by the unrolling of the K-loop seem to be more beneficial for bottleneck paths than for shortest paths. This is likely a result of the different instruction mix and the available ports to issue instructions. We must however state that this is speculation and we found no concrete evidence pinpointing the cause of the difference.

Bottleneck Path optimisations showing the best optimisations for each category.

Figure 3: Bottleneck Path optimisations showing the best optimisations for each category.

Table 3: Cycle counts and speedups for Bottleneck Path at matrix size n=2048n = 2048.

Implementation Cycles Speedup
Base 33,007,300,082 1.00×
Best scalar 13,955,684,346 2.37×
Best compiler-vectorised 4,670,719,180 7.07×
Best SIMD-intrinsics 3,591,380,310 9.19×

Transitive Closure. The transitive closure variant works over the boolean semiring (∨,∧)(\lor, \land) and is measured in operations/cycle. Because bit-packing reduces storage by 64×, we can evaluate it on larger matrices, up to n=14n=14, such that the matrices again no longer fit into cache.

The branchless scalar version reaches about 27 ops/cycle, while the generic floating-point baseline stays essentially flat near zero on this scale.

Compiler-vectorisation brings only a marginal improvement, to roughly 30 ops/cycle, since the scalar code already does word-parallel operations on packed 64-bit integers.

The fully vectorised fast-mask version (Fig. 4) reaches about 222 ops/cycle. Operating on 256-bit AVX2 words processes four 64-bit packed rows at once, and the branchless mask update avoids the mispredictions of the naive reachability test.

Transitive Closure optimisations showing the best optimisations for each category.

Figure 4: Transitive Closure optimisations showing the best optimisations for each category.

Fig. 4 places the optimised implementations against the generic baseline, which sits effectively on the axis at this scale. The fast-mask version beats it by a large margin and exceeds the best bit-packed scalar version (≈ 30 ops/cycle) by roughly 7×; bit-packing, branchless updates, and AVX2 together make transitive closure by far the highest-throughput of the three problems. The corresponding cycle count can be seen in Table 4. The values that the autotuner chose for our machine can be seen in Table 5.

Autotuning for the transitive closure code was slightly different, both block size and the J-unrolling factor were not autotuned. This, as the code was structurally different and, for example, block size could not be changed without significant adjustments to the code structure. The chosen values follow logic similar to that of the previous algorithms. The unrolling again makes sure all values fit into the 16 registers available. Notable is that a tile fits into L1 cache in the transitive closure case.

Table 4: Cycle counts and speedups for Transitive Closure at matrix size n=16384n = 16384.

Implementation Cycles Speedup
Base 50,368,221,698,560 1.00×
Best scalar 324,534,318,283 155×
Best compiler-vectorised 292,644,510,586 172×
Best SIMD 39,422,010,966 1278×

Table 5: Autotuned parameters selected per variant on the Intel Core Ultra 7 155H. Transitive closure has no block-size or JJ-unroll parameter (Section 3).

Parameter Shortest Bottleneck Transitive
Block size 16 16 –
Tile size 8 8 8
II unroll 4 1 8
JJ unroll 8 16 –
KK unroll 1 4 8

Profiling. We used VTune to find bottlenecks, focusing on the top hotspots, the memory-bound fraction, FPvec256, the retiring percentage, and the CPI. The shortest- and bottleneck-path optimisations retire at 84% and 80.7% respectively, meaning the pipeline issues useful work in almost every slot. Transitive closure retires lower, at 53.8%: its inner loop spends a large share of its instructions building the per-lane mask (vpand, vpcmpeqq) and loading the mask table, so fewer of its retired slots correspond to the or/and operations we count. In all three cases, however, the memory-bound fraction stays below 10%. The limit is therefore on the execution core, not in memory, and changes to data layout or scheduling are unlikely to relax it. This also explains why transitive closure reaches only ∼29% of its nominal peak (Table 1): that bound counts only or/and, whereas every kk-step must also issue the mask construction and a table load. More broadly, the binding constraint is set by the semiring operations themselves: min⁡\min, max⁡\max, ∧\land, and ∨\lor have no fused multiply-add, AVX-512 is not available on this Meteor Lake chip, and the algorithm is already Θ(n3)\Theta(n^3).

5 Conclusions Link to heading

Overall, our optimisations showed promising results. Starting from a single generic Floyd-Warshall baseline, we specialised and optimised three semiring instantiations (shortest path (min⁡,+)(\min, +), bottleneck path (max⁡,min⁡)(\max, \min), and transitive closure (∨,∧)(\lor, \land)) through blocking, four-phase tiling, AVX2 vectorisation, and exhaustive autotuning of block size, tile size, and unrolling factors. Each variant improves by nearly or more than an order of magnitude over the generic baseline. On the Intel Core Ultra 7 155H, the optimised floating-point versions reach roughly 6.4 flop/cycle for shortest path and 4.8 flop/cycle for bottleneck path. Transitive closure used an additional strategy: bit-packing, combined with branchless mask updates, to ultimately achieve 222 ops/cycle.

The clearest takeaway is that explicit vectorisation is important: for shortest path the compiler’s auto-vectoriser barely improved on scalar code, whereas hand-written intrinsics gave a roughly 4× speedup over the best scalar version. Additionally, autotuning is a valuable tool to squeeze additional performance out of already optimised code.

In the future, the autotune step could be analysed further and tested on more machines. In particular, more parameters could be auto-tuned for transitive closure. Additionally, it would be interesting to see, what speed-up can be achieved when several threads are used and if the code is parallelised.

6 References Link to heading

[1] Han:06 (full entry is in bibl_conf.bib)

[2] atlas (full entry is in bibl_conf.bib)

[3] throttlestop (full entry is in bibl_conf.bib)

7 Contributions of Team Members Link to heading

Gnkgo. Implemented the base case of the Floyd-Warshall Algorithm. Experimented with optimisations at the start of the project like the flat matrix, blocking and changing the order of the loop. Ran optimisations from all team members in VTune to detect bottlenecks. Ran all the optimised code to ensure that all the data was coming from one machine.

A. Implemented plotting. Implemented and combined different optimisations e.g. rearranging data to block-major, blocking, register-blocking for phases 1 to 3 (bottleneck paths). Specifically for transitive-closure: bit-packing, branchless-masking, look up table for masking.

B. Implemented algebraic simplifications (all three algorithms), basic SIMD implementation (bottleneck paths), block-major tiling (bottleneck paths), block-major tiling with optimised fwi_abc kernel (bottleneck paths), and improved blocked implementations (shortest path), including scalar improved blocking and SIMD improved blocked tiling BS32.

C. Implemented autotuning scripts for all three variants. SIMD and non-SIMD. Analysed the best autotuned versions.

8 Code Link to heading

Following, we show the inner most triple loop which computes the results of one block for the shortest paths problem (clean-up code not included). The code utilizing SIMD intrinsics was auto-generated by the autotuning script and was the best performing out of all generated. The autotuned scalar versions did not make it into this report therefore the scalar code shown here is still all hand-written. The code used for the bottleneck paths problem is very similar to the code included here, with the only difference being the loop unrolling factors and the operations. Deviating from this is the transitive closure, which achieves a much higher speed-up thanks to bit packing.

First the scalar code:

int i = 0;
for (; i + I_UNROLL - 1 < iLen; i += I_UNROLL)
{
    double *target_row0 = target + (i + 0) * BLOCK_SIZE;
    double *target_row1 = target + (i + 1) * BLOCK_SIZE;
    double *target_row2 = target + (i + 2) * BLOCK_SIZE;
    double *target_row3 = target + (i + 3) * BLOCK_SIZE;
    const double *col_row0 = col_block + (i + 0) * BLOCK_SIZE;
    const double *col_row1 = col_block + (i + 1) * BLOCK_SIZE;
    const double *col_row2 = col_block + (i + 2) * BLOCK_SIZE;
    const double *col_row3 = col_block + (i + 3) * BLOCK_SIZE;

    int j = 0;
    for (; j + J_UNROLL - 1 < jLen; j += J_UNROLL)
    {
        double r0[J_UNROLL], r1[J_UNROLL], r2[J_UNROLL], r3[J_UNROLL];
        for (int jj = 0; jj < J_UNROLL; ++jj)
        {
            r0[jj] = target_row0[j + jj];
            r1[jj] = target_row1[j + jj];
            r2[jj] = target_row2[j + jj];
            r3[jj] = target_row3[j + jj];
        }

        for (int k = 0; k < kLen; ++k)
        {
            const double *row_k = row_block + k * BLOCK_SIZE + j;
            const double c0 = col_row0[k];
            const double c1 = col_row1[k];
            const double c2 = col_row2[k];
            const double c3 = col_row3[k];
            for (int jj = 0; jj < J_UNROLL; ++jj)
            {
                const double a = row_k[jj];
                r0[jj] = std::min(r0[jj], c0 + a);
                r1[jj] = std::min(r1[jj], c1 + a);
                r2[jj] = std::min(r2[jj], c2 + a);
                r3[jj] = std::min(r3[jj], c3 + a);
            }
        }

Here the auto-generated SIMD code:

int i = 0;
for (; i + I_UNROLL - 1 < iLen; i += I_UNROLL){
    double *__restrict__ target_row0 = target + (i + 0) * BLOCK_SIZE;
    double *__restrict__ target_row1 = target + (i + 1) * BLOCK_SIZE;
    double *__restrict__ target_row2 = target + (i + 2) * BLOCK_SIZE;
    double *__restrict__ target_row3 = target + (i + 3) * BLOCK_SIZE;
    const double *__restrict__ col_row0 = col_block + (i + 0) * BLOCK_SIZE;
    const double *__restrict__ col_row1 = col_block + (i + 1) * BLOCK_SIZE;
    const double *__restrict__ col_row2 = col_block + (i + 2) * BLOCK_SIZE;
    const double *__restrict__ col_row3 = col_block + (i + 3) * BLOCK_SIZE;
    int j = 0;
    for (; j + J_UNROLL - 1 < jLen; j += J_UNROLL){
        __m256d r0_0 = _mm256_load_pd(target_row0 + j + 0);
        __m256d r0_1 = _mm256_load_pd(target_row0 + j + 4);
        __m256d r1_0 = _mm256_load_pd(target_row1 + j + 0);
        __m256d r1_1 = _mm256_load_pd(target_row1 + j + 4);
        __m256d r2_0 = _mm256_load_pd(target_row2 + j + 0);
        __m256d r2_1 = _mm256_load_pd(target_row2 + j + 4);
        __m256d r3_0 = _mm256_load_pd(target_row3 + j + 0);
        __m256d r3_1 = _mm256_load_pd(target_row3 + j + 4);
        int k = 0;
        for (; k + K_UNROLL - 1 < kLen; k += K_UNROLL){
            const double *__restrict__ row_0 = row_block + (k + 0) * BLOCK_SIZE + j;
            const __m256d rk0_0 = _mm256_load_pd(row_0 + 0);
            const __m256d rk0_1 = _mm256_load_pd(row_0 + 4);
            const __m256d c0_0 = _mm256_set1_pd(col_row0[k + 0]);
            r0_0 = _mm256_min_pd(r0_0, _mm256_add_pd(c0_0, rk0_0));
            r0_1 = _mm256_min_pd(r0_1, _mm256_add_pd(c0_0, rk0_1));
            const __m256d c1_0 = _mm256_set1_pd(col_row1[k + 0]);
            r1_0 = _mm256_min_pd(r1_0, _mm256_add_pd(c1_0, rk0_0));
            r1_1 = _mm256_min_pd(r1_1, _mm256_add_pd(c1_0, rk0_1));
            const __m256d c2_0 = _mm256_set1_pd(col_row2[k + 0]);
            r2_0 = _mm256_min_pd(r2_0, _mm256_add_pd(c2_0, rk0_0));
            r2_1 = _mm256_min_pd(r2_1, _mm256_add_pd(c2_0, rk0_1));
            const __m256d c3_0 = _mm256_set1_pd(col_row3[k + 0]);
            r3_0 = _mm256_min_pd(r3_0, _mm256_add_pd(c3_0, rk0_0));
            r3_1 = _mm256_min_pd(r3_1, _mm256_add_pd(c3_0, rk0_1));
        }
        for (; k < kLen; ++k){
            const double *__restrict__ row = row_block + k * BLOCK_SIZE + j;
            const __m256d row0 = _mm256_load_pd(row + 0);
            const __m256d row1 = _mm256_load_pd(row + 4);
            const __m256d c0 = _mm256_set1_pd(col_row0[k]);
            const __m256d c1 = _mm256_set1_pd(col_row1[k]);
            const __m256d c2 = _mm256_set1_pd(col_row2[k]);
            const __m256d c3 = _mm256_set1_pd(col_row3[k]);
            r0_0 = _mm256_min_pd(r0_0, _mm256_add_pd(c0, row0));
            r0_1 = _mm256_min_pd(r0_1, _mm256_add_pd(c0, row1));
            r1_0 = _mm256_min_pd(r1_0, _mm256_add_pd(c1, row0));
            r1_1 = _mm256_min_pd(r1_1, _mm256_add_pd(c1, row1));
            r2_0 = _mm256_min_pd(r2_0, _mm256_add_pd(c2, row0));
            r2_1 = _mm256_min_pd(r2_1, _mm256_add_pd(c2, row1));
            r3_0 = _mm256_min_pd(r3_0, _mm256_add_pd(c3, row0));
            r3_1 = _mm256_min_pd(r3_1, _mm256_add_pd(c3, row1));
        }
    }
}