Stay Ahead, Stay ONMINE

Nine Rules for SIMD Acceleration of Your Rust Code (Part 1)

Thanks to Ben Lichtman (B3NNY) at the Seattle Rust Meetup for pointing me in the right direction on SIMD. SIMD (Single Instruction, Multiple Data) operations have been a feature of Intel/AMD and ARM CPUs since the early 2000s. These operations enable you to, for example, add an array of eight i32 to another array of eight i32 with just one CPU operation on a single core. Using SIMD operations greatly speeds up certain tasks. If you’re not using SIMD, you may not be fully using your CPU’s capabilities. Is this “Yet Another Rust and SIMD” article? Yes and no. Yes, I did apply SIMD to a programming problem and then feel compelled to write an article about it. No, I hope that this article also goes into enough depth that it can guide you through your project. It explains the newly available SIMD capabilities and settings in Rust nightly. It includes a Rust SIMD cheatsheet. It shows how to make your SIMD code generic without leaving safe Rust. It gets you started with tools such as Godbolt and Criterion. Finally, it introduces new cargo commands that make the process easier. The range-set-blaze crate uses its RangeSetBlaze::from_iter method to ingest potentially long sequences of integers. When the integers are “clumpy”, it can do this 30 times faster than Rust’s standard HashSet::from_iter. Can we do even better if we use Simd operations? Yes! See this documentation for the definition of “clumpy”. Also, what happens if the integers are not clumpy? RangeSetBlaze is 2 to 3 times slower than HashSet. On clumpy integers, RangeSetBlaze::from_slice — a new method based on SIMD operations — is 7 times faster than RangeSetBlaze::from_iter. That makes it more than 200 times faster than HashSet::from_iter. (When the integers are not clumpy, it is still 2 to 3 times slower than HashSet.) Over the course of implementing this speed up, I learned nine rules that can help you accelerate your projects with SIMD operations. The rules are: Use nightly Rust and core::simd, Rust’s experimental standard SIMD module. CCC: Check, Control, and Choose your computer’s SIMD capabilities. Learn core::simd, but selectively. Brainstorm candidate algorithms. Use Godbolt and AI to understand your code’s assembly, even if you don’t know assembly language. Generalize to all types and LANES with in-lined generics, (and when that doesn’t work) macros, and (when that doesn’t work) traits. See Part 2 for these rules: 7. Use Criterion benchmarking to pick an algorithm and to discover that LANES should (almost) always be 32 or 64. 8. Integrate your best SIMD algorithm into your project with as_simd, special code for i128/u128, and additional in-context benchmarking. 9. Extricate your best SIMD algorithm from your project (for now) with an optional cargo feature. Aside: To avoid wishy-washiness, I call these “rules”, but they are, of course, just suggestions. Rule 1: Use nightly Rust and core::simd, Rust’s experimental standard SIMD module. Rust can access SIMD operations either via the stable core::arch module or via nighty’s core::simd module. Let’s compare them: core::arch core::simd Nightly Delightfully easy and portable. Limits downstream users to nightly. I decided to go with “easy”. If you decide to take the harder road, starting first with the easier path may still be worthwhile. In either case, before we try to use SIMD operations in a larger project, let’s make sure we can get them working at all. Here are the steps: First, create a project called simd_hello: cargo new simd_hello cd simd_hello Edit src/main.rs to contain (Rust playground): // Tell nightly Rust to enable ‘portable_simd’ #![feature(portable_simd)] use core::simd::prelude::*; // constant Simd structs const LANES: usize = 32; const THIRTEENS: Simd = Simd::::from_array([13; LANES]); const TWENTYSIXS: Simd = Simd::::from_array([26; LANES]); const ZEES: Simd = Simd::::from_array([b’Z’; LANES]); fn main() { // create a Simd struct from a slice of LANES bytes let mut data = Simd::::from_slice(b”URYYBJBEYQVQBUBCRVGFNYYTBVATJRYY”); data += THIRTEENS; // add 13 to each byte // compare each byte to ‘Z’, where the byte is greater than ‘Z’, subtract 26 let mask = data.simd_gt(ZEES); // compare each byte to ‘Z’ data = mask.select(data – TWENTYSIXS, data); let output = String::from_utf8_lossy(data.as_array()); assert_eq!(output, “HELLOWORLDIDOHOPEITSALLGOINGWELL”); println!(“{}”, output); } Next — full SIMD capabilities require the nightly version of Rust. Assuming you have Rust installed, install nightly (rustup install nightly). Make sure you have the latest nightly version (rustup update nightly). Finally, set this project to use nightly (rustup override set nightly). You can now run the program with cargo run. The program applies ROT13 decryption to 32 bytes of upper-case letters. With SIMD, the program can decrypt all 32 bytes simultaneously. Let’s look at each section of the program to see how it works. It starts with: #![feature(portable_simd)] use core::simd::prelude::*; Rust nightly offers its extra capabilities (or “features”) only on request. The #![feature(portable_simd)] statement requests that Rust nightly make available the new experimental core::simd module. The use statement then imports the module’s most important types and traits. In the code’s next section, we define useful constants: const LANES: usize = 32; const THIRTEENS: Simd = Simd::::from_array([13; LANES]); const TWENTYSIXS: Simd = Simd::::from_array([26; LANES]); const ZEES: Simd = Simd::::from_array([b’Z’; LANES]); The Simd struct is a special kind of Rust array. (It is, for example, always memory aligned.) The constant LANES tells the length of the Simd array. The from_array constructor copies a regular Rust array to create a Simd. In this case, because we want const Simd’s, the arrays we construct from must also be const. The next two lines copy our encrypted text into data and then adds 13 to each letter. let mut data = Simd::::from_slice(b”URYYBJBEYQVQBUBCRVGFNYYTBVATJRYY”); data += THIRTEENS; What if you make an error and your encrypted text isn’t exactly length LANES (32)? Sadly, the compiler won’t tell you. Instead, when you run the program, from_slice will panic. What if the encrypted text contains non-upper-case letters? In this example program, we’ll ignore that possibility. The += operator does element-wise addition between the Simd data and Simd THIRTEENS. It puts the result in data. Recall that debug builds of regular Rust addition check for overflows. Not so with SIMD. Rust defines SIMD arithmetic operators to always wrap. Values of type u8 wrap after 255. Coincidentally, Rot13 decryption also requires wrapping, but after ‘Z’ rather than after 255. Here is one approach to coding the needed Rot13 wrapping. It subtracts 26 from any values on beyond ‘Z’. let mask = data.simd_gt(ZEES); data = mask.select(data – TWENTYSIXS, data); This says to find the element-wise places beyond ‘Z’. Then, subtract 26 from all values. At the places of interest, use the subtracted values. At the other places, use the original values. Does subtracting from all values and then using only some seem wasteful? With SIMD, this takes no extra computer time and avoids jumps. This strategy is, thus, efficient and common. The program ends like so: let output = String::from_utf8_lossy(data.as_array()); assert_eq!(output, “HELLOWORLDIDOHOPEITSALLGOINGWELL”); println!(“{}”, output); Notice the .as_array() method. It safely transmutes a Simd struct into a regular Rust array without copying. Surprisingly to me, this program runs fine on computers without SIMD extensions. Rust nightly compiles the code to regular (non-SIMD) instructions. But we don’t just want to run “fine”, we want to run faster. That requires us to turn on our computer’s SIMD power. Rule 2: CCC: Check, Control, and Choose your computer’s SIMD capabilities. To make SIMD programs run faster on your machine, you must first discover which SIMD extensions your machine supports. If you have an Intel/AMD machine, you can use my simd-detect cargo command. Run with: rustup override set nightly cargo install cargo-simd-detect –force cargo simd-detect On my machine, it outputs: extension width available enabled sse2 128-bit/16-bytes true true avx2 256-bit/32-bytes true false avx512f 512-bit/64-bytes true false This says that my machine supports the sse2, avx2, and avx512f SIMD extensions. Of those, by default, Rust enables the ubiquitous twenty-year-old sse2 extension. The SIMD extensions form a hierarchy with avx512f above avx2 above sse2. Enabling a higher-level extension also enables the lower-level extensions. Most Intel/AMD computers also support the ten-year-old avx2 extension. You enable it by setting an environment variable: # For Windows Command Prompt set RUSTFLAGS=-C target-feature=+avx2 # For Unix-like shells (like Bash) export RUSTFLAGS=”-C target-feature=+avx2″ “Force install” and run simd-detect again and you should see that avx2 is enabled. # Force install every time to see changes to ‘enabled’ cargo install cargo-simd-detect –force cargo simd-detect extension width available enabled sse2 128-bit/16-bytes true true avx2 256-bit/32-bytes true true avx512f 512-bit/64-bytes true false Alternatively, you can turn on every SIMD extension that your machine supports: # For Windows Command Prompt set RUSTFLAGS=-C target-cpu=native # For Unix-like shells (like Bash) export RUSTFLAGS=”-C target-cpu=native” On my machine this enables avx512f, a newer SIMD extension supported by some Intel computers and a few AMD computers. You can set SIMD extensions back to their default (sse2 on Intel/AMD) with: # For Windows Command Prompt set RUSTFLAGS= # For Unix-like shells (like Bash) unset RUSTFLAGS You may wonder why target-cpu=native isn’t Rust’s default. The problem is that binaries created using avx2 or avx512f won’t run on computers missing those SIMD extensions. So, if you are compiling only for your own use, use target-cpu=native. If, however, you are compiling for others, choose your SIMD extensions thoughtfully and let people know which SIMD extension level you are assuming. Happily, whatever level of SIMD extension you pick, Rust’s SIMD support is so flexible you can easily change your decision later. Let’s next learn details of programming with SIMD in Rust. Rule 3: Learn core::simd, but selectively. To build with Rust’s new core::simd module you should learn selected building blocks. Here is a cheatsheet with the structs, methods, etc., that I’ve found most useful. Each item includes a link to its documentation. Structs Simd – a special, aligned, fixed-length array of SimdElement. We refer to a position in the array and the element stored at that position as a “lane”. By default, we copy Simd structs rather than reference them. Mask – a special Boolean array showing inclusion/exclusion on a per-lane basis. SimdElements Floating-Point Types: f32, f64 Integer Types: i8, u8, i16, u16, i32, u32, i64, u64, isize, usize — but not i128, u128 Simd constructors Simd::from_array – creates a Simd struct by copying a fixed-length array. Simd::from_slice – creates a Simd struct by copying the first LANE elements of a slice. Simd::splat – replicates a single value across all lanes of a Simd struct. slice::as_simd – without copying, safely transmutes a regular slice into an aligned slice of Simd (plus unaligned leftovers). Simd conversion Simd::as_array – without copying, safely transmutes an Simd struct into a regular array reference. Simd methods and operators simd[i] – extract a value from a lane of a Simd. simd + simd – performs element-wise addition of two Simd structs. Also, supported -, *, /, %, remainder, bitwise-and, -or, xor, -not, -shift. simd += simd – adds another Simd struct to the current one, in place. Other operators supported, too. Simd::simd_gt – compares two Simd structs, returning a Mask indicating which elements of the first are greater than those of the second. Also, supported simd_lt, simd_le, simd_ge, simd_lt, simd_eq, simd_ne. Simd::rotate_elements_left – rotates the elements of a Simd struct to the left by a specified amount. Also, rotate_elements_right. simd_swizzle!(simd, indexes) – rearranges the elements of a Simd struct based on the specified const indexes. simd == simd – checks for equality between two Simd structs, returning a regular bool result. Simd::reduce_and – performs a bitwise AND reduction across all lanes of a Simd struct. Also, supported: reduce_or, reduce_xor, reduce_max, reduce_min, reduce_sum (but noreduce_eq). Mask methods and operators Mask::select – selects elements from two Simd struct based on a mask. Mask::all – tells if the mask is all true. Mask::any – tells if the mask contains any true. All about lanes Simd::LANES – a constant indicating the number of elements (lanes) in a Simd struct. SupportedLaneCount – tells the allowed values of LANES. Use by generics. simd.lanes – const method that tells a Simd struct’s number of lanes. Low-level alignment, offsets, etc. When possible, use to_simd instead. More, perhaps of interest With these building blocks at hand, it’s time to build something. Rule 4: Brainstorm candidate algorithms. What do you want to speed up? You won’t know ahead of time which SIMD approach (of any) will work best. You should, therefore, create many algorithms that you can then analyze (Rule 5) and benchmark (Rule 7). I wanted to speed up range-set-blaze, a crate for manipulating sets of “clumpy” integers. I hoped that creating is_consecutive, a function to detect blocks of consecutive integers, would be useful. Background: Crate range-set-blaze works on “clumpy” integers. “Clumpy”, here, means that the number of ranges needed to represent the data is small compared to the number of input integers. For example, these 1002 input integers 100, 101, …, 489, 499, 501, 502, …, 998, 999, 999, 100, 0 Ultimately become three Rust ranges: 0..=0, 100..=499, 501..=999. (Internally, the RangeSetBlaze struct represents a set of integers as a sorted list of disjoint ranges stored in a cache efficient BTreeMap.) Although the input integers are allowed to be unsorted and redundant, we expect them to often be “nice”. RangeSetBlaze’s from_iter constructor already exploits this expectation by grouping up adjacent integers. For example, from_iter first turns the 1002 input integers into four ranges 100..=499, 501..=999, 100..=100, 0..=0. with minimal, constant memory usage, independent of input size. It then sorts and merges these reduced ranges. I wondered if a new from_slice method could speed construction from array-like inputs by quickly finding (some) consecutive integers. For example, could it— with minimal, constant memory — turn the 1002 inputs integers into five Rust ranges: 100..=499, 501..=999, 999..=999, 100..=100, 0..=0. If so, from_iter could then quickly finish the processing. Let’s start by writing is_consecutive with regular Rust: pub const LANES: usize = 16; pub fn is_consecutive_regular(chunk: &[u32; LANES]) – > bool { for i in 1..LANES { if chunk[i – 1].checked_add(1) != Some(chunk[i]) { return false; } } true } The algorithm just loops through the array sequentially, checking that each value is one more than its predecessor. It also avoids overflow. Looping over the items seemed so easy, I wasn’t sure if SIMD could do any better. Here was my first attempt: Splat0 use std::simd::prelude::*; const COMPARISON_VALUE_SPLAT0: Simd = Simd::from_array([15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]); pub fn is_consecutive_splat0(chunk: Simd) – > bool { if chunk[0].overflowing_add(LANES as u32 – 1) != (chunk[LANES – 1], false) { return false; } let added = chunk + COMPARISON_VALUE_SPLAT0; Simd::splat(added[0]) == added } Here is an outline of its calculations: Source: This and all following images by author. It first (needlessly) checks that the first and last items are 15 apart. It then creates added by adding 15 to the 0th item, 14 to the next, etc. Finally, to see if all items in added are the same, it creates a new Simd based on added’s 0th item and then compares. Recall that splat creates a Simd struct from one value. Splat1 & Splat2 When I mentioned the is_consecutive problem to Ben Lichtman, he independently came up with this, Splat1: const COMPARISON_VALUE_SPLAT1: Simd = Simd::from_array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); pub fn is_consecutive_splat1(chunk: Simd) – > bool { let subtracted = chunk – COMPARISON_VALUE_SPLAT1; Simd::splat(chunk[0]) == subtracted } Splat1 subtracts the comparison value from chunk and checks if the result is the same as the first element of chunk, splatted. He also came up with a variation called Splat2 that splats the first element of subtracted rather than chunk. That would seemingly avoid one memory access. I’m sure you are wondering which of these is best, but before we discuss that let’s look at two more candidates. Swizzle Swizzle is like Splat2 but uses simd_swizzle! instead of splat. Macro simd_swizzle! creates a new Simd by rearranging the lanes of an old Simd according to an array of indexes. pub fn is_consecutive_sizzle(chunk: Simd) – > bool { let subtracted = chunk – COMPARISON_VALUE_SPLAT1; simd_swizzle!(subtracted, [0; LANES]) == subtracted } Rotate This one is different. I had high hopes for it. const COMPARISON_VALUE_ROTATE: Simd = Simd::from_array([4294967281, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]); pub fn is_consecutive_rotate(chunk: Simd) – > bool { let rotated = chunk.rotate_elements_right::(); chunk – rotated == COMPARISON_VALUE_ROTATE } The idea is to rotate all the elements one to the right. We then subtract the original chunk from rotated. If the input is consecutive, the result should be “-15” followed by all 1’s. (Using wrapped subtraction, -15 is 4294967281u32.) Now that we have candidates, let’s start to evaluate them. Rule 5: Use Godbolt and AI to understand your code’s assembly, even if you don’t know assembly language. We’ll evaluate the candidates in two ways. First, in this rule, we’ll look at the assembly language generated from our code. Second, in Rule 7, we’ll benchmark the code’s speed. Don’t worry if you don’t know assembly language, you can still get something out of looking at it. The easiest way to see the generated assembly language is with the Compiler Explorer, AKA Godbolt. It works best on short bits of code that don’t use outside crates. It looks like this: Referring to the numbers in the figure above, follow these steps to use Godbolt: Open godbolt.org with your web browser. Add a new source editor. Select Rust as your language. Paste in the code of interest. Make the functions of interest public (pub fn). Do not include a main or unneeded functions. The tool doesn’t support external crates. Add a new compiler. Set the compiler version to nightly. Set options (for now) to -C opt-level=3 -C target-feature=+avx512f. If there are errors, look at the output. If you want to share or save the state of the tool, click “Share” From the image above, you can see that Splat2 and Sizzle are exactly the same, so we can remove Sizzle from consideration. If you open up a copy of my Godbolt session, you’ll also see that most of the functions compile to about the same number of assembly operations. The exceptions are Regular — which is much longer — and Splat0 — which includes the early check. In the assembly, 512-bit registers start with ZMM. 256-bit registers start YMM. 128-bit registers start with XMM. If you want to better understand the generated assembly, use AI tools to generate annotations. For example, here I ask Bing Chat about Splat2: Try different compiler settings, including -C target-feature=+avx2 and then leaving target-feature completely off. Fewer assembly operations don’t necessarily mean faster speed. Looking at the assembly does, however, give us a sanity check that the compiler is at least trying to use SIMD operations, inlining const references, etc. Also, as with Splat1 and Swizzle, it can sometimes let us know when two candidates are the same. You may need disassembly features beyond what Godbolt offers, for example, the ability to work with code the uses external crates. B3NNY recommended the cargo tool cargo-show-asm to me. I tried it and found it reasonably easy to use. The range-set-blaze crate must handle integer types beyond u32. Moreover, we must pick a number of LANES, but we have no reason to think that 16 LANES is always best. To address these needs, in the next rule we’ll generalize the code. Rule 6: Generalize to all types and LANES with in-lined generics, (and when that doesn’t work) macros, and (when that doesn’t work) traits. Let’s first generalize Splat1 with generics. #[inline] pub fn is_consecutive_splat1_gen( chunk: Simd, comparison_value: Simd, ) – > bool where T: SimdElement + PartialEq, Simd: Sub, LaneCount: SupportedLaneCount, { let subtracted = chunk – comparison_value; Simd::splat(chunk[0]) == subtracted } First, note the #[inline] attribute. It’s important for efficiency and we’ll use it on pretty much every one of these small functions. The function defined above, is_consecutive_splat1_gen, looks great except that it needs a second input, called comparison_value, that we have yet to define. If you don’t need a generic const comparison_value, I envy you. You can skip to the next rule if you like. Likewise, if you are reading this in the future and creating a generic const comparison_value is as effortless as having your personal robot do your household chores, then I doubly envy you. We can try to create a comparison_value_splat_gen that is generic and const. Sadly, neither From nor alternative T::One are const, so this doesn’t work: // DOESN’T WORK BECAUSE From is not const pub const fn comparison_value_splat_gen() – > Simd where T: SimdElement + Default + From + AddAssign, LaneCount: SupportedLaneCount, { let mut arr: [T; N] = [T::from(0usize); N]; let mut i_usize = 0; while i_usize { #[inline] pub fn $function(chunk: Simd) – > bool where LaneCount: SupportedLaneCount, { define_comparison_value_splat!(comparison_value_splat, $type); let subtracted = chunk – comparison_value_splat(); Simd::splat(chunk[0]) == subtracted } }; } #[macro_export] macro_rules! define_comparison_value_splat { ($function:ident, $type:ty) = > { pub const fn $function() – > Simd where LaneCount: SupportedLaneCount, { let mut arr: [$type; N] = [0; N]; let mut i = 0; while i bool where Self: SimdElement, Simd: Sub, LaneCount: SupportedLaneCount; } macro_rules! impl_is_consecutive { ($type:ty) = > { impl IsConsecutive for $type { #[inline] // very important fn is_consecutive(chunk: Simd) – > bool where Self: SimdElement, Simd: Sub, LaneCount: SupportedLaneCount, { define_is_consecutive_splat1!(is_consecutive_splat1, $type); is_consecutive_splat1(chunk) } } }; } impl_is_consecutive!(i8); impl_is_consecutive!(i16); impl_is_consecutive!(i32); impl_is_consecutive!(i64); impl_is_consecutive!(isize); impl_is_consecutive!(u8); impl_is_consecutive!(u16); impl_is_consecutive!(u32); impl_is_consecutive!(u64); impl_is_consecutive!(usize); We can now call fully generic code (Rust Playground): // Works on i32 and 16 lanes let a: Simd = black_box(Simd::from_array(array::from_fn(|i| 100 + i as i32))); let ninety_nines: Simd = black_box(Simd::from_array([99; 16])); assert!(IsConsecutive::is_consecutive(a)); assert!(!IsConsecutive::is_consecutive(ninety_nines)); // Works on i8 and 64 lanes let a: Simd = black_box(Simd::from_array(array::from_fn(|i| 10 + i as i8))); let ninety_nines: Simd = black_box(Simd::from_array([99; 64])); assert!(IsConsecutive::is_consecutive(a)); assert!(!IsConsecutive::is_consecutive(ninety_nines)); With this technique, we can create multiple candidate algorithms that are fully generic over type and LANES. Next, it is time to benchmark and see which algorithms are fastest. Those are the first six rules for adding SIMD code to Rust. In Part 2, we look at rules 7 to 9. These rules will cover how to pick an algorithm and set LANES. Also, how to integrate SIMD operations into your existing code and (importantly) how to make it optional. Part 2 concludes with a discussion of when/if you should use SIMD and ideas for improving Rust’s SIMD experience. I hope to see you there. Please follow Carl on Medium. I write on scientific programming in Rust and Python, machine learning, and statistics. I tend to write about one article per month.

Thanks to Ben Lichtman (B3NNY) at the Seattle Rust Meetup for pointing me in the right direction on SIMD.

SIMD (Single Instruction, Multiple Data) operations have been a feature of Intel/AMD and ARM CPUs since the early 2000s. These operations enable you to, for example, add an array of eight i32 to another array of eight i32 with just one CPU operation on a single core. Using SIMD operations greatly speeds up certain tasks. If you’re not using SIMD, you may not be fully using your CPU’s capabilities.

Is this “Yet Another Rust and SIMD” article? Yes and no. Yes, I did apply SIMD to a programming problem and then feel compelled to write an article about it. No, I hope that this article also goes into enough depth that it can guide you through your project. It explains the newly available SIMD capabilities and settings in Rust nightly. It includes a Rust SIMD cheatsheet. It shows how to make your SIMD code generic without leaving safe Rust. It gets you started with tools such as Godbolt and Criterion. Finally, it introduces new cargo commands that make the process easier.


The range-set-blaze crate uses its RangeSetBlaze::from_iter method to ingest potentially long sequences of integers. When the integers are “clumpy”, it can do this 30 times faster than Rust’s standard HashSet::from_iter. Can we do even better if we use Simd operations? Yes!

See this documentation for the definition of “clumpy”. Also, what happens if the integers are not clumpy? RangeSetBlaze is 2 to 3 times slower than HashSet.

On clumpy integers, RangeSetBlaze::from_slice — a new method based on SIMD operations — is 7 times faster than RangeSetBlaze::from_iter. That makes it more than 200 times faster than HashSet::from_iter. (When the integers are not clumpy, it is still 2 to 3 times slower than HashSet.)

Over the course of implementing this speed up, I learned nine rules that can help you accelerate your projects with SIMD operations.

The rules are:

  1. Use nightly Rust and core::simd, Rust’s experimental standard SIMD module.
  2. CCC: Check, Control, and Choose your computer’s SIMD capabilities.
  3. Learn core::simd, but selectively.
  4. Brainstorm candidate algorithms.
  5. Use Godbolt and AI to understand your code’s assembly, even if you don’t know assembly language.
  6. Generalize to all types and LANES with in-lined generics, (and when that doesn’t work) macros, and (when that doesn’t work) traits.

See Part 2 for these rules:

7. Use Criterion benchmarking to pick an algorithm and to discover that LANES should (almost) always be 32 or 64.

8. Integrate your best SIMD algorithm into your project with as_simd, special code for i128/u128, and additional in-context benchmarking.

9. Extricate your best SIMD algorithm from your project (for now) with an optional cargo feature.

Aside: To avoid wishy-washiness, I call these “rules”, but they are, of course, just suggestions.

Rule 1: Use nightly Rust and core::simd, Rust’s experimental standard SIMD module.

Rust can access SIMD operations either via the stable core::arch module or via nighty’s core::simd module. Let’s compare them:

core::arch

core::simd

  • Nightly
  • Delightfully easy and portable.
  • Limits downstream users to nightly.

I decided to go with “easy”. If you decide to take the harder road, starting first with the easier path may still be worthwhile.


In either case, before we try to use SIMD operations in a larger project, let’s make sure we can get them working at all. Here are the steps:

First, create a project called simd_hello:

cargo new simd_hello
cd simd_hello

Edit src/main.rs to contain (Rust playground):

// Tell nightly Rust to enable 'portable_simd'
#![feature(portable_simd)]
use core::simd::prelude::*;

// constant Simd structs
const LANES: usize = 32;
const THIRTEENS: Simd = Simd::::from_array([13; LANES]);
const TWENTYSIXS: Simd = Simd::::from_array([26; LANES]);
const ZEES: Simd = Simd::::from_array([b'Z'; LANES]);

fn main() {
    // create a Simd struct from a slice of LANES bytes
    let mut data = Simd::::from_slice(b"URYYBJBEYQVQBUBCRVGFNYYTBVATJRYY");

    data += THIRTEENS; // add 13 to each byte

    // compare each byte to 'Z', where the byte is greater than 'Z', subtract 26
    let mask = data.simd_gt(ZEES); // compare each byte to 'Z'
    data = mask.select(data - TWENTYSIXS, data);

    let output = String::from_utf8_lossy(data.as_array());
    assert_eq!(output, "HELLOWORLDIDOHOPEITSALLGOINGWELL");
    println!("{}", output);
}

Next — full SIMD capabilities require the nightly version of Rust. Assuming you have Rust installed, install nightly (rustup install nightly). Make sure you have the latest nightly version (rustup update nightly). Finally, set this project to use nightly (rustup override set nightly).

You can now run the program with cargo run. The program applies ROT13 decryption to 32 bytes of upper-case letters. With SIMD, the program can decrypt all 32 bytes simultaneously.

Let’s look at each section of the program to see how it works. It starts with:

#![feature(portable_simd)]
use core::simd::prelude::*;

Rust nightly offers its extra capabilities (or “features”) only on request. The #![feature(portable_simd)] statement requests that Rust nightly make available the new experimental core::simd module. The use statement then imports the module’s most important types and traits.

In the code’s next section, we define useful constants:

const LANES: usize = 32;
const THIRTEENS: Simd = Simd::::from_array([13; LANES]);
const TWENTYSIXS: Simd = Simd::::from_array([26; LANES]);
const ZEES: Simd = Simd::::from_array([b'Z'; LANES]);

The Simd struct is a special kind of Rust array. (It is, for example, always memory aligned.) The constant LANES tells the length of the Simd array. The from_array constructor copies a regular Rust array to create a Simd. In this case, because we want const Simd’s, the arrays we construct from must also be const.

The next two lines copy our encrypted text into data and then adds 13 to each letter.

let mut data = Simd::::from_slice(b"URYYBJBEYQVQBUBCRVGFNYYTBVATJRYY");
data += THIRTEENS;

What if you make an error and your encrypted text isn’t exactly length LANES (32)? Sadly, the compiler won’t tell you. Instead, when you run the program, from_slice will panic. What if the encrypted text contains non-upper-case letters? In this example program, we’ll ignore that possibility.

The += operator does element-wise addition between the Simd data and Simd THIRTEENS. It puts the result in data. Recall that debug builds of regular Rust addition check for overflows. Not so with SIMD. Rust defines SIMD arithmetic operators to always wrap. Values of type u8 wrap after 255.

Coincidentally, Rot13 decryption also requires wrapping, but after ‘Z’ rather than after 255. Here is one approach to coding the needed Rot13 wrapping. It subtracts 26 from any values on beyond ‘Z’.

let mask = data.simd_gt(ZEES);
data = mask.select(data - TWENTYSIXS, data);

This says to find the element-wise places beyond ‘Z’. Then, subtract 26 from all values. At the places of interest, use the subtracted values. At the other places, use the original values. Does subtracting from all values and then using only some seem wasteful? With SIMD, this takes no extra computer time and avoids jumps. This strategy is, thus, efficient and common.

The program ends like so:

let output = String::from_utf8_lossy(data.as_array());
assert_eq!(output, "HELLOWORLDIDOHOPEITSALLGOINGWELL");
println!("{}", output);

Notice the .as_array() method. It safely transmutes a Simd struct into a regular Rust array without copying.

Surprisingly to me, this program runs fine on computers without SIMD extensions. Rust nightly compiles the code to regular (non-SIMD) instructions. But we don’t just want to run “fine”, we want to run faster. That requires us to turn on our computer’s SIMD power.

Rule 2: CCC: Check, Control, and Choose your computer’s SIMD capabilities.

To make SIMD programs run faster on your machine, you must first discover which SIMD extensions your machine supports. If you have an Intel/AMD machine, you can use my simd-detect cargo command.

Run with:

rustup override set nightly
cargo install cargo-simd-detect --force
cargo simd-detect

On my machine, it outputs:

extension       width                   available       enabled
sse2            128-bit/16-bytes        true            true
avx2            256-bit/32-bytes        true            false
avx512f         512-bit/64-bytes        true            false

This says that my machine supports the sse2avx2, and avx512f SIMD extensions. Of those, by default, Rust enables the ubiquitous twenty-year-old sse2 extension.

The SIMD extensions form a hierarchy with avx512f above avx2 above sse2. Enabling a higher-level extension also enables the lower-level extensions.

Most Intel/AMD computers also support the ten-year-old avx2 extension. You enable it by setting an environment variable:

# For Windows Command Prompt
set RUSTFLAGS=-C target-feature=+avx2

# For Unix-like shells (like Bash)
export RUSTFLAGS="-C target-feature=+avx2"

“Force install” and run simd-detect again and you should see that avx2 is enabled.

# Force install every time to see changes to 'enabled'
cargo install cargo-simd-detect --force
cargo simd-detect
extension         width                   available       enabled
sse2            128-bit/16-bytes        true            true
avx2            256-bit/32-bytes        true            true
avx512f         512-bit/64-bytes        true            false

Alternatively, you can turn on every SIMD extension that your machine supports:

# For Windows Command Prompt
set RUSTFLAGS=-C target-cpu=native

# For Unix-like shells (like Bash)
export RUSTFLAGS="-C target-cpu=native"

On my machine this enables avx512f, a newer SIMD extension supported by some Intel computers and a few AMD computers.

You can set SIMD extensions back to their default (sse2 on Intel/AMD) with:

# For Windows Command Prompt
set RUSTFLAGS=

# For Unix-like shells (like Bash)
unset RUSTFLAGS

You may wonder why target-cpu=native isn’t Rust’s default. The problem is that binaries created using avx2 or avx512f won’t run on computers missing those SIMD extensions. So, if you are compiling only for your own use, use target-cpu=native. If, however, you are compiling for others, choose your SIMD extensions thoughtfully and let people know which SIMD extension level you are assuming.

Happily, whatever level of SIMD extension you pick, Rust’s SIMD support is so flexible you can easily change your decision later. Let’s next learn details of programming with SIMD in Rust.

Rule 3: Learn core::simd, but selectively.

To build with Rust’s new core::simd module you should learn selected building blocks. Here is a cheatsheet with the structs, methods, etc., that I’ve found most useful. Each item includes a link to its documentation.

Structs

  • Simd – a special, aligned, fixed-length array of SimdElement. We refer to a position in the array and the element stored at that position as a “lane”. By default, we copy Simd structs rather than reference them.
  • Mask – a special Boolean array showing inclusion/exclusion on a per-lane basis.

SimdElements

  • Floating-Point Types: f32f64
  • Integer Types: i8u8i16u16i32u32i64u64isizeusize
  • — but not i128u128

Simd constructors

  • Simd::from_array – creates a Simd struct by copying a fixed-length array.
  • Simd::from_slice – creates a Simd struct by copying the first LANE elements of a slice.
  • Simd::splat – replicates a single value across all lanes of a Simd struct.
  • slice::as_simd – without copying, safely transmutes a regular slice into an aligned slice of Simd (plus unaligned leftovers).

Simd conversion

  • Simd::as_array – without copying, safely transmutes an Simd struct into a regular array reference.

Simd methods and operators

  • simd[i] – extract a value from a lane of a Simd.
  • simd + simd – performs element-wise addition of two Simd structs. Also, supported -*/%, remainder, bitwise-and, -or, xor, -not, -shift.
  • simd += simd – adds another Simd struct to the current one, in place. Other operators supported, too.
  • Simd::simd_gt – compares two Simd structs, returning a Mask indicating which elements of the first are greater than those of the second. Also, supported simd_ltsimd_lesimd_gesimd_ltsimd_eqsimd_ne.
  • Simd::rotate_elements_left – rotates the elements of a Simd struct to the left by a specified amount. Also, rotate_elements_right.
  • simd_swizzle!(simd, indexes) – rearranges the elements of a Simd struct based on the specified const indexes.
  • simd == simd – checks for equality between two Simd structs, returning a regular bool result.
  • Simd::reduce_and – performs a bitwise AND reduction across all lanes of a Simd struct. Also, supported: reduce_orreduce_xorreduce_maxreduce_minreduce_sum (but noreduce_eq).

Mask methods and operators

  • Mask::select – selects elements from two Simd struct based on a mask.
  • Mask::all – tells if the mask is all true.
  • Mask::any – tells if the mask contains any true.

All about lanes

  • Simd::LANES – a constant indicating the number of elements (lanes) in a Simd struct.
  • SupportedLaneCount – tells the allowed values of LANES. Use by generics.
  • simd.lanes – const method that tells a Simd struct’s number of lanes.

Low-level alignment, offsets, etc.

When possible, use to_simd instead.

More, perhaps of interest

With these building blocks at hand, it’s time to build something.

Rule 4: Brainstorm candidate algorithms.

What do you want to speed up? You won’t know ahead of time which SIMD approach (of any) will work best. You should, therefore, create many algorithms that you can then analyze (Rule 5) and benchmark (Rule 7).

I wanted to speed up range-set-blaze, a crate for manipulating sets of “clumpy” integers. I hoped that creating is_consecutive, a function to detect blocks of consecutive integers, would be useful.

Background: Crate range-set-blaze works on “clumpy” integers. “Clumpy”, here, means that the number of ranges needed to represent the data is small compared to the number of input integers. For example, these 1002 input integers

100, 101, …, 489, 499, 501, 502, …, 998, 999, 999, 100, 0

Ultimately become three Rust ranges:

0..=0, 100..=499, 501..=999.

(Internally, the RangeSetBlaze struct represents a set of integers as a sorted list of disjoint ranges stored in a cache efficient BTreeMap.)

Although the input integers are allowed to be unsorted and redundant, we expect them to often be “nice”. RangeSetBlaze’s from_iter constructor already exploits this expectation by grouping up adjacent integers. For example, from_iter first turns the 1002 input integers into four ranges

100..=499, 501..=999, 100..=100, 0..=0.

with minimal, constant memory usage, independent of input size. It then sorts and merges these reduced ranges.

I wondered if a new from_slice method could speed construction from array-like inputs by quickly finding (some) consecutive integers. For example, could it— with minimal, constant memory — turn the 1002 inputs integers into five Rust ranges:

100..=499, 501..=999, 999..=999, 100..=100, 0..=0.

If so, from_iter could then quickly finish the processing.

Let’s start by writing is_consecutive with regular Rust:

pub const LANES: usize = 16;
pub fn is_consecutive_regular(chunk: &[u32; LANES]) -> bool {
    for i in 1..LANES {
        if chunk[i - 1].checked_add(1) != Some(chunk[i]) {
            return false;
        }
    }
    true
}

The algorithm just loops through the array sequentially, checking that each value is one more than its predecessor. It also avoids overflow.

Looping over the items seemed so easy, I wasn’t sure if SIMD could do any better. Here was my first attempt:

Splat0

use std::simd::prelude::*;

const COMPARISON_VALUE_SPLAT0: Simd =
    Simd::from_array([15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);

pub fn is_consecutive_splat0(chunk: Simd) -> bool {
    if chunk[0].overflowing_add(LANES as u32 - 1) != (chunk[LANES - 1], false) {
        return false;
    }
    let added = chunk + COMPARISON_VALUE_SPLAT0;
    Simd::splat(added[0]) == added
}

Here is an outline of its calculations:

Source: This and all following images by author.

It first (needlessly) checks that the first and last items are 15 apart. It then creates added by adding 15 to the 0th item, 14 to the next, etc. Finally, to see if all items in added are the same, it creates a new Simd based on added’s 0th item and then compares. Recall that splat creates a Simd struct from one value.

Splat1 & Splat2

When I mentioned the is_consecutive problem to Ben Lichtman, he independently came up with this, Splat1:

const COMPARISON_VALUE_SPLAT1: Simd =
    Simd::from_array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);

pub fn is_consecutive_splat1(chunk: Simd) -> bool {
    let subtracted = chunk - COMPARISON_VALUE_SPLAT1;
    Simd::splat(chunk[0]) == subtracted
}

Splat1 subtracts the comparison value from chunk and checks if the result is the same as the first element of chunk, splatted.

He also came up with a variation called Splat2 that splats the first element of subtracted rather than chunk. That would seemingly avoid one memory access.

I’m sure you are wondering which of these is best, but before we discuss that let’s look at two more candidates.

Swizzle

Swizzle is like Splat2 but uses simd_swizzle! instead of splat. Macro simd_swizzle! creates a new Simd by rearranging the lanes of an old Simd according to an array of indexes.

pub fn is_consecutive_sizzle(chunk: Simd) -> bool {
    let subtracted = chunk - COMPARISON_VALUE_SPLAT1;
    simd_swizzle!(subtracted, [0; LANES]) == subtracted
}

Rotate

This one is different. I had high hopes for it.

const COMPARISON_VALUE_ROTATE: Simd =
    Simd::from_array([4294967281, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);

pub fn is_consecutive_rotate(chunk: Simd) -> bool {
    let rotated = chunk.rotate_elements_right::();
    chunk - rotated == COMPARISON_VALUE_ROTATE
}

The idea is to rotate all the elements one to the right. We then subtract the original chunk from rotated. If the input is consecutive, the result should be “-15” followed by all 1’s. (Using wrapped subtraction, -15 is 4294967281u32.)

Now that we have candidates, let’s start to evaluate them.

Rule 5: Use Godbolt and AI to understand your code’s assembly, even if you don’t know assembly language.

We’ll evaluate the candidates in two ways. First, in this rule, we’ll look at the assembly language generated from our code. Second, in Rule 7, we’ll benchmark the code’s speed.

Don’t worry if you don’t know assembly language, you can still get something out of looking at it.

The easiest way to see the generated assembly language is with the Compiler Explorer, AKA Godbolt. It works best on short bits of code that don’t use outside crates. It looks like this:

Referring to the numbers in the figure above, follow these steps to use Godbolt:

  1. Open godbolt.org with your web browser.
  2. Add a new source editor.
  3. Select Rust as your language.
  4. Paste in the code of interest. Make the functions of interest public (pub fn). Do not include a main or unneeded functions. The tool doesn’t support external crates.
  5. Add a new compiler.
  6. Set the compiler version to nightly.
  7. Set options (for now) to -C opt-level=3 -C target-feature=+avx512f.
  8. If there are errors, look at the output.
  9. If you want to share or save the state of the tool, click “Share”

From the image above, you can see that Splat2 and Sizzle are exactly the same, so we can remove Sizzle from consideration. If you open up a copy of my Godbolt session, you’ll also see that most of the functions compile to about the same number of assembly operations. The exceptions are Regular — which is much longer — and Splat0 — which includes the early check.

In the assembly, 512-bit registers start with ZMM. 256-bit registers start YMM. 128-bit registers start with XMM. If you want to better understand the generated assembly, use AI tools to generate annotations. For example, here I ask Bing Chat about Splat2:

Try different compiler settings, including -C target-feature=+avx2 and then leaving target-feature completely off.

Fewer assembly operations don’t necessarily mean faster speed. Looking at the assembly does, however, give us a sanity check that the compiler is at least trying to use SIMD operations, inlining const references, etc. Also, as with Splat1 and Swizzle, it can sometimes let us know when two candidates are the same.

You may need disassembly features beyond what Godbolt offers, for example, the ability to work with code the uses external crates. B3NNY recommended the cargo tool cargo-show-asm to me. I tried it and found it reasonably easy to use.

The range-set-blaze crate must handle integer types beyond u32. Moreover, we must pick a number of LANES, but we have no reason to think that 16 LANES is always best. To address these needs, in the next rule we’ll generalize the code.

Rule 6: Generalize to all types and LANES with in-lined generics, (and when that doesn’t work) macros, and (when that doesn’t work) traits.

Let’s first generalize Splat1 with generics.

#[inline]
pub fn is_consecutive_splat1_gen(
    chunk: Simd,
    comparison_value: Simd,
) -> bool
where
    T: SimdElement + PartialEq,
    Simd: Sub, Output = Simd>,
    LaneCount: SupportedLaneCount,
{
    let subtracted = chunk - comparison_value;
    Simd::splat(chunk[0]) == subtracted
}

First, note the #[inline] attribute. It’s important for efficiency and we’ll use it on pretty much every one of these small functions.

The function defined above, is_consecutive_splat1_gen, looks great except that it needs a second input, called comparison_value, that we have yet to define.

If you don’t need a generic const comparison_value, I envy you. You can skip to the next rule if you like. Likewise, if you are reading this in the future and creating a generic const comparison_value is as effortless as having your personal robot do your household chores, then I doubly envy you.

We can try to create a comparison_value_splat_gen that is generic and const. Sadly, neither From nor alternative T::One are const, so this doesn’t work:

// DOESN'T WORK BECAUSE From is not const
pub const fn comparison_value_splat_gen() -> Simd
where
    T: SimdElement + Default + From + AddAssign,
    LaneCount: SupportedLaneCount,
{
    let mut arr: [T; N] = [T::from(0usize); N];
    let mut i_usize = 0;
    while i_usize < N {
        arr[i_usize] = T::from(i_usize);
        i_usize += 1;
    }
    Simd::from_array(arr)
}

Macros are the last refuge of scoundrels. So, let’s use macros:

#[macro_export]
macro_rules! define_is_consecutive_splat1 {
    ($function:ident, $type:ty) => {
        #[inline]
        pub fn $function(chunk: Simd) -> bool
        where
            LaneCount: SupportedLaneCount,
        {
            define_comparison_value_splat!(comparison_value_splat, $type);

            let subtracted = chunk - comparison_value_splat();
            Simd::splat(chunk[0]) == subtracted
        }
    };
}
#[macro_export]
macro_rules! define_comparison_value_splat {
    ($function:ident, $type:ty) => {
        pub const fn $function() -> Simd
        where
            LaneCount: SupportedLaneCount,
        {
            let mut arr: [$type; N] = [0; N];
            let mut i = 0;
            while i < N {
                arr[i] = i as $type;
                i += 1;
            }
            Simd::from_array(arr)
        }
    };
}

This lets us run on any particular element type and all number of LANES (Rust Playground):

define_is_consecutive_splat1!(is_consecutive_splat1_i32, i32);

let a: Simd = black_box(Simd::from_array(array::from_fn(|i| 100 + i as i32)));
let ninety_nines: Simd = black_box(Simd::from_array([99; 16]));
assert!(is_consecutive_splat1_i32(a));
assert!(!is_consecutive_splat1_i32(ninety_nines));

Sadly, this still isn’t enough for range-set-blaze. It needs to run on all element types (not just one) and (ideally) all LANES (not just one).

Happily, there’s a workaround, that again depends on macros. It also exploits the fact that we only need to support a finite list of types, namely: i8i16i32i64isizeu8u16u32u64, and usize. If you need to also (or instead) support f32 and f64, that’s fine.

If, on the other hand, you need to support i128 and u128, you may be out of luck. The core::simd module doesn’t support them. We’ll see in Rule 8 how range-set-blaze gets around that at a performance cost.

The workaround defines a new trait, here called IsConsecutive. We then use a macro (that calls a macro, that calls a macro) to implement the trait on the 10 types of interest.

pub trait IsConsecutive {
    fn is_consecutive(chunk: Simd) -> bool
    where
        Self: SimdElement,
        Simd: Sub, Output = Simd>,
        LaneCount: SupportedLaneCount;
}

macro_rules! impl_is_consecutive {
    ($type:ty) => {
        impl IsConsecutive for $type {
            #[inline] // very important
            fn is_consecutive(chunk: Simd) -> bool
            where
                Self: SimdElement,
                Simd: Sub, Output = Simd>,
                LaneCount: SupportedLaneCount,
            {
                define_is_consecutive_splat1!(is_consecutive_splat1, $type);
                is_consecutive_splat1(chunk)
            }
        }
    };
}

impl_is_consecutive!(i8);
impl_is_consecutive!(i16);
impl_is_consecutive!(i32);
impl_is_consecutive!(i64);
impl_is_consecutive!(isize);
impl_is_consecutive!(u8);
impl_is_consecutive!(u16);
impl_is_consecutive!(u32);
impl_is_consecutive!(u64);
impl_is_consecutive!(usize);

We can now call fully generic code (Rust Playground):

// Works on i32 and 16 lanes
let a: Simd = black_box(Simd::from_array(array::from_fn(|i| 100 + i as i32)));
let ninety_nines: Simd = black_box(Simd::from_array([99; 16]));

assert!(IsConsecutive::is_consecutive(a));
assert!(!IsConsecutive::is_consecutive(ninety_nines));

// Works on i8 and 64 lanes
let a: Simd = black_box(Simd::from_array(array::from_fn(|i| 10 + i as i8)));
let ninety_nines: Simd = black_box(Simd::from_array([99; 64]));

assert!(IsConsecutive::is_consecutive(a));
assert!(!IsConsecutive::is_consecutive(ninety_nines));

With this technique, we can create multiple candidate algorithms that are fully generic over type and LANES. Next, it is time to benchmark and see which algorithms are fastest.


Those are the first six rules for adding SIMD code to Rust. In Part 2, we look at rules 7 to 9. These rules will cover how to pick an algorithm and set LANES. Also, how to integrate SIMD operations into your existing code and (importantly) how to make it optional. Part 2 concludes with a discussion of when/if you should use SIMD and ideas for improving Rust’s SIMD experience. I hope to see you there.

Please follow Carl on Medium. I write on scientific programming in Rust and Python, machine learning, and statistics. I tend to write about one article per month.

Shape
Shape
Stay Ahead

Explore More Insights

Stay ahead with more perspectives on cutting-edge power, infrastructure, energy,  bitcoin and AI solutions. Explore these articles to uncover strategies and insights shaping the future of industries.

Shape

Nutanix expands beyond HCI

The Pure Storage integration will also be supported within Cisco’s FlashStack offering, creating a “FlashStack with Nutanix” solution with storage provided by Pure, networking capabilities as well as UCS servers from Cisco, and then the common Nutanix Cloud Platform. Cloud Native AOS: Breaking free from hypervisors Another sharp departure from

Read More »

IBM introduces new generation of LinuxOne AI mainframe

In addition to generative AI applications, new multiple model AI approaches are engineered to enhance prediction and accuracy in many industry use cases like advanced fraud detection, image processing and retail automation, according to IBM. LinuxONE Emperor 5 also comes with advanced security features specifically designed for the AI threat

Read More »

Oceaneering Secures Multi-Year GTA Job from BP

Oceaneering International Inc.’s Offshore Projects Group (OPG) has secured a multi-year deal from BP Mauritania Investments Ltd. Oceaneering said in a media release that the contract includes the provision of subsea inspection, maintenance, and repair (IMR) services and remotely operated vehicle (ROV) services in the Greater Tortue Ahmeyim (GTA) field. Oceaneering will provide support for this contract using a multi-purpose vessel equipped with two of its work-class ROVs. The project will also involve management, engineering, and integration services delivered by Oceaneering’s local and international teams. Engineering and pre-mobilization activities have started, and field operations are anticipated to begin in the second quarter of 2025. The contract is initially set for three years, with two additional one-year extension options available. “We believe that our expertise in delivering high-quality subsea solutions in harsh environments, utilizing our advanced products and services, was a key element to winning this contract. We look forward to supporting bp’s operations in this field”, Ben Laura, Oceaneering’s Chief Operating Officer, said. In mid-April, BP loaded the first cargo of liquefied natural gas (LNG) for export from the Greater Tortue Ahmeyim project. The initial shipment of LNG at GTA marks BP’s third major upstream project launch this year, the company said. These projects are among the first of 10 anticipated by the conclusion of 2027, aligning with BP’s strategy to expand its upstream oil and gas operations, it said in a media release announcing the first LNG shipment. GTA stands out as one of Africa’s most significant offshore ventures, hosting gas reserves at depths reaching 2,850 meters (9,350 feet), according to BP. The governments of Mauritania and Senegal have recognized it as “a project of strategic national importance”. Upon full commissioning, GTA Phase 1 is projected to generate approximately 2.4 million tonnes of LNG annually, catering to global energy

Read More »

China Teapots Make Rare Murban Oil Purchases

At least two independent Chinese refiners have made a rare foray into the broader international crude market, snapping up cargoes of Middle Eastern oil for delivery next month. Fuhai Group Co. and Shaanxi Yanchang Petroleum Group each purchased around 1 million barrels of Abu Dhabi’s Murban crude, according to people familiar with the matter who asked not to be identified because the information is private. The trades were handled by international and Chinese firms, they added. The current trading cycle is for crude loaded in July, and any cargoes bought now for June is considered prompt. Traders were mixed on the reason behind the purchase, with some pointing to a supply overhang in the Middle Eastern market – meaning cheaper barrels – and others flagging costlier fuel oil. The two refiners didn’t respond to a request for comment. China’s smaller processors, known as teapots, typically opt for discounted crude from Iran and Russia, and often use fuel oil as a feedstock. However, the dirty fuel is trading at an unusual premium to international benchmarks, while a tax crackdown by Beijing has added to costs. “Straight-run fuel oil is simply not an economic feedstock currently,” said June Goh, a senior oil market analyst at Sparta Commodities in Singapore. “With healthy simple margins, independent refineries in China are taking this opportunity to buy incremental crude to increase run rates.” Around 12 million barrels of heavy fuel oil and residual fuels flowed into China in April, the lowest since September 2023, according to Kpler. Processing rates by teapots in Shandong, meanwhile, have edged higher since the end of February ahead of peak summer demand, OilChem data shows. Fuhai and Yanchang purchased the Murban cargoes at a premium of around $5 a barrel to August ICE Brent futures, traders said. What do you think? We’d love

Read More »

All about All-Energy 2025

The All-Energy conference is set to return to Glasgow this month as it aims to top last year’s record-breaking show. The event, hosted by RX, aims to bring people from across the low-carbon energy sector together for one of the biggest dates in the industry’s calendar this year. All-Energy was initially set to be kicked off by first minister John Swinney. However, due to “an urgent matter”, he will no longer be in attendance. In his place, deputy first minister, Kate Forbes, will join the opening session alongside UK energy minister Michael Shanks, GB Energy chairman Juergen Maier and more as they discuss ‘Britain’s Clean Power Mission’ on 14 May. However, Shanks is also not set to appear in Glasgow due to Parliamentary commitments, instead he will dial in live via the internet. © Erikka Askeland/DCT MediaEnergy Minister Michael Shanks in a recorded message for day two of Floating Offshore Wind conference in Aberdeen. Unlike its contemporaries, All-Energy does not set itself a theme for each outing, instead, it continuously focuses on “Clean Power 2030 and after 2030,” an event spokesperson explained. All-Energy is a two-day event, running Wednesday 14 May and Thursday 15 May, taking place at Glasgow’s SEC. The organisers have also arranged an evening networking get-together at Glasgow Science Centre on the first night. The spokesperson told Energy Voice that it is important that the event touches on “topics for everyone and all the sectors we serve”, these include the move towards net zero, a just energy transition, and grid upgrades, among others. Last year’s conference saw All-Energy’s previous attendance record topped by 21% and although the event’s organisers don’t make predictions on head count, it said that signups for the year were “running 16% above this time last year”. The group behind the UK’s largest renewable

Read More »

Consultations look to energy market future

Paula Kidd and Philip Reid, Partners CMS discuss two major consultations that are poised to affect the energy industry in the UK.    About partnership content Some Energy Voice online content is funded by outside parties. The revenue from this helps to sustain our independent news gathering. You will always know if you are reading paid-for material as it will be clearly labelled as “Partnership” on the site and on social media channels, This can take two different forms. “Presented by”This means the content has been paid for and produced by the named advertiser. “In partnership with”This means the content has been paid for and approved by the named advertiser but written and edited by our own commercial content team. On March 5, two consultations in relation to the future of the energy market in the UK were launched by the UK Government – Oil and Gas Price Mechanism (the “Fiscal Consultation”) and Building the North Sea’s Energy Future (the “DESNZ Consultation”). These consultations have been seeking input from various stakeholders to develop robust frameworks that support economic growth, job security and environmental sustainability. DESNZ consultation The DESNZ Consultation set out the UK Government’s vision for transforming the North Sea into a leading offshore clean energy industry while continuing to manage the increasingly maturing offshore oil and gas industry. The overarching objective of the consultation was stated to be to ensure long-term jobs, growth and investment in North Sea communities. The consultation initially set out key policy considerations and outlined its plans to invest in various clean energy industries including offshore wind, carbon capture, usage and storage (CCUS), and hydrogen. Key initiatives include establishing Great British Energy (headquartered in Aberdeen) to drive clean energy jobs and investment, and supporting the development of floating offshore wind, CCUS and hydrogen projects. The

Read More »

Hornsea 4 cancellation puts pressure on AR7

The UK government has proposed changes to the way it procures offshore wind as it now needs to claw back capacity after the massive Hornsea 4 project ground to a halt. The Department for Energy Security and Net Zero (DESNZ) confirmed changes to the way it will run its contracts for difference (CfD) auctions, starting with the upcoming Allocation Round 7 (AR7), expected this year. Under the reforms, the government would no longer set a monetary budget for the various technologies across the auction, such as the £1.5 billion allocated for offshore wind in AR6, at the start of the auction. Instead, the government would publish a “capacity ambition,” stating instead the amount of power it aims to procure. However, it would still publish a budget for the auction after the process has run. In addition, the reforms envision allowing the secretary of state to see the anonymous bids, including price and capacity. They would use this information to determine how much capacity to procure and to set the final budget. AR7 The amendments will also end flexible bidding for fixed-bottom offshore wind applications. According to the proposals, flexible bids are no longer useful if the auction sets the budget after seeing the bids in advance. Finally, the proposed reforms also considered accelerating the offshore wind part of the auction if developers get their bids in on time and there are no appeals. However, the government said that legislation needed to make change could not be delivered before AR7 – though it did not rule it out for subsequent auctions. © Supplied by OrstedOrsted’s Hornsea One wind farm. It added that the government is exploring non-legislative routes to accelerate a fixed-bottom offshore wind auction in time for AR7. In comments to Energy Voice, Aegir Insights market analyst Signe Tellier Christensen

Read More »

Grid queue: Lay of the land for renewables developers is still unclear

Renewable energy developments can only export the electricity they produce to the grid if they have a grid connection. This has created a large queue of developers waiting for a connection date for their projects, which can extend to over a decade in the future. This backlog is causing significant uncertainty for developers and strain on some renewable projects preventing their construction from being progressed. Once they are in it, developers rarely leave the queue even if they ultimately decide that their project isn’t viable. As the queue currently operates on a “first come, first served” basis, it means that viable and ready-to-build projects can be delayed longer than necessary. To help address these lengthy delays and enable new clean energy projects to secure grid connections, a new grid queue management system is being developed by the National Energy System Operator (NESO). Expected to be introduced this summer, this new system aims to ease the current bottleneck by allocating “confirmed connection dates, connection points and queue positions” to projects which are deemed viable and ready to progress over those which don’t meet its criteria. One of the biggest changes for developers will be demonstrating they have secured land rights to keep their place in the queue when satisfying the milestones known as “gate 2”. While this new initiative will be welcomed across the renewables sector, it raises several issues for project developers to consider including how they negotiate new land agreements. NESO has been clear that nothing short of a signed option agreement will be required for projects to qualify for a grid position under gate 2 – an exclusivity agreement or heads of terms will no longer suffice. Although NESO is clear that only projects that are demonstrably viable will keep their place in the grid connection queue, how

Read More »

Tech CEOs warn Senate: Outdated US power grid threatens AI ambitions

The implications are clear: without dramatic improvements to the US energy infrastructure, the nation’s AI ambitions could be significantly constrained by simple physical limitations – the inability to power the massive computing clusters necessary for advanced AI development and deployment. Streamlining permitting processes The tech executives have offered specific recommendations to address these challenges, with several focusing on the need to dramatically accelerate permitting processes for both energy generation and the transmission infrastructure needed to deliver that power to AI facilities, the report added. Intrator specifically called for efforts “to streamline the permitting process to enable the addition of new sources of generation and the transmission infrastructure to deliver it,” noting that current regulatory frameworks were not designed with the urgent timelines of the AI race in mind. This acceleration would help technology companies build and power the massive data centers needed for AI training and inference, which require enormous amounts of electricity delivered reliably and consistently. Beyond the cloud: bringing AI to everyday devices While much of the testimony focused on large-scale infrastructure needs, AMD CEO Lisa Su emphasized that true AI leadership requires “rapidly building data centers at scale and powering them with reliable, affordable, and clean energy sources.” Su also highlighted the importance of democratizing access to AI technologies: “Moving faster also means moving AI beyond the cloud. To ensure every American benefits, AI must be built into the devices we use every day and made as accessible and dependable as electricity.”

Read More »

Networking errors pose threat to data center reliability

Still, IT and networking issues increased in 2024, according to Uptime Institute. The analysis attributed the rise in outages due to increased IT and network complexity, specifically, change management and misconfigurations. “Particularly with distributed services, cloud services, we find that cascading failures often occur when networking equipment is replicated across an entire network,” Lawrence explained. “Sometimes the failure of one forces traffic to move in one direction, overloading capacity at another data center.” The most common causes of major network-related outages were cited as: Configuration/change management failure: 50% Third-party network provider failure: 34% Hardware failure: 31% Firmware/software error: 26% Line breakages: 17% Malicious cyberattack: 17% Network overload/congestion failure: 13% Corrupted firewall/routing tables issues: 8% Weather-related incident: 7% Configuration/change management issues also attributed for 62% of the most common causes of major IT system-/software-related outages. Change-related disruptions consistently are responsible for software-related outages. Human error continues to be one of the “most persistent challenges in data center operations,” according to Uptime’s analysis. The report found that the biggest cause of these failures is data center staff failing to follow established procedures, which has increased by about 10 percentage points compared to 2023. “These are things that were 100% under our control. I mean, we can’t control when the UPS module fails because it was either poorly manufactured, it had a flaw, or something else. This is 100% under our control,” Brown said. The most common causes of major human error-related outages were reported as:

Read More »

Liquid cooling technologies: reducing data center environmental impact

“Highly optimized cold-plate or one-phase immersion cooling technologies can perform on par with two-phase immersion, making all three liquid-cooling technologies desirable options,” the researchers wrote. Factors to consider There are numerous factors to consider when adopting liquid cooling technologies, according to Microsoft’s researchers. First, they advise performing a full environmental, health, and safety analysis, and end-to-end life cycle impact analysis. “Analyzing the full data center ecosystem to include systems interactions across software, chip, server, rack, tank, and cooling fluids allows decision makers to understand where savings in environmental impacts can be made,” they wrote. It is also important to engage with fluid vendors and regulators early, to understand chemical composition, disposal methods, and compliance risks. And associated socioeconomic, community, and business impacts are equally critical to assess. More specific environmental considerations include ozone depletion and global warming potential; the researchers emphasized that operators should only use fluids with low to zero ozone depletion potential (ODP) values, and not hydrofluorocarbons or carbon dioxide. It is also critical to analyze a fluid’s viscosity (thickness or stickiness), flammability, and overall volatility. And operators should only use fluids with minimal bioaccumulation (the buildup of chemicals in lifeforms, typically in fish) and terrestrial and aquatic toxicity. Finally, once up and running, data center operators should monitor server lifespan and failure rates, tracking performance uptime and adjusting IT refresh rates accordingly.

Read More »

Cisco unveils prototype quantum networking chip

Clock synchronization allows for coordinated time-dependent communications between end points that might be cloud databases or in large global databases that could be sitting across the country or across the world, he said. “We saw recently when we were visiting Lawrence Berkeley Labs where they have all of these data sources such as radio telescopes, optical telescopes, satellites, the James Webb platform. All of these end points are taking snapshots of a piece of space, and they need to synchronize those snapshots to the picosecond level, because you want to detect things like meteorites, something that is moving faster than the rotational speed of planet Earth. So the only way you can detect that quickly is if you synchronize these snapshots at the picosecond level,” Pandey said. For security use cases, the chip can ensure that if an eavesdropper tries to intercept the quantum signals carrying the key, they will likely disturb the state of the qubits, and this disturbance can be detected by the legitimate communicating parties and the link will be dropped, protecting the sender’s data. This feature is typically implemented in a Quantum Key Distribution system. Location information can serve as a critical credential for systems to authenticate control access, Pandey said. The prototype quantum entanglement chip is just part of the research Cisco is doing to accelerate practical quantum computing and the development of future quantum data centers.  The quantum data center that Cisco envisions would have the capability to execute numerous quantum circuits, feature dynamic network interconnection, and utilize various entanglement generation protocols. The idea is to build a network connecting a large number of smaller processors in a controlled environment, the data center warehouse, and provide them as a service to a larger user base, according to Cisco.  The challenges for quantum data center network fabric

Read More »

Zyxel launches 100GbE switch for enterprise networks

Port specifications include: 48 SFP28 ports supporting dual-rate 10GbE/25GbE connectivity 8 QSFP28 ports supporting 100GbE connections Console port for direct management access Layer 3 routing capabilities include static routing with support for access control lists (ACLs) and VLAN segmentation. The switch implements IEEE 802.1Q VLAN tagging, port isolation, and port mirroring for traffic analysis. For link aggregation, the switch supports IEEE 802.3ad for increased throughput and redundancy between switches or servers. Target applications and use cases The CX4800-56F targets multiple deployment scenarios where high-capacity backbone connectivity and flexible port configurations are required. “This will be for service providers initially or large deployments where they need a high capacity backbone to deliver a primarily 10G access layer to the end point,” explains Nguyen. “Now with Wi-Fi 7, more 10G/25G capable POE switches are being powered up and need interconnectivity without the bottleneck. We see this for data centers, campus, MDU (Multi-Dwelling Unit) buildings or community deployments.” Management is handled through Zyxel’s NebulaFlex Pro technology, which supports both standalone configuration and cloud management via the Nebula Control Center (NCC). The switch includes a one-year professional pack license providing IGMP technology and network analytics features. The SFP28 ports maintain backward compatibility between 10G and 25G standards, enabling phased migration paths for organizations transitioning between these speeds.

Read More »

Engineers rush to master new skills for AI-driven data centers

According to the Uptime Institute survey, 57% of data centers are increasing salary spending. Data center job roles that saw the highest increases were in operations management – 49% of data center operators said they saw highest increases in this category – followed by junior and mid-level operations staff at 45%, and senior management and strategy at 35%. Other job categories that saw salary growth were electrical, at 32% and mechanical, at 23%. Organizations are also paying premiums on top of salaries for particular skills and certifications. Foote Partners tracks pay premiums for more than 1,300 certified and non-certified skills for IT jobs in general. The company doesn’t segment the data based on whether the jobs themselves are data center jobs, but it does track 60 skills and certifications related to data center management, including skills such as storage area networking, LAN, and AIOps, and 24 data center-related certificates from Cisco, Juniper, VMware and other organizations. “Five of the eight data center-related skills recording market value gains in cash pay premiums in the last twelve months are all AI-related skills,” says David Foote, chief analyst at Foote Partners. “In fact, they are all among the highest-paying skills for all 723 non-certified skills we report.” These skills bring in 16% to 22% of base salary, he says. AIOps, for example, saw an 11% increase in market value over the past year, now bringing in a premium of 20% over base salary, according to Foote data. MLOps now brings in a 22% premium. “Again, these AI skills have many uses of which the data center is only one,” Foote adds. The percentage increase in the specific subset of these skills in data centers jobs may vary. The Uptime Institute survey suggests that the higher pay is motivating workers to stay in the

Read More »

Microsoft will invest $80B in AI data centers in fiscal 2025

And Microsoft isn’t the only one that is ramping up its investments into AI-enabled data centers. Rival cloud service providers are all investing in either upgrading or opening new data centers to capture a larger chunk of business from developers and users of large language models (LLMs).  In a report published in October 2024, Bloomberg Intelligence estimated that demand for generative AI would push Microsoft, AWS, Google, Oracle, Meta, and Apple would between them devote $200 billion to capex in 2025, up from $110 billion in 2023. Microsoft is one of the biggest spenders, followed closely by Google and AWS, Bloomberg Intelligence said. Its estimate of Microsoft’s capital spending on AI, at $62.4 billion for calendar 2025, is lower than Smith’s claim that the company will invest $80 billion in the fiscal year to June 30, 2025. Both figures, though, are way higher than Microsoft’s 2020 capital expenditure of “just” $17.6 billion. The majority of the increased spending is tied to cloud services and the expansion of AI infrastructure needed to provide compute capacity for OpenAI workloads. Separately, last October Amazon CEO Andy Jassy said his company planned total capex spend of $75 billion in 2024 and even more in 2025, with much of it going to AWS, its cloud computing division.

Read More »

John Deere unveils more autonomous farm machines to address skill labor shortage

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More Self-driving tractors might be the path to self-driving cars. John Deere has revealed a new line of autonomous machines and tech across agriculture, construction and commercial landscaping. The Moline, Illinois-based John Deere has been in business for 187 years, yet it’s been a regular as a non-tech company showing off technology at the big tech trade show in Las Vegas and is back at CES 2025 with more autonomous tractors and other vehicles. This is not something we usually cover, but John Deere has a lot of data that is interesting in the big picture of tech. The message from the company is that there aren’t enough skilled farm laborers to do the work that its customers need. It’s been a challenge for most of the last two decades, said Jahmy Hindman, CTO at John Deere, in a briefing. Much of the tech will come this fall and after that. He noted that the average farmer in the U.S. is over 58 and works 12 to 18 hours a day to grow food for us. And he said the American Farm Bureau Federation estimates there are roughly 2.4 million farm jobs that need to be filled annually; and the agricultural work force continues to shrink. (This is my hint to the anti-immigration crowd). John Deere’s autonomous 9RX Tractor. Farmers can oversee it using an app. While each of these industries experiences their own set of challenges, a commonality across all is skilled labor availability. In construction, about 80% percent of contractors struggle to find skilled labor. And in commercial landscaping, 86% of landscaping business owners can’t find labor to fill open positions, he said. “They have to figure out how to do

Read More »

2025 playbook for enterprise AI success, from agents to evals

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More 2025 is poised to be a pivotal year for enterprise AI. The past year has seen rapid innovation, and this year will see the same. This has made it more critical than ever to revisit your AI strategy to stay competitive and create value for your customers. From scaling AI agents to optimizing costs, here are the five critical areas enterprises should prioritize for their AI strategy this year. 1. Agents: the next generation of automation AI agents are no longer theoretical. In 2025, they’re indispensable tools for enterprises looking to streamline operations and enhance customer interactions. Unlike traditional software, agents powered by large language models (LLMs) can make nuanced decisions, navigate complex multi-step tasks, and integrate seamlessly with tools and APIs. At the start of 2024, agents were not ready for prime time, making frustrating mistakes like hallucinating URLs. They started getting better as frontier large language models themselves improved. “Let me put it this way,” said Sam Witteveen, cofounder of Red Dragon, a company that develops agents for companies, and that recently reviewed the 48 agents it built last year. “Interestingly, the ones that we built at the start of the year, a lot of those worked way better at the end of the year just because the models got better.” Witteveen shared this in the video podcast we filmed to discuss these five big trends in detail. Models are getting better and hallucinating less, and they’re also being trained to do agentic tasks. Another feature that the model providers are researching is a way to use the LLM as a judge, and as models get cheaper (something we’ll cover below), companies can use three or more models to

Read More »

OpenAI’s red teaming innovations define new essentials for security leaders in the AI era

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More OpenAI has taken a more aggressive approach to red teaming than its AI competitors, demonstrating its security teams’ advanced capabilities in two areas: multi-step reinforcement and external red teaming. OpenAI recently released two papers that set a new competitive standard for improving the quality, reliability and safety of AI models in these two techniques and more. The first paper, “OpenAI’s Approach to External Red Teaming for AI Models and Systems,” reports that specialized teams outside the company have proven effective in uncovering vulnerabilities that might otherwise have made it into a released model because in-house testing techniques may have missed them. In the second paper, “Diverse and Effective Red Teaming with Auto-Generated Rewards and Multi-Step Reinforcement Learning,” OpenAI introduces an automated framework that relies on iterative reinforcement learning to generate a broad spectrum of novel, wide-ranging attacks. Going all-in on red teaming pays practical, competitive dividends It’s encouraging to see competitive intensity in red teaming growing among AI companies. When Anthropic released its AI red team guidelines in June of last year, it joined AI providers including Google, Microsoft, Nvidia, OpenAI, and even the U.S.’s National Institute of Standards and Technology (NIST), which all had released red teaming frameworks. Investing heavily in red teaming yields tangible benefits for security leaders in any organization. OpenAI’s paper on external red teaming provides a detailed analysis of how the company strives to create specialized external teams that include cybersecurity and subject matter experts. The goal is to see if knowledgeable external teams can defeat models’ security perimeters and find gaps in their security, biases and controls that prompt-based testing couldn’t find. What makes OpenAI’s recent papers noteworthy is how well they define using human-in-the-middle

Read More »