* Copyright (c) Huawei Technologies Co., Ltd. 2026.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
#pragma once
#include <acl/acl.h>
#include <cmath>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <vector>
#include "detail/dynamic_map/kernels.h"
#include "detail/storages/arg_storage.h"
#include "static_map.h"
#include "tiling/platform/platform_ascendc.h"
namespace aclco
{
template <class Key, class T, class Extent = aclco::Extent<size_t>, class KeyEqual = aclco::EqualTo<Key>,
class ProbingScheme = aclco::LinearProbing<aclco::murmurhash3_32<Key>>,
class Storage = aclco::Storage<defaultMapBucketSize>>
class DynamicMap
{
public:
using MapType = aclco::StaticMap<Key, T, Extent, KeyEqual, ProbingScheme, Storage>;
using SizeType = typename MapType::SizeType;
using KeyType = Key;
using ValueType = T;
enum class InsertMode
{
kExactDedup,
kAppendUnique
};
static constexpr SizeType DEFAULT_MIN_INSERT = 10000;
static constexpr float DEFAULT_MAX_LOAD = 0.60f;
static constexpr SizeType GROWTH_FACTOR = 2;
static constexpr SizeType INSERT_SUBBATCH = 800000;
DynamicMap(const DynamicMap&) = delete;
DynamicMap& operator=(const DynamicMap&) = delete;
DynamicMap(DynamicMap&&) = default;
DynamicMap& operator=(DynamicMap&&) = default;
~DynamicMap() = default;
DynamicMap(Extent initialCapacity, Key emptyKey, T emptyValue, Key erasedKey, KeyEqual const& pred = {},
ProbingScheme const& ps = {}, Storage storage = {}, aclrtStream stream = nullptr)
: size_(0),
minInsertSize_(DEFAULT_MIN_INSERT),
maxLoadFactor_(DEFAULT_MAX_LOAD),
emptyKey_(emptyKey),
emptyValue_(emptyValue),
erasedKey_(erasedKey),
pred_(pred),
probingScheme_(ps),
storage_(storage)
{
if (emptyKey == erasedKey)
{
throw std::invalid_argument("DynamicMap: emptyKey and erasedKey must differ");
}
submaps_.push_back(std::make_unique<MapType>(initialCapacity, emptyKey, emptyValue, pred, ps, storage, stream));
submaps_.back()->SetErasedKey(erasedKey_, stream);
submapSize_.push_back(0);
totalCapacity_ = submaps_.back()->Capacity();
nextCapacity_ = static_cast<SizeType>(initialCapacity) * GROWTH_FACTOR;
void* p = nullptr;
CheckRet(aclrtMalloc(&p, sizeof(T), ACL_MEM_MALLOC_HUGE_FIRST), "DynamicMap::ctor::aclrtMalloc");
CheckRet(aclrtMemcpy(p, sizeof(T), &emptyValue_, sizeof(T), ACL_MEMCPY_HOST_TO_DEVICE),
"DynamicMap::ctor::aclrtMemcpy");
dEmptyValue_.reset(p);
aivCoreNum_ = static_cast<uint32_t>(platform_ascendc::PlatformAscendCManager::GetInstance()->GetCoreNumAiv());
if (aivCoreNum_ == 0) aivCoreNum_ = 1;
aclrtStream prepS = nullptr;
aclrtEvent prepE = nullptr;
if (aclrtCreateStream(&prepS) == ACL_SUCCESS && aclrtCreateEvent(&prepE) == ACL_SUCCESS)
{
prepStreamHolder_.reset(prepS);
prepEventHolder_.reset(prepE);
prepStream_ = prepS;
prepEvent_ = prepE;
}
else if (prepS != nullptr)
{
aclrtDestroyStream(prepS);
}
}
SizeType Size() const noexcept { return size_; }
SizeType Capacity() const noexcept { return totalCapacity_; }
size_t NumSubmaps() const noexcept { return submaps_.size(); }
void Reserve(SizeType n, aclrtStream stream)
{
SizeType remaining = n;
size_t idx = 0;
while (remaining > 0)
{
SizeType cap;
if (idx < submaps_.size())
{
cap = submaps_[idx]->Capacity();
}
else
{
cap = nextCapacity_;
submaps_.push_back(std::make_unique<MapType>(Extent{cap}, emptyKey_, emptyValue_, pred_, probingScheme_,
storage_, stream));
submaps_.back()->SetErasedKey(erasedKey_, stream);
submapSize_.push_back(0);
totalCapacity_ += submaps_.back()->Capacity();
nextCapacity_ = cap * GROWTH_FACTOR;
}
SizeType usable = Usable(cap);
if (usable >= remaining) break;
remaining -= usable;
++idx;
}
}
SizeType Insert(void* values, Extent valueNum, aclrtStream stream)
{
return Insert(values, valueNum, stream, InsertMode::kExactDedup);
}
SizeType Insert(void* values, Extent valueNum, aclrtStream stream, InsertMode mode)
{
SizeType n = static_cast<SizeType>(valueNum);
if (n == 0 || values == nullptr) return 0;
EnsureActiveRoom(n, stream);
size_t a = ActiveIdx();
bool appendUnique = (mode == InsertMode::kAppendUnique);
bool fast = appendUnique || !HasNonEmptyBefore(a);
if (fast)
{
if (appendUnique)
{
for (SizeType off = 0; off < n; off += INSERT_SUBBATCH)
{
SizeType cur = (n - off < INSERT_SUBBATCH) ? (n - off) : INSERT_SUBBATCH;
submaps_[a]->InsertAsync((uint8_t*)values + static_cast<size_t>(off) * sizeof(Pair<Key, T>),
Extent{cur}, stream);
}
submapSize_[a] += n;
size_ += n;
return n;
}
SizeType failed = submaps_[a]->Insert(values, Extent{n}, stream);
SizeType ins = (n >= failed) ? (n - failed) : 0;
submapSize_[a] += ins;
size_ += ins;
return ins;
}
SizeType total = 0, offset = 0;
while (offset < n)
{
SizeType room = ActiveRoom();
if (room == 0)
{
GrowOneSubmap(n - offset, stream);
continue;
}
if (room < (n - offset) * 2) StartPrepareNext(n - offset);
SizeType chunk = (n - offset < room) ? (n - offset) : room;
total += InsertChunk((uint8_t*)values + static_cast<size_t>(offset) * sizeof(Pair<Key, T>), chunk, stream);
offset += chunk;
}
return total;
}
SizeType InsertAsync(void* values, Extent valueNum, aclrtStream stream)
{
SizeType n = static_cast<SizeType>(valueNum);
if (n == 0 || values == nullptr) return 0;
EnsureActiveRoom(n, stream);
if (ActiveRoom() < n * 2) StartPrepareNext(n);
size_t a = ActiveIdx();
submaps_[a]->InsertAsync(values, Extent{n}, stream);
submapSize_[a] += n;
size_ += n;
return n;
}
SizeType InsertOrAssign(void* values, Extent valueNum, aclrtStream stream)
{
SizeType n = static_cast<SizeType>(valueNum);
if (n == 0 || values == nullptr) return 0;
EnsureActiveRoom(n, stream);
SizeType total = 0, offset = 0;
while (offset < n)
{
SizeType room = ActiveRoom();
if (room == 0)
{
GrowOneSubmap(n - offset, stream);
continue;
}
if (room < (n - offset) * 2) StartPrepareNext(n - offset);
SizeType chunk = (n - offset < room) ? (n - offset) : room;
total += InsertOrAssignChunk((uint8_t*)values + static_cast<size_t>(offset) * sizeof(Pair<Key, T>), chunk,
stream);
offset += chunk;
}
return total;
}
void Find(void* keys, void* outputValues, Extent keyNum, aclrtStream stream)
{
SizeType n = static_cast<SizeType>(keyNum);
if (n == 0 || keys == nullptr || outputValues == nullptr) return;
size_t base = FirstNonEmpty();
if (base == submaps_.size())
{
submaps_[0]->Find(keys, outputValues, n, stream);
return;
}
submaps_[base]->Find(keys, outputValues, n, stream);
if (!HasMoreNonEmptyAfter(base)) return;
EnsureScratch(static_cast<size_t>(n) * sizeof(T));
for (size_t s = base + 1; s < submaps_.size(); ++s)
{
if (submapSize_[s] == 0) continue;
submaps_[s]->Find(keys, dScratch_.get(), n, stream);
aclco::MergeFind<T><<<aivCoreNum_, 0, stream>>>((uint8_t*)outputValues, (uint8_t*)dScratch_.get(),
(uint8_t*)dEmptyValue_.get(), static_cast<uint32_t>(n));
}
}
void Contains(void* keys, void* outputValues, Extent keyNum, aclrtStream stream)
{
SizeType n = static_cast<SizeType>(keyNum);
if (n == 0 || keys == nullptr || outputValues == nullptr) return;
size_t base = FirstNonEmpty();
if (base == submaps_.size())
{
submaps_[0]->Contains(keys, outputValues, n, stream);
return;
}
submaps_[base]->Contains(keys, outputValues, n, stream);
if (!HasMoreNonEmptyAfter(base)) return;
EnsureScratch(static_cast<size_t>(n));
for (size_t s = base + 1; s < submaps_.size(); ++s)
{
if (submapSize_[s] == 0) continue;
submaps_[s]->Contains(keys, dScratch_.get(), n, stream);
aclco::MergeContains<><<<aivCoreNum_, 0, stream>>>((uint8_t*)outputValues, (uint8_t*)dScratch_.get(),
static_cast<uint32_t>(n));
}
}
SizeType Erase(void* keys, Extent keyNum, aclrtStream stream)
{
SizeType n = static_cast<SizeType>(keyNum);
if (n == 0 || keys == nullptr) return 0;
SizeType total = 0;
for (size_t s = 0; s < submaps_.size(); ++s)
{
if (submapSize_[s] == 0) continue;
SizeType failed = submaps_[s]->Erase(keys, n, stream);
SizeType del = n - failed;
submapSize_[s] -= (submapSize_[s] >= del) ? del : submapSize_[s];
total += del;
}
size_ -= (size_ >= total) ? total : size_;
return total;
}
void EraseAsync(void* keys, Extent keyNum, aclrtStream stream)
{
SizeType n = static_cast<SizeType>(keyNum);
if (n == 0 || keys == nullptr) return;
for (size_t s = 0; s < submaps_.size(); ++s)
{
if (submapSize_[s] == 0) continue;
submaps_[s]->EraseAsync(keys, n, stream);
}
}
void Clear(aclrtStream stream)
{
if (nextSubmap_ && prepStream_ != nullptr)
{
CheckRet(aclrtSynchronizeStream(prepStream_), "DynamicMap::Clear::aclrtSynchronizeStream");
}
nextSubmap_.reset();
nextSubmapCap_ = 0;
for (auto& sm : submaps_) sm->Clear(stream);
for (auto& s : submapSize_) s = 0;
size_ = 0;
}
private:
struct AclFreeDeleter
{
void operator()(void* p) const noexcept
{
if (p) aclrtFree(p);
}
};
SizeType Usable(SizeType cap) const
{
SizeType u = static_cast<SizeType>(std::floor(maxLoadFactor_ * static_cast<double>(cap)));
return (u > minInsertSize_) ? (u - minInsertSize_) : 0;
}
size_t ActiveIdx() const { return submaps_.size() - 1; }
size_t FirstNonEmpty() const
{
for (size_t s = 0; s < submaps_.size(); ++s)
if (submapSize_[s] != 0) return s;
return submaps_.size();
}
bool HasNonEmptyBefore(size_t a) const
{
for (size_t s = 0; s < a; ++s)
if (submapSize_[s] != 0) return true;
return false;
}
uint8_t* Keys() const { return (uint8_t*)dDedup_.get(); }
uint8_t* Mask() const { return Keys() + keysBytes_; }
uint8_t* Tmp() const { return Mask() + maskBytes_; }
void EnsureDedupScratch(SizeType n)
{
size_t keysBytes = ((static_cast<size_t>(n) * sizeof(Key) + 63) / 64) * 64;
size_t maskBytes = ((static_cast<size_t>(n) + 63) / 64) * 64;
size_t bytes = keysBytes + maskBytes * 2;
if (dedupBytes_ >= bytes && dDedup_)
{
keysBytes_ = keysBytes;
maskBytes_ = maskBytes;
return;
}
void* p = nullptr;
CheckRet(aclrtMalloc(&p, bytes, ACL_MEM_MALLOC_HUGE_FIRST), "DynamicMap::EnsureDedupScratch::aclrtMalloc");
dDedup_.reset(p);
dedupBytes_ = bytes;
keysBytes_ = keysBytes;
maskBytes_ = maskBytes;
}
void BuildContainsMask(void* pairs, SizeType n, aclrtStream stream)
{
EnsureDedupScratch(n);
aclco::ExtractKeys<Key, Pair<Key, T>>
<<<aivCoreNum_, 0, stream>>>(Keys(), (uint8_t*)pairs, static_cast<uint32_t>(n));
bool first = true;
size_t a = ActiveIdx();
for (size_t s = 0; s < a; ++s)
{
if (submapSize_[s] == 0) continue;
if (first)
{
submaps_[s]->ContainsAsync(Keys(), Mask(), Extent{n}, stream);
first = false;
}
else
{
submaps_[s]->ContainsAsync(Keys(), Tmp(), Extent{n}, stream);
aclco::MergeContains<><<<aivCoreNum_, 0, stream>>>(Mask(), Tmp(), static_cast<uint32_t>(n));
}
}
}
bool HasMoreNonEmptyAfter(size_t base) const
{
for (size_t s = base + 1; s < submaps_.size(); ++s)
if (submapSize_[s] != 0) return true;
return false;
}
void EnsureScratch(size_t bytes)
{
if (scratchBytes_ >= bytes && dScratch_) return;
void* p = nullptr;
CheckRet(aclrtMalloc(&p, bytes, ACL_MEM_MALLOC_HUGE_FIRST), "DynamicMap::EnsureScratch::aclrtMalloc");
dScratch_.reset(p);
scratchBytes_ = bytes;
}
SizeType ActiveRoom() const
{
size_t a = ActiveIdx();
SizeType usable = Usable(submaps_[a]->Capacity());
return (usable > submapSize_[a]) ? (usable - submapSize_[a]) : 0;
}
void StartPrepareNext(SizeType minUsable)
{
if (nextSubmap_ || prepStream_ == nullptr) return;
SizeType newCap = nextCapacity_;
while (Usable(newCap) < GrowTarget(minUsable)) newCap *= GROWTH_FACTOR;
nextSubmap_ = std::make_unique<MapType>(Extent{newCap}, emptyKey_, emptyValue_, pred_, probingScheme_, storage_,
prepStream_);
nextSubmap_->SetErasedKey(erasedKey_, prepStream_);
nextSubmapCap_ = newCap;
CheckRet(aclrtRecordEvent(prepEvent_, prepStream_), "DynamicMap::StartPrepareNext::aclrtRecordEvent");
}
void ActivateNext(SizeType minUsable, aclrtStream stream)
{
if (nextSubmap_ && Usable(nextSubmapCap_) >= minUsable)
{
CheckRet(aclrtStreamWaitEvent(stream, prepEvent_), "DynamicMap::ActivateNext::aclrtStreamWaitEvent");
submaps_.push_back(std::move(nextSubmap_));
submapSize_.push_back(0);
totalCapacity_ += submaps_.back()->Capacity();
nextCapacity_ = nextSubmapCap_ * GROWTH_FACTOR;
nextSubmapCap_ = 0;
return;
}
nextSubmap_.reset();
SizeType newCap = nextCapacity_;
while (Usable(newCap) < minUsable) newCap *= GROWTH_FACTOR;
submaps_.push_back(
std::make_unique<MapType>(Extent{newCap}, emptyKey_, emptyValue_, pred_, probingScheme_, storage_, stream));
submaps_.back()->SetErasedKey(erasedKey_, stream);
submapSize_.push_back(0);
totalCapacity_ += submaps_.back()->Capacity();
nextCapacity_ = newCap * GROWTH_FACTOR;
}
void GrowOneSubmap(SizeType minUsable, aclrtStream stream) { ActivateNext(GrowTarget(minUsable), stream); }
* 让单次增长覆盖整轮 bulk 插入,子表数收敛(少一档读扇出)。 */
SizeType GrowTarget(SizeType minUsable) const
{
SizeType byGrowth = size_ * GROWTH_FACTOR;
return (byGrowth > minUsable) ? byGrowth : minUsable;
}
void EnsureActiveRoom(SizeType n, aclrtStream stream)
{
if (ActiveRoom() >= n) return;
ActivateNext(GrowTarget(n), stream);
}
SizeType InsertChunk(void* values, SizeType n, aclrtStream stream)
{
size_t a = ActiveIdx();
SizeType ins;
if (!HasNonEmptyBefore(a))
{
SizeType failed = submaps_[a]->Insert(values, Extent{n}, stream);
ins = n - failed;
}
else
{
BuildContainsMask(values, n, stream);
counter_.Initialize(0, stream);
aclco::CountZero<>
<<<aivCoreNum_, 0, stream>>>(Mask(), static_cast<uint32_t>(n), (uint32_t*)counter_.Data());
SizeType failed = submaps_[a]->template InsertIf<uint8_t, MaskIsZero>(values, Mask(), Extent{n}, stream);
SizeType candidates = static_cast<SizeType>(counter_.LoadToHost(stream));
ins = candidates - failed;
}
submapSize_[a] += ins;
size_ += ins;
return ins;
}
* 返回值只计真正新插入(assign 不计入)。 */
SizeType InsertOrAssignChunk(void* values, SizeType n, aclrtStream stream)
{
size_t a = ActiveIdx();
SizeType ins;
if (!HasNonEmptyBefore(a))
{
SizeType assigned = 0;
SizeType failed = submaps_[a]->InsertOrAssign(values, Extent{n}, stream, assigned);
ins = n - failed - assigned;
}
else
{
BuildContainsMask(values, n, stream);
counter_.Initialize(0, stream);
aclco::CountZero<>
<<<aivCoreNum_, 0, stream>>>(Mask(), static_cast<uint32_t>(n), (uint32_t*)counter_.Data());
for (size_t s = 0; s < a; ++s)
{
if (submapSize_[s] == 0) continue;
submaps_[s]->template AssignIfAsync<uint8_t, MaskNonZero>(values, Mask(), Extent{n}, stream);
}
submaps_[a]->template AssignIfAsync<uint8_t, MaskIsZero>(values, Mask(), Extent{n}, stream);
SizeType failed = submaps_[a]->template InsertIf<uint8_t, MaskIsZero>(values, Mask(), Extent{n}, stream);
SizeType candidates = static_cast<SizeType>(counter_.LoadToHost(stream));
ins = candidates - failed;
}
submapSize_[a] += ins;
size_ += ins;
return ins;
}
std::vector<std::unique_ptr<MapType>> submaps_;
std::vector<SizeType> submapSize_;
SizeType size_, totalCapacity_, nextCapacity_, minInsertSize_;
float maxLoadFactor_;
Key emptyKey_;
T emptyValue_;
Key erasedKey_;
KeyEqual pred_;
ProbingScheme probingScheme_;
Storage storage_;
struct AclStreamDeleter
{
void operator()(void* p) const noexcept
{
if (p) aclrtDestroyStream((aclrtStream)p);
}
};
struct AclEventDeleter
{
void operator()(void* p) const noexcept
{
if (p) aclrtDestroyEvent((aclrtEvent)p);
}
};
std::unique_ptr<void, AclFreeDeleter> dEmptyValue_;
std::unique_ptr<void, AclFreeDeleter> dScratch_;
std::unique_ptr<void, AclFreeDeleter> dDedup_;
size_t scratchBytes_ = 0;
size_t dedupBytes_ = 0, keysBytes_ = 0, maskBytes_ = 0;
ArgStorage<uint32_t> counter_;
std::unique_ptr<MapType> nextSubmap_;
SizeType nextSubmapCap_ = 0;
std::unique_ptr<void, AclStreamDeleter> prepStreamHolder_;
std::unique_ptr<void, AclEventDeleter> prepEventHolder_;
aclrtStream prepStream_ = nullptr;
aclrtEvent prepEvent_ = nullptr;
uint32_t aivCoreNum_ = 1;
};
}