Sign up for the KDAB Newsletter
Stay on top of the latest news, publications, events and more.
Go to Sign-up


Find what you need - explore our website and developer resources
25 November 2026
Memory allocation has been a concern of software engineers for a very long time. Before malloc there were custom memory allocation solutions such as object pools and custom allocators. Then came libc and the general-purpose malloc(), and since that became the dominant paradigm there has been a never-ending chase for better performance from the system allocator. Take for example Firefox, which replaces malloc() with a "highly customized version" of jemalloc to improve allocation speeds under heavy thread contention.
Replacing and customizing the system allocator can only go so far, however. malloc()is global and general purpose, and that invites some limitations:
malloc() with a corresponding free(). Though effective, these totally general solutions may sometimes be more complex or less performant than the alternative.These problems can be addressed with local allocators. With local allocators, every piece of code which performs memory allocation is given some additional context information (a pointer to the allocator object), enabling the programmer and allocator implementor to make smarter decisions about where and how to allocate memory, depending on the need.
In this blog post, I will cover the features for local allocation provided by the C++ STL and demonstrate what incorporating them into simple programs might look like. I'll provide a list of potential pitfalls and best practices to avoid them. At that point, readers will be equipped to perform most of the simple yet impactful optimizations that pmr (the C++ STL implementation of local allocators) is good for. I will cover more advanced subjects in a future blog post, such as implementing custom allocator-aware generic containers.
This blog will not include benchmarks. I intend primarily to demonstrate the mechanics of the C++ STL implementation of local allocators. But performance is the main reason for many to use local allocators, so here are a few remarks and observations regarding it:
std::pmr::monotonic_buffer_resource in C++) allocate very quickly. For immediate results optimizing simple, single-threaded tasks that make many allocations that don't need to persist after completion (serialization, for example), try an arena.Before beginning, I want to briefly touch on what exactly a memory allocator is and what types you might want to use.
An allocator is an object which takes some memory and then partitions it up for callers who want pieces of it. Types of allocators include:
monotonic_buffer_resources)Each allocator type has different upsides and downsides.
The free list and buddy allocators can allocate arbitrarily sized blocks. They split blocks of memory based on requests, and so they are vulnerable to memory fragmentation. These types of allocators require a "coalescing" process, where adjacent free blocks are joined. That way, large allocations are still possible in places which had previously been allocated into many small pieces. Depending on implementation, allocating may require a linear search through the free list to find a correctly sized block for the request.
This diagram shows how a free list allocator might work in the best case:
Animation demonstrating how a free list allocator allocates and deallocates memory
Block allocators partition up memory into evenly sized blocks. This constraint means allocations have a maximum size, and space may be wasted for smaller allocations (this effect is called internal fragmentation). In exchange, all allocator operations are very simple and constant-time.
Animation demonstrating how a block allocator allocates and deallocates memory
The arena allocator allocates memory in a stack, simply performing an addition to a pointer. Memory before the pointer is considered to be in use, and memory starting at the pointer is free. This means it is impossible to reuse freed memory (arenas usually implement `free()` as a no-op). In exchange, allocation is extremely fast and allocated memory blocks are guaranteed to be nearby each other, and laid out in the order they were allocated.
Animation demonstrating how an arena allocator allocates and deallocates memory
An arena allocator could also be made to allow freeing of the most recent allocation, in which case the name 'stack allocator' may be more specific and accurate.
These allocators may also be combined. For example, the multipool allocator is just a set of block allocators with different sizes (and a slab allocator is similar). Some types of free list allocator, such as the two-level segregated fit allocator, use multiple free lists.
Finally, these allocators may be implemented as threadsafe or singlethreaded. If you know an allocator is only used by one thread, you can employ a non-threadsafe allocator. This may be a huge win for overall speed and maximum latency of allocation and deallocation.
std::pmr namespace and the <memory_resource> headerAllocators have existed since C++98, but have been difficult or impossible to use due to poor ergonomics and the lack of standardization. The STL was designed such that allocators would be specified as template parameters to a container type, something like std::vector<int, my_custom_allocator<int>>. Besides the poor ergonomics, it is important to note that this design introduced a more specific definition of "allocator" than the general definition. An allocator is typically defined as an object which partitions and distributes pieces of memory, but "allocator" in C++ refers specifically to the class of objects which may be passed to the template arguments of containers, like the my_custom_allocator<T> template I just mentioned. These "allocators" are not what we would call allocators, but rather they are handles which each address an allocator. Going forward, I will say specifically "STL allocator" when referring to these types like std::allocator<T> or my_custom_allocator<T>, and otherwise I am referring to the traditional concept of a memory allocator.
In in C++17, the <memory_resource> header was standardized. This header added an abstract class that memory allocators can inherit from and implement, called std::pmr::memory_resource, as well as new STL allocator called std::pmr::polymorphic_allocator. std::pmr::memory_resource requires the implementations of three virtual functions: do_allocate, do_deallocate, and do_is_equal. The polymorphic_allocator is a pointer to an instance of this abstract memory_resourceclass (ie. a pointer to a memory allocator), wrapping it and adding the necessary functionality to be compliant with the requirements for a proper STL allocator. The result is that a container like std::vector<T, std::pmr::polymorphic_allocator<T>> internally contains a pointer to a memory allocator (more specifically, an object that implements std::pmr::memory_resource), which it accesses in place of new or delete. That pointer could point to an arena allocator, a block allocator, a global new/delete allocator, or a custom user-defined allocator. The <memory_resource> header also supplies the functions set_default_resource and get_default_resource in order to provide allocation to a container in the case that no polymorphic_allocator is specified in its constructor. The header additionally includes implementations of multiple memory allocators:
std::pmr::monotonic_buffer_resourcestd::pmr::unsynchronized_pool_resource (and its threadsafe variant, std::pmr::synchronized_pool_resource)Finally, the pmr namespace contains aliases for STL containers. They look something like this:
namespace std::pmr {
template <typename T>
using vector = std::vector<T, polymorphic_allocator<T>>;
} memory_resources, traditional allocators, and STL allocatorsThe difference between std::pmr::memory_resource and std::pmr::polymorphic_allocatorand friends is not very intuitive. I would like to further belabor this explanation in the hopes that different approaches will help it to click with more people. Let's start with memory_resource, because it is the most obvious:
"Memory resource" is the name the C++ standards committee has chosen for what most people call a memory allocator. It is an object which owns a chunk of memory, and accepts requests for partitions of that memory. std::pmr::memory_resource is the interface that such an object should implement, in order to work with the rest of the STL.
So, why did they choose to call it a memory resource, and not an allocator? Because the name "allocator" had already been used by the language to mean something else. What is that?
The allocator requirements provide the definition. Notably, they specify that an allocator must be copyable, moveable, and equality comparable. However, copying an allocator (a traditional allocator, as we understand them) does not make sense, because an allocator owns memory that we have pointers or references to. The memory of an allocator may contain pointers to itself, as well. Additionally, how and why would you ever compare two allocators? Even if you bytewise compared them, the same bytes in an allocator may mean something different at a different memory location.
The answer is that std::allocator, and anything else the standard calls an "allocator," is not by-value storage of an allocator. Rather, it is a handle, which provides some method of addressing the actual allocator, which is stored somewhere else. So maybe a STL allocator is a pointer, a shared pointer, an integer ID, or something else. For a more in depth explanation, see Arthur O'Dwyer's CppCon2018 talk, "An allocator is a handle to a heap".
Given what we know, take a look at these simplified versions of std::pmr::memory_resource and std::pmr::polymorphic_allocator:
struct memory_resource
{
virtual void* do_allocate(size_t bytes, size_t align) = 0;
virtual void do_deallocate(void* memory, size_t bytes, size_t align) = 0;
};
template <typename T>
struct polymorphic_allocator
{
memory_resource* ptr = std::pmr::get_default_resource();
polymorphic_allocator(memory_resource* mr) : ptr(mr) {}
T* allocate()
{
return static_cast<T*>(ptr->do_allocate(sizeof(T), alignof(T)));
}
void deallocate(T* object)
{
ptr->do_deallocate(object, sizeof(T), alignof(T));
}
}; Notice that a polymorphic_allocator even implicitly constructs from a memory_resource*. So, for conciseness, you can avoid ever constructing or really dealing with a polymorphic_allocator and instead pass memory_resource* to the constructors of allocator-aware containers. The downside is that you will lose out on some convenient member functions available on std::pmr::polymorphic_allocator for allocating memory manually.
One final clarification: if I say a container "has" and allocator or is "using" an allocator, that means that its polymorphic_allocator is pointing to that allocator. If I say two containers have the same allocator, I mean that they will each end up allocating from the same pool of memory.
To practice applying allocators, let's add a few of them to this simple example:
// A program which generates many random sentences and then sorts them alphabetically
std::string randomWord(size_t wordLength)
{
std::string out;
for (size_t i = 0; i < wordLength; ++i) {
constexpr uint8_t start = 'a';
constexpr uint8_t numLetters = ('z' - start) + 1;
out.push_back(char((rand() % numLetters) + start));
}
return out;
}
std::list<std::string> randomSentence(size_t numWords)
{
std::list<std::string> out;
for (size_t i = 0; i < numWords; ++i)
out.emplace_back(randomWord((rand() % 10) + 15) + " ");
return out;
}
int main()
{
constexpr size_t numSentences = 5000000;
std::vector<std::list<std::string>> sentences;
srand(42);
for (size_t i = 0; i < numSentences; ++i)
sentences.emplace_back(randomSentence((rand() % 15) + 5));
std::stable_sort(sentences.begin(), sentences.end());
std::string lastSentenceJoined = std::accumulate(
sentences.back().begin(), sentences.back().end(), std::string{});
std::printf("Last sentence alphabetically: %s\n", lastSentenceJoined.c_str());
} Note the different types of allocation in this program, from top to bottom:
std::stringallocations and reallocations in randomWord()randomSentence(), no reallocationmain() for the sentences vectorInterestingly, I do not call .reserve() in randomWord() in order to remove temporary allocations. I found that to actually worsen performance slightly with this program, regardless of the allocator. (Always profile, right?)
Running the program, I get the following output:
Last sentence alphabetically: zzzzusslypcugzacuchocbl ghmojccoybpjptwld elitxsybwusezdvjwuuk hfxosxxsasomuanvrskilu uypkgyrcxrkjfik mpwtoritoexuoezxey qdadywsquoxeeuhnpg legucxktyokhrmrelrovr pwlviepruvncdbgt jfcjbthjwndwxkdcuxophky ljwulcqrnwesihtleoetocv xhuzqiuiqtrmjaxbw dtvomfnbvxsbtqndeblb bnxpfgrjyhuemyxbvgr tgoxwqntiolmgedajnqnijnl naelauomoggyjdt Lexographically lesser incomprehensible garbage. Perfect.
Let's start by making everything use std::pmr, but not create any memory resources. The resulting program should still perform allocations in the same way, thanks to the default new/delete resource. Here's our new code:
// A program which generates many random sentences and then sorts them alphabetically
std::pmr::string randomWord(size_t wordLength)
{
std::pmr::string out;
for (size_t i = 0; i < wordLength; ++i) {
constexpr uint8_t start = 'a';
constexpr uint8_t numLetters = ('z' - start) + 1;
out.push_back(char((rand() % numLetters) + start));
}
return out;
}
std::pmr::list<std::pmr::string> randomSentence(size_t numWords)
{
std::pmr::list<std::pmr::string> out;
for (size_t i = 0; i < numWords; ++i)
out.emplace_back(randomWord((rand() % 10) + 15) + " ");
return out;
}
int main()
{
constexpr size_t numSentences = 5000000;
std::pmr::vector<std::pmr::list<std::pmr::string>> sentences;
srand(42);
for (size_t i = 0; i < numSentences; ++i)
sentences.emplace_back(randomSentence((rand() % 15) + 5));
std::stable_sort(sentences.begin(), sentences.end());
std::pmr::string lastSentenceJoined = std::accumulate(sentences.back().begin(), sentences.back().end(), std::pmr::string{});
std::printf("Last sentence alphabetically: %s\n", lastSentenceJoined.c_str());
} All I did was replace std:: with std::pmr:: before the relevant containers. The output is still the same.
Let's try a different type of allocator, set globally using set_default_resource. I just add the following code to the top of main:
std::pmr::monotonic_buffer_resource arena;
std::pmr::set_default_resource(&arena); This seems to have cut about a second off of the original nine second long execution time, likely due to increased allocation speeds.
Next, let's demonstrate passing allocators around the proper pmr way. So far, we have not really been using local allocators, as we just stored the allocator in a global variable. I'll change that by removing set_default_resource and pass the monotonic_buffer_resource around manually. First, I need to change the main function to pass the allocator into the sentences constructor instead:
int main()
{
std::pmr::monotonic_buffer_resource arena;
constexpr size_t numSentences = 5000000;
std::pmr::vector<std::pmr::list<std::pmr::string>> sentences{&arena};
// ... Now all allocations within sentences will come from the arena . There is a mechanism implemented by STL containers to pass allocators into nested containers. Stay tuned for a future blog post where I will cover how to implement that for your own types.
After this, performance has worsened again, back to nine seconds. A good guess as to why this is happening is that randomSentence() is doing most of the allocation and work, but it has no way of knowing about our monotonic_buffer_resource . It is back to using new/delete now.
Additionally, when we return from randomSentence, we have to emplace_back into the sentences vector. But sentencesuses our monotonic_buffer_resource , not new/delete, so it has to do a copy from one allocator to another. Yes, that's right, this move construction actually copies memory (and can throw!):
sentences.emplace_back(randomSentence((rand() % 15) + 5)); Let's try giving randomSentence the arena allocator directly, so it can build the list<string> in it, instead of copying at the end. We can change the first few lines of randomSentence to look like this:
std::pmr::list<std::pmr::string>
randomSentence(std::pmr::polymorphic_allocator<> allocator, size_t numWords)
{
std::pmr::list<std::pmr::string> out{allocator};
// ... And we just pass in the polymorphic allocator arena when we call it from main:
sentences.emplace_back(&arena, randomSentence((rand() % 15) + 5)); And now we go back to the same performance as when arena was the default resource.
But wait, in our current setup, we still have a copy from one allocator to another, and our performance seems fine. The exact same thing I just described when returning from randomSentence into main also happens when returning from randomWord into randomSentence:
std::pmr::string randomWord(size_t wordLength)
{
// we build a string using the new/delete resource
std::pmr::string out;
for (size_t i = 0; i < wordLength; ++i) {
constexpr uint8_t start = 'a';
constexpr uint8_t numLetters = ('z' - start) + 1;
out.push_back(char((rand() % numLetters) + start));
}
// we return a string which still has a pointer to the new/delete resource
return out;
}
std::pmr::list<std::pmr::string>
randomSentence(std::pmr::polymorphic_allocator<> allocator, size_t numWords)
{
std::pmr::list<std::pmr::string> out{allocator};
for (size_t i = 0; i < numWords; ++i)
// right here, we have to copy the characters from randomWord into a piece
// of memory allocated by `allocator`, since that's what the `out` string
// uses.
out.emplace_back(randomWord((rand() % 10) + 15) + " ");
return out;
} Whether to leave it as-is or to pass in the allocator to randomWord is up in the air as it seems to have no performance benefit. But I will take advantage of this to demonstrate another tool available to anyone using local allocators: the temporary allocator. I will create a new memory resource, just to pass into randomWord(). Since I only use it for the temporary allocations and reallocations of the string there, I will call it the tempArena :
std::pmr::string
randomWord(std::pmr::polymorphic_allocator<> allocator, size_t wordLength)
{
std::pmr::string out{allocator};
for (size_t i = 0; i < wordLength; ++i) {
constexpr uint8_t start = 'a';
constexpr uint8_t numLetters = ('z' - start) + 1;
out.push_back(char((rand() % numLetters) + start));
}
return out;
}
std::pmr::list<std::pmr::string>
randomSentence(std::pmr::polymorphic_allocator<> allocator, size_t numWords)
{
std::pmr::list<std::pmr::string> out{allocator};
std::pmr::monotonic_buffer_resource tempArena; // this is new!
for (size_t i = 0; i < numWords; ++i)
// pass `tempArena` as what `randomWord()` should allocate with, but
// copy it out into a container that uses `allocator` instead, so we can
// return it out of this function.
out.emplace_back(randomWord(&tempArena, (rand() % 10) + 15) + " ");
return out;
} This doesn't affect the execution time or output of the program. However, it does show an interesting technique. An arena is used for a task that reallocates (randomWord), and then only the final bytes which were actually used are copied out into randomSentence's allocator. By this process, the space potentially lost from reallocating the out string over and over in randomWord has been recovered.
There is a major caveat here: only do this with std::pmrcontainers! More generally: only do this with allocator-aware containers. The technique behind std::pmr is storing a pointer to a memory_resource. Just like any other pointer in C++, it is possible for it to dangle. Containers that are not allocator aware will not correctly change their allocator and move the data from tempArena to the allocator in the above function. Instead, those containers will keep their original allocator (when moved) or else use the default resource (when copied). I cover this caveat and how to avoid it in the "The danger of different allocators" section.
Indeed, this temporary allocator technique even violates my #1 safety recommendation in the following section. Remember that the way pmr works is to store raw pointers to your memory_resources. If the lifetime of the memory_resource and the data allocated inside it is not clear and easily enforced, then it is safer to just avoid the temporary allocator and either use the default resource or one passed in to a function by the caller.
Another good way to avoid this is to just use the default resource as your temporary allocator, or even use non-pmr containers to do your temporary allocation, and then copy into a pmr containers afterwards. This makes a lot of sense if your main goal using allocators is to avoid fragmentation or dispersion of more long-term allocations.
The concern with allocators is use-after-free. Here I will cover some best practices and the corresponding pitfalls they prevent.
1. Rarely create memory_resources. If possible, accept a polymorphic_allocator instead. This puts the responsibility of ensuring the allocator is freed correctly on the caller. To demonstrate, here is an example of an error that I could have written earlier, in the example program:
std::pmr::string randomWord(size_t wordLength)
{
std::pmr::monotonic_buffer_resource tempArena;
std::pmr::string out{&tempArena};
for (size_t i = 0; i < wordLength; ++i) {
constexpr uint8_t start = 'a';
constexpr uint8_t numLetters = ('z' - start) + 1;
out.push_back(char((rand() % numLetters) + start));
}
// Undefined behavior: this returns the string `out`, which contains a
// pointer to a stack-local variable `tempArena`, as well as memory
// allocated from it.
return out;
} The actual signature of randomWord in the working program was:
std::pmr::string
randomWord(std::pmr::polymorphic_allocator<> allocator, size_t wordLength); Using the allocator argument in the function for our string was an easy way to make sure the allocated memory remained valid out into the caller's scope.
2. Always try to give your memory_resources obvious lifetimes. One of the simplest cases is instantiating a memory_resource at the start of a function, doing work with it, and destroying it at the end. An example of a confusing usage of a memory_resource would be trying to make an object factory with a memory_resource member variable:
class FooFactory
{
private:
std::pmr::monotonic_buffer_resource m_resource;
std::pmr::polymorphic_allocator<std::byte> m_allocator{&m_resource};
public:
void configureFooField(int num);
// this new_object() member function is C++20 only, included for brevity
Foo* makeFoo() { return m_allocator.new_object<Foo>(); }
// though it is not obvious to the caller, all Foo*s MUST no longer be in
// use when this object is destroyed, otherwise that is use-after-free.
~FooFactory() = default;
}; A partial fix or improvement we could make is to use practice #1, and accept a polymorphic_allocator in the constructor. This makes it more clear that this object and all of its subobjects are freed at the same time:
explicit FooFactory(std::pmr::polymorphic_allocator<std::byte> a)
: m_allocator(a)
{} From the caller's perspective, using the FooFactory API now includes instantiating a memory resource, which indicates the common lifetime:
{
// BEFORE...
FooFactory factory;
factory.configureFooField(42);
Foo* myFoo = factory.makeFoo();
return myFoo; // use-after-free when someone else dereferences this...
}
{
// AFTER...
std::pmr::monotonic_buffer_resource arena;
FooFactory factory{&arena};
factory.configureFooField(42);
Foo* myFoo = factory.makeFoo();
// hm... I probably shouldn't do this, since `factory` uses the `arena`.
// Maybe if the caller wants to access this `Foo*`, they should pass me a
// polymorphic_allocator, which I can give to the `FooFactory`, as was
// recommended in best practice #1?
// - The person writing this
return myFoo;
} 3. Avoid .release(). Think of it like a naked call to delete. It's always preferable to let RAII handle releasing memory, and get the advantage of correct destructor call order.
std::pmr::vector<std::pmr::vector<std::pmr::string>> spreadsheet;
std::pmr::monotonic_buffer_resource tempArena;
for (size_t x = 0; x < dimensions.x; ++x) {
std::pmr::vector<std::pmr::string> column{&tempArena};
for (size_t y = 0; y < dimensions.y; ++y) {
std::pmr::string tempString{&tempArena};
fillLineForSpreadsheetCell(tempString, x, y); // hypothetical function
column.emplace_back(std::move(tempString));
// Undefined behavior: got too greedy with memory usage optimization, called this too
// early, now `column` is a dangling reference
tempArena.release();
}
spreadsheet.push_back(std::move(column));
} Versus the version without a call to .release(), simply moving the memory resource into the block where it should be reset:
std::pmr::vector<std::pmr::vector<std::pmr::string>> spreadsheet;
for (size_t x = 0; x < dimensions.x; ++x) {
std::pmr::monotonic_buffer_resource tempArena; // no need to call .release(), this gets destroyed at the right time
auto column = std::pmr::vector<std::pmr::string>{&tempArena};
for (size_t y = 0; y < dimensions.y; ++x) {
std::pmr::string tempString{&tempArena};
fillLineForSpreadsheetCell(tempString, x, y); // hypothetical function
column.emplace_back(std::move(tempString));
}
spreadsheet.push_back(std::move(column));
} Unfortunately .release() frees everything from the backing allocator, so you do not get to re-use buffers allocated within the arena after a call to .release(). On the bright side, that means that .release() is not more performant than the allocator going out of scope, so there's no downside to following this safety advice.
4. It is especially important to avoid static variables in function scope when using pmr. Otherwise you may initialize something the first time you call a function, maybe some static const std::pmr::vector<int> ints{localAllocator};, and then it will store that pointer that was inside localAllocator until the end of the program, and then try to dereference it, in order to free its own memory. Function-scoped static breaks the symmetrical call order of constructors and destructors under RAII.
void myFunction(std::pmr::polymorphic_allocator<> allocator) {
// just don't do this, please.
static const std::pmr::anything_pmr_at_all varname{allocator};
} Most of the time, data can and should stay within a single allocator. Ideally a function or object that uses an allocator will create one single memory_resource at startup and then destroy it at shutdown. However, there is sometimes a need for data to move between containers with different allocators: namely, copying data out of a container that uses a temporary allocator. Unfortunately, C++ makes this process of copying from one allocator to another largely implicit. It can be difficult to reason about what allocator a given object should have (and even worse if you account for different stateful allocators besides std::pmr::polymorphic_allocator). There are two main dangers here:
std::shared_ptr,out of a function using a temporary allocator. When a pointer or copy of the pointer is destroyed, it will dereference a dangling pointer to the temporary allocator.std::pmr::get_default_resource(). Later, you use a standard algorithm on this container and another with different allocators. The standard algorithm invokes std::swap. std::swap on two containers with different allocators is undefined behavior.To avoid these issues, you have a few options:
std::swap yourself, on anything pmr related (including structs and classes containing pmr types).allocate_shared to create shared pointers with allocators. Avoiding this same problem with unique_ptris easy. It already doesn't work with allocators out of the box. Besides, shared_ptr and unique_ptrdon't usually make sense with allocators. The allocator itself can bound the lifetime of the object.In this blog we covered a lot:
- What an allocator is, and types of allocators (free-list, block, slab, and arena)
- The benefits of local allocators (cache locality and allocation speed)
- The types and functions provided by the <memory_resource> header
- How to pass around a memory resource into functions and std::pmr containers
- Remember: nested std::pmr containers all share the same allocator
- What happens when you move from one container to another with a different allocator
- Temporary allocators
- Safety best practices
Hopefully some of it stuck with you, and added a new optimization tool to your tool belt. If there's one part that I hope you took away from this, it's this:
> Arena allocators (std::pmr::monotonic_buffer_resource in C++) allocate very quickly. For immediate results optimizing simple, single-threaded tasks that make many allocations that don't need to persist after completion (serialization, for example) use an arena.
Lots of simple, serial tasks done by a single thread are using new`/`delete when they really don't have to be. They just build up a data structure and then immediately destroy it. Optimizing these with arenas is very effective and very simple to do.
In the next blog post, I'll go into more depth on how allocator aware containers work and the protocol they implement for passing allocators between each other. Additionally, I'll cover using arenas as an RAII replacement, similar to recent C-like systems languages such as Zig, Odin, and Jai.