You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "tqchen (via GitHub)" <gi...@apache.org> on 2026/02/18 14:43:38 UTC

[PR] [REACTOPR] Cleanup and improve map array containers [tvm-ffi]

tqchen opened a new pull request, #462:
URL: https://github.com/apache/tvm-ffi/pull/462

   This PR runs the following refactor of the map and array containers.
   
   - Remove InplaceArrayBase since it is not as useful
   - Extract MapObj into map_base.h so it can be used for other different subclass and variant of map if needed.
   - Add extra helper methods such as clean
   
   We also reorganized SmallBaseMapObj after DenseMapObj as SmallBaseMapObj is a specialization, which can help possible future refactors to make SmallBaseMapObj be aware of DenseMapObj.
   
   The split out of map_base.h is roughly manual copy and a few extra manual edits to reduce unexpected surprises. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REACTOPR] Cleanup and improve map array containers [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #462:
URL: https://github.com/apache/tvm-ffi/pull/462#issuecomment-3921238599

   To simplify the review, the PR is structured in two commits
   
   - The first commit splits out the related files into map_base.h and cleans up the sequence
      - Copy of MapObj implementation is just copy with no editing
   - The second commit contains the related edits of map_base.h to allow subclass


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REACTOR] Cleanup and improve map array containers [tvm-ffi]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #462:
URL: https://github.com/apache/tvm-ffi/pull/462#issuecomment-3921230923

   ## Summary of Changes
   
   Hello @tqchen, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
   
   This pull request significantly refactors the internal implementation of array and map container classes. The primary goal is to improve modularity and maintainability by separating common map functionalities into a new base class, removing an underutilized array base class, and introducing new utility methods. These changes consolidate shared logic and simplify the container's internal structure without altering external API behavior.
   
   ### Highlights
   
   * **Refactored Map Container Hierarchy**: The core implementation logic for map containers (SmallMapObj and DenseMapObj) has been extracted into a new base class hierarchy (MapBaseObj, SmallMapBaseObj, DenseMapBaseObj) located in `map_base.h`. The original `MapObj` now inherits from `MapBaseObj`, streamlining the design and preparing for future extensions.
   * **Removed InplaceArrayBase**: The `InplaceArrayBase` utility class, previously used for array-like memory layouts, has been removed from `container_details.h`. This simplifies the underlying array implementation.
   * **Updated ArrayObj Implementation**: The `ArrayObj` class no longer relies on `InplaceArrayBase`, and its internal data pointer initialization has been updated to reflect this change, using direct memory offset calculation.
   * **Added `clear()` Helper Method**: A new `clear()` method has been introduced to the map base classes, providing a convenient way to empty map contents and release associated memory.
   * **Templated Map Creation and Insertion Methods**: Static helper methods for map creation, copying, and insertion (`Empty`, `CreateFromRange`, `InsertMaybeReHash`, `CopyFrom`) have been updated to accept template arguments for the specific `MapObjType`, enhancing flexibility and type safety.
   
   🧠 **New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
   
   <details>
   <summary><b>Changelog</b></summary>
   
   * **include/tvm/ffi/container/array.h**
       * Removed inheritance from `details::InplaceArrayBase` for `ArrayObj`.
       * Updated data pointer initialization in `make_inplace_array_object` to directly calculate memory offset.
       * Removed `friend InplaceArrayBase` declaration.
   * **include/tvm/ffi/container/container_details.h**
       * Removed the entire `InplaceArrayBase` template class definition.
   * **include/tvm/ffi/container/map.h**
       * Included new header `tvm/ffi/container/map_base.h`.
       * Changed `MapObj` to inherit from `MapBaseObj` instead of `Object`.
       * Removed extensive map implementation details, delegating them to the new base classes.
       * Updated calls to static map helper methods (`Empty`, `CreateFromRange`, `InsertMaybeReHash`, `CopyFrom`) to include explicit template arguments.
   * **include/tvm/ffi/container/map_base.h**
       * Added new file to define `MapBaseObj`, `DenseMapBaseObj`, and `SmallMapBaseObj`.
       * Implemented all core map functionalities (e.g., `size`, `count`, `at`, `iterator`, `Empty`, `CreateFromRange`, `InsertMaybeReHash`, `CopyFrom`) within these new base classes.
       * Introduced a `clear()` method for map objects.
       * Templated static map helper methods to allow specification of the concrete map object type.
       * Adjusted `SmallMapBaseObj` data initialization to use direct memory offset.
   * **include/tvm/ffi/extra/stl.h**
       * Updated `CopyToMap` and `MoveToMap` methods to use the templated `MapObj::CreateFromRange<MapObj>`.
   </details>
   
   <details>
   <summary><b>Using Gemini Code Assist</b></summary>
   <br>
   
   The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
   
   <b>Invoking Gemini</b>
   
   You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
   
   Feature | Command | Description
   --- | --- | ---
   Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
   Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
   Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
   Help | `/gemini help` | Displays a list of available commands.
   
   <b>Customization</b>
   
   To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
   
   <b>Limitations & Feedback</b>
   
   Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
   
   <b>You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the [Gemini Code Assist IDE Extension](https://cloud.google.com/products/gemini/code-assist).</b>
   </details>
   
   
   [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REACTOR] Cleanup and improve map array containers [tvm-ffi]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #462:
URL: https://github.com/apache/tvm-ffi/pull/462#discussion_r2822710911


##########
include/tvm/ffi/container/map_base.h:
##########
@@ -0,0 +1,1444 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/container/map_base.h
+ * \brief Base container for runtime maps
+ */
+#ifndef TVM_FFI_CONTAINER_MAP_BASE_H_
+#define TVM_FFI_CONTAINER_MAP_BASE_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/container/container_details.h>
+#include <tvm/ffi/memory.h>
+#include <tvm/ffi/object.h>
+#include <tvm/ffi/optional.h>
+
+#include <algorithm>
+#include <limits>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/// \cond Doxygen_Suppress
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+#define TVM_FFI_MAP_FAIL_IF_CHANGED() \
+  TVM_FFI_ICHECK(state_marker == self->state_marker) << "Concurrent modification of the Map";
+#else
+#define TVM_FFI_MAP_FAIL_IF_CHANGED()
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+/// \endcond
+
+/*!
+ * \brief Shared content of all specializations of hash map
+ *
+ * MapBaseObj is transparent to the FFI type system (no type index),
+ * following the same pattern as BytesObjBase.
+ */
+class MapBaseObj : public Object {
+ public:
+  /*! \brief Type of the keys in the hash map */
+  using key_type = Any;
+  /*! \brief Type of the values in the hash map */
+  using mapped_type = Any;
+  /*! \brief Type of value stored in the hash map */
+  using KVType = std::pair<Any, Any>;
+  /// \cond Doxygen_Suppress
+  /*! \brief Type of raw storage of the key-value pair in the hash map */
+  struct KVRawStorageType {
+    TVMFFIAny first;
+    TVMFFIAny second;
+  };
+  /// \endcond
+  /*! \brief Iterator class */
+  class iterator;
+
+  static_assert(std::is_standard_layout_v<KVType>, "KVType is not standard layout");
+  static_assert(sizeof(KVType) == 32, "sizeof(KVType) incorrect");
+
+  /*!
+   * \brief Number of elements in the MapBaseObj
+   * \return The result
+   */
+  size_t size() const { return size_; }
+  /*!
+   * \brief Count the number of times a key exists in the hash map
+   * \param key The indexing key
+   * \return The result, 0 or 1
+   */
+  size_t count(const key_type& key) const;
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The const reference to the value
+   */
+  const mapped_type& at(const key_type& key) const;
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The mutable reference to the value
+   */
+  mapped_type& at(const key_type& key);
+  /*! \return begin iterator */
+  iterator begin() const;
+  /*! \return end iterator */
+  iterator end() const;
+  /*!
+   * \brief Index value associated with a key
+   * \param key The indexing key
+   * \return The iterator of the entry associated with the key, end iterator if not exists
+   */
+  iterator find(const key_type& key) const;
+  /*!
+   * \brief Erase the entry associated with the iterator
+   * \param position The iterator
+   */
+  void erase(const iterator& position);
+  /*!
+   * \brief Erase the entry associated with the key, do nothing if not exists
+   * \param key The indexing key
+   */
+  void erase(const key_type& key) { erase(find(key)); }
+
+  /*!
+   * \brief clear all entries
+   */
+  void clear();
+
+  /// \cond Doxygen_Suppress
+  class iterator {
+   public:
+    using iterator_category = std::forward_iterator_tag;
+    using difference_type = int64_t;
+    using value_type = KVType;
+    using pointer = KVType*;
+    using reference = KVType&;
+/*! \brief Default constructor */
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    iterator() : state_marker(0), index(0), self(nullptr) {}
+#else
+    iterator() : index(0), self(nullptr) {}
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    /*! \brief Compare iterators */
+    bool operator==(const iterator& other) const {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      return index == other.index && self == other.self;
+    }
+    /*! \brief Compare iterators */
+    bool operator!=(const iterator& other) const { return !(*this == other); }
+    /*! \brief De-reference iterators */
+    pointer operator->() const;
+    /*! \brief De-reference iterators */
+    reference operator*() const {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      return *((*this).operator->());
+    }
+    /*! \brief Prefix self increment, e.g. ++iter */
+    iterator& operator++();
+    /*! \brief Prefix self decrement, e.g. --iter */
+    iterator& operator--();
+    /*! \brief Suffix self increment */
+    iterator operator++(int) {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      iterator copy = *this;
+      ++(*this);
+      return copy;
+    }
+    /*! \brief Suffix self decrement */
+    iterator operator--(int) {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      iterator copy = *this;
+      --(*this);
+      return copy;
+    }
+
+   protected:
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    uint64_t state_marker;
+    /*! \brief Construct by value */
+    iterator(uint64_t index, const MapBaseObj* self)
+        : state_marker(self->state_marker), index(index), self(self) {}
+
+#else
+    iterator(uint64_t index, const MapBaseObj* self) : index(index), self(self) {}
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    /*! \brief The position on the array */
+    uint64_t index;
+    /*! \brief The container it points to */
+    const MapBaseObj* self;
+
+    friend class DenseMapBaseObj;
+    friend class SmallMapBaseObj;
+  };
+  /// \endcond
+
+ protected:
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+  uint64_t state_marker;
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+  /*!
+   * \brief Create an empty container
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static inline ObjectPtr<Object> Empty();
+  /*!
+   * \brief Create the map using contents from the given iterators.
+   * \param first Begin of iterator
+   * \param last End of iterator
+   * \tparam MapObjType The type of map object
+   * \tparam IterType The type of iterator
+   * \return ObjectPtr to the map created
+   */
+  template <typename MapObjType, typename IterType>
+  static inline ObjectPtr<Object> CreateFromRange(IterType first, IterType last);
+  /*!
+   * \brief InsertMaybeReHash an entry into the given hash map
+   * \param kv The entry to be inserted
+   * \param map The pointer to the map, can be changed if re-hashing happens
+   * \tparam MapObjType The type of map object
+   */
+  template <typename MapObjType>
+  static inline void InsertMaybeReHash(KVType&& kv, ObjectPtr<Object>* map);
+  /*!
+   * \brief Create an empty container with elements copying from another SmallMapBaseObj
+   * \param from The source container
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static inline ObjectPtr<Object> CopyFrom(MapBaseObj* from);
+
+  /*!
+   * \brief data pointer to the data region of the map.
+   * \note For immutable inplace small map we do not need data_,
+   *       but we keep it here for future compact with mutable container.
+   */
+  void* data_;
+  /*! \brief number of entries in the container */
+  uint64_t size_;
+  /*! \brief number of slots  */
+  uint64_t slots_;
+  /*!
+   * \brief Small layout tag mask
+   * \note The most significant bit is used to indicate the small map layout.
+   */
+  static constexpr uint64_t kSmallTagMask = static_cast<uint64_t>(1) << 63;
+  /*!
+   * \brief Check if the map is a small map
+   * \return True if the map is a small map
+   */
+  bool IsSmallMap() const { return (slots_ & kSmallTagMask) != 0ull; }
+  /*!
+   * \brief Optional data deleter when data is allocated separately
+   *        and its deletion is not managed by MapBaseObj::deleter_.
+   */
+  void (*data_deleter_)(void*) = nullptr;
+  // Reference class
+  friend class SmallMapBaseObj;
+  friend class DenseMapBaseObj;
+
+  template <typename, typename>
+  friend struct TypeTraits;
+};
+
+/*! \brief A specialization of hash map that implements the idea of array-based hash map.
+ * Another reference implementation can be found [1].
+ *
+ * A. Overview
+ *
+ * DenseMapBaseObj did several improvements over traditional separate chaining hash,
+ * in terms of cache locality, memory footprints and data organization.
+ *
+ * A1. Implicit linked list. For better cache locality, instead of using linked list
+ * explicitly for each bucket, we store list data into a single array that spans contiguously
+ * in memory, and then carefully design access patterns to make sure most of them fall into
+ * a single cache line.
+ *
+ * A2. 1-byte metadata. There is only 1 byte overhead for each slot in the array to indexing and
+ * traversal. This can be divided in 3 parts.
+ * 1) Reserved code: (0b11111111)_2 indicates a slot is empty; (0b11111110)_2 indicates protected,
+ * which means the slot is empty but not allowed to be written.
+ * 2) If not empty or protected, the highest bit is used to indicate whether data in the slot is
+ * head of a linked list.
+ * 3) The rest 7 bits are used as the "next pointer" (i.e. pointer to the next element). On 64-bit
+ * architecture, an ordinary pointer can take up to 8 bytes, which is not acceptable overhead when
+ * dealing with 16-byte ObjectRef pairs. Based on a commonly noticed fact that the lists are
+ * relatively short (length <= 3) in hash maps, we follow [1]'s idea that only allows the pointer to
+ * be one of the 126 possible values, i.e. if the next element of i-th slot is (i + x)-th element,
+ * then x must be one of the 126 pre-defined values.
+ *
+ * A3. Data blocking. We organize the array in the way that every 16 elements forms a data block.
+ * The 16-byte metadata of those 16 elements are stored together, followed by the real data, i.e.
+ * 16 key-value pairs.
+ *
+ * B. Implementation details
+ *
+ * B1. Power-of-2 table size and Fibonacci Hashing. We use power-of-two as table size to avoid
+ * modulo for more efficient arithmetics. To make the hash-to-slot mapping distribute more evenly,
+ * we use the Fibonacci Hashing [2] trick.
+ *
+ * B2. Traverse a linked list in the array.
+ * 1) List head. Assume Fibonacci Hashing maps a given key to slot i, if metadata at slot i
+ * indicates that it is list head, then we found the head; otherwise the list is empty. No probing
+ * is done in this procedure. 2) Next element. To find the next element of a non-empty slot i, we
+ * look at the last 7 bits of the metadata at slot i. If they are all zeros, then it is the end of
+ * list; otherwise, we know that the next element is (i + candidates[the-last-7-bits]).
+ *
+ * B3. InsertMaybeReHash an element. Following B2, we first traverse the linked list to see if this
+ * element is in the linked list, and if not, we put it at the end by probing the next empty
+ * position in one of the 126 candidate positions. If the linked list does not even exist, but the
+ * slot for list head has been occupied by another linked list, we should find this intruder another
+ * place.
+ *
+ * B4. Quadratic probing with triangle numbers. In open address hashing, it is provable that probing
+ * with triangle numbers can traverse power-of-2-sized table [3]. In our algorithm, we follow the
+ * suggestion in [1] that also use triangle numbers for "next pointer" as well as sparing for list
+ * head.
+ *
+ * [1] https://github.com/skarupke/flat_hash_map
+ * [2] https://programmingpraxis.com/2018/06/19/fibonacci-hash/
+ * [3] https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/
+ */
+class DenseMapBaseObj : public MapBaseObj {
+ private:
+  /*! \brief The number of elements in a memory block */
+  static constexpr int kBlockCap = 16;
+  /*! \brief Maximum load factor of the hash map */
+  static constexpr double kMaxLoadFactor = 0.99;
+  /*! \brief Binary representation of the metadata of an empty slot */
+  static constexpr uint8_t kEmptySlot = static_cast<uint8_t>(0b11111111);
+  /*! \brief Binary representation of the metadata of a protected slot */
+  static constexpr uint8_t kProtectedSlot = static_cast<uint8_t>(0b11111110);
+  /*! \brief Number of probing choices available */
+  static constexpr int kNumJumpDists = 126;
+  /*! \brief Index indicator to indicate an invalid index */
+  static constexpr uint64_t kInvalidIndex = std::numeric_limits<uint64_t>::max();
+  /*! \brief Head of the implicit linked list */
+  struct ListNode;
+  /*! \brief item type of the dense map, including a kv data and prev/next pointer */
+  struct ItemType {
+    KVType data;
+    uint64_t prev = kInvalidIndex;
+    uint64_t next = kInvalidIndex;
+
+    explicit ItemType(KVType&& data) : data(std::move(data)) {}
+    explicit ItemType(key_type key, mapped_type value) : data(std::move(key), std::move(value)) {}
+  };
+  /*! \brief POD type of a block of memory */
+  struct Block {
+    uint8_t bytes[kBlockCap + kBlockCap * sizeof(ItemType)];
+  };
+  static_assert(sizeof(Block) == kBlockCap * (sizeof(ItemType) + 1), "sizeof(Block) incorrect");
+  static_assert(std::is_standard_layout_v<Block>, "Block is not standard layout");
+
+  /*!
+   * \brief Deleter for the Block
+   * \param data The pointer to the Block
+   */
+  static void BlockDeleter(void* data) { delete[] static_cast<Block*>(data); }
+
+ public:
+  using MapBaseObj::iterator;
+
+  /*!
+   * \brief Return the number of usable slots for Dense layout (MSB clear => identity).
+   * \return The number of usable slots
+   */
+  uint64_t NumSlots() const { return slots_; }
+
+  /*!
+   * \brief Destroy the DenseMapBaseObj
+   */
+  ~DenseMapBaseObj() { this->Reset(); }
+  /*! \return The number of elements of the key */
+  size_t count(const key_type& key) const { return !Search(key).IsNone(); }
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The const reference to the value
+   */
+  const mapped_type& at(const key_type& key) const { return At(key); }
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The mutable reference to the value
+   */
+  mapped_type& at(const key_type& key) { return At(key); }
+  /*!
+   * \brief Index value associated with a key
+   * \param key The indexing key
+   * \return The iterator of the entry associated with the key, end iterator if not exists
+   */
+  iterator find(const key_type& key) const {
+    ListNode node = Search(key);
+    return node.IsNone() ? end() : iterator(node.index, this);
+  }
+  /*!
+   * \brief Erase the entry associated with the iterator
+   * \param position The iterator
+   */
+  void erase(const iterator& position) {
+    uint64_t index = position.index;
+    if (position.self != nullptr && index <= this->NumSlots()) {
+      Erase(ListNode(index, this));
+    }
+  }
+  /*! \return begin iterator */
+  iterator begin() const { return iterator(iter_list_head_, this); }
+  /*! \return end iterator */
+  iterator end() const { return iterator(kInvalidIndex, this); }
+
+  /*!
+   * \brief clear all entries
+   */
+  void clear() {
+    uint64_t n_blocks = CalcNumBlocks(this->NumSlots());
+    for (uint64_t bi = 0; bi < n_blocks; ++bi) {
+      uint8_t* meta_ptr = GetBlock(bi)->bytes;
+      ItemType* data_ptr = reinterpret_cast<ItemType*>(GetBlock(bi)->bytes + kBlockCap);
+      for (int j = 0; j < kBlockCap; ++j, ++meta_ptr, ++data_ptr) {
+        uint8_t& meta = *meta_ptr;
+        if (meta != kProtectedSlot && meta != kEmptySlot) {
+          meta = kEmptySlot;
+          data_ptr->ItemType::~ItemType();
+        }
+      }
+    }
+    size_ = 0;
+    iter_list_head_ = kInvalidIndex;
+    iter_list_tail_ = kInvalidIndex;
+  }
+
+ private:
+  Block* GetBlock(size_t index) const { return static_cast<Block*>(data_) + index; }
+  /*!
+   * \brief Unlink the entry from iterator list
+   * \param node The node to be unlinked
+   * \note This function is usually used before deletion,
+   *       and it does not change data content of the node.
+   */
+  void IterListUnlink(ListNode node) {
+    // update head and tail of iterator list if needed
+    if (node.Item().prev == kInvalidIndex) {
+      iter_list_head_ = node.Item().next;
+    } else {
+      ListNode prev_node(node.Item().prev, this);
+      prev_node.Item().next = node.Item().next;
+    }
+    if (node.Item().next == kInvalidIndex) {
+      iter_list_tail_ = node.Item().prev;
+    } else {
+      ListNode next_node(node.Item().next, this);
+      next_node.Item().prev = node.Item().prev;
+    }
+  }
+  /*!
+   * \brief Insert the entry into tail of iterator list
+   * \param node The node to be inserted
+   * \note this function does not change data content of the node.
+   */
+  void IterListPushBack(ListNode node) {
+    node.Item().prev = iter_list_tail_;
+    node.Item().next = kInvalidIndex;
+    if (iter_list_tail_ != kInvalidIndex) {
+      ListNode prev_node(iter_list_tail_, this);
+      prev_node.Item().next = node.index;
+    }
+    if (iter_list_head_ == kInvalidIndex) {
+      iter_list_head_ = node.index;
+    }
+    iter_list_tail_ = node.index;
+  }
+  /*!
+   * \brief Replace node src by dst in the iter list
+   * \param src The source node
+   * \param dst The destination node, must be empty
+   * \note This function does not change data content of the nodes,
+   *       which needs to be updated by the caller.
+   */
+  void IterListReplaceNodeBy(ListNode src, ListNode dst) {
+    // set link correctly on the dst
+    dst.Item().prev = src.Item().prev;
+    dst.Item().next = src.Item().next;
+    // update prev and next of dst
+    if (dst.Item().prev == kInvalidIndex) {
+      iter_list_head_ = dst.index;
+    } else {
+      ListNode prev_node(dst.Item().prev, this);
+      prev_node.Item().next = dst.index;
+    }
+    if (dst.Item().next == kInvalidIndex) {
+      iter_list_tail_ = dst.index;
+    } else {
+      ListNode next_node(dst.Item().next, this);
+      next_node.Item().prev = dst.index;
+    }
+  }
+  /*!
+   * \brief Search for the given key
+   * \param key The key
+   * \return ListNode that associated with the key
+   */
+  ListNode Search(const key_type& key) const {
+    if (this->size_ == 0) {
+      return ListNode();
+    }
+    for (ListNode iter = GetListHead(AnyHash()(key)); !iter.IsNone(); iter.MoveToNext(this)) {
+      if (AnyEqual()(key, iter.Key())) {
+        return iter;
+      }
+    }
+    return ListNode();
+  }
+  /*!
+   * \brief Search for the given key, throw exception if not exists
+   * \param key The key
+   * \return ListNode that associated with the key
+   */
+  mapped_type& At(const key_type& key) const {
+    ListNode iter = Search(key);
+    if (iter.IsNone()) {
+      TVM_FFI_THROW(KeyError) << "key is not in Map";
+    }
+    return iter.Val();
+  }
+  /*!
+   * \brief Try to insert a key, or do nothing if already exists
+   * \param key The indexing key
+   * \param result The linked-list entry found or just constructed
+   * \return A boolean, indicating if actual insertion happens
+   */
+  bool TryInsert(const key_type& key, ListNode* result) {
+    if (slots_ == 0) {
+      return false;
+    }
+    // required that `iter` to be the head of a linked list through which we can iterator
+    ListNode iter = IndexFromHash(AnyHash()(key));
+    // `iter` can be: 1) empty; 2) body of an irrelevant list; 3) head of the relevant list
+    // Case 1: empty
+    if (iter.IsEmpty()) {
+      iter.NewHead(ItemType(key, Any(nullptr)));
+      this->size_ += 1;
+      *result = iter;
+      return true;
+    }
+    // Case 2: body of an irrelevant list
+    if (!iter.IsHead()) {
+      // we move the elements around and construct the single-element linked list
+      return IsFull() ? false : TrySpareListHead(iter, key, result);
+    }
+    // Case 3: head of the relevant list
+    // we iterate through the linked list until the end
+    // make sure `iter` is the previous element of `next`
+    ListNode next = iter;
+    do {
+      // find equal item, do not insert
+      if (AnyEqual()(key, next.Key())) {
+        // we plan to take next, so we need to unlink it from iterator list
+        IterListUnlink(next);
+        *result = next;
+        return true;
+      }
+      // make sure `iter` is the previous element of `next`
+      iter = next;
+    } while (next.MoveToNext(this));
+    // `iter` is the tail of the linked list
+    // always check capacity before insertion
+    if (IsFull()) {
+      return false;
+    }
+    // find the next empty slot
+    uint8_t jump;
+    if (!iter.GetNextEmpty(this, &jump, result)) {
+      return false;
+    }
+    result->NewTail(ItemType(key, Any(nullptr)));
+    // link `iter` to `empty`, and move forward
+    iter.SetJump(jump);
+    this->size_ += 1;
+    return true;
+  }
+  /*!
+   * \brief Spare an entry to be the head of a linked list.
+   * As described in B3, during insertion, it is possible that the entire linked list does not
+   * exist, but the slot of its head has been occupied by other linked lists. In this case, we need
+   * to spare the slot by moving away the elements to another valid empty one to make insertion
+   * possible.
+   * \param target The given entry to be spared
+   * \param key The indexing key
+   * \param result The linked-list entry constructed as the head
+   * \return A boolean, if actual insertion happens
+   */
+  bool TrySpareListHead(ListNode target, const key_type& key, ListNode* result) {
+    // `target` is not the head of the linked list
+    // move the original item of `target` (if any)
+    // and construct new item on the position `target`
+    // To make `target` empty, we
+    // 1) find `w` the previous element of `target` in the linked list
+    // 2) copy the linked list starting from `r = target`
+    // 3) paste them after `w`
+    // read from the linked list after `r`
+    ListNode r = target;
+    // write to the tail of `w`
+    ListNode w = target.FindPrev(this);
+    // after `target` is moved, we disallow writing to the slot
+    bool is_first = true;
+    uint8_t r_meta, jump;
+    ListNode empty;
+    do {
+      // `jump` describes how `w` is jumped to `empty`
+      // rehash if there is no empty space after `w`
+      if (!w.GetNextEmpty(this, &jump, &empty)) {
+        return false;
+      }
+      // move `r` to `empty`
+      // first move the data over
+      empty.NewTail(ItemType(std::move(r.Data())));
+      // then move link list chain of r to empty
+      // this needs to happen after NewTail so empty's prev/next get updated
+      IterListReplaceNodeBy(r, empty);
+      // explicit call destructor to destroy the item in `r`
+      r.DestructData();
+      // clear the metadata of `r`
+      r_meta = r.Meta();
+      if (is_first) {
+        is_first = false;
+        r.SetProtected();
+      } else {
+        r.SetEmpty();
+      }
+      // link `w` to `empty`, and move forward
+      w.SetJump(jump);
+      w = empty;
+      // move `r` forward as well
+    } while (r.MoveToNext(this, r_meta));
+    // finally we have done moving the linked list
+    // fill data_ into `target`
+    target.NewHead(ItemType(key, Any(nullptr)));
+    this->size_ += 1;
+    *result = target;
+    return true;
+  }
+  /*!
+   * \brief Remove a ListNode
+   * \param iter The node to be removed
+   */
+  void Erase(const ListNode& iter) {
+    this->size_ -= 1;
+    if (!iter.HasNext()) {
+      // `iter` is the last
+      if (!iter.IsHead()) {
+        // cut the link if there is any
+        iter.FindPrev(this).SetJump(0);
+      }
+      // unlink the node from iterator list
+      IterListUnlink(iter);
+      // IMPORTANT: must explicit call destructor `iter` to avoid memory leak
+      // This is because we need to recycle iter's data
+      iter.DestructData();
+      // set the meta data to be empty
+      iter.SetEmpty();
+    } else {
+      ListNode last = iter, prev = iter;
+      for (last.MoveToNext(this); last.HasNext(); prev = last, last.MoveToNext(this)) {
+      }
+      // needs to first unlink iter from the list
+      IterListUnlink(iter);
+      // move data from last to iter
+      iter.Data() = std::move(last.Data());
+      // Move link chain of iter to last as we stores last node to the new iter loc.
+      IterListReplaceNodeBy(last, iter);
+      // IMPORTANT: must explicit call destructor `last` to avoid memory leak
+      // likely we don't need this in this particular case because Any move behavior
+      // keep it here to be safe so code do not depend on specific move behavior of KVType
+      last.DestructData();
+      // set the meta data to be empty
+      last.SetEmpty();
+      prev.SetJump(0);
+    }
+  }
+  /*! \brief Clear the container to empty, release all entries and memory acquired */
+  void Reset() {
+    clear();
+    ReleaseMemory();
+  }
+  /*!
+   * \brief Release the memory acquired by the container without deleting its entries stored inside
+   */
+  void ReleaseMemory() {
+    if (data_ != nullptr) {
+      TVM_FFI_ICHECK(data_deleter_ != nullptr);
+      data_deleter_(data_);
+    }
+    data_ = nullptr;
+    data_deleter_ = nullptr;
+    slots_ = 0;
+    size_ = 0;
+    fib_shift_ = 63;
+  }
+  /*!
+   * \brief Create an empty container
+   * \param fib_shift The fib shift provided
+   * \param n_slots Number of slots required, should be power-of-two
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static ObjectPtr<Object> Empty(uint32_t fib_shift, uint64_t n_slots) {
+    // Ensure even slot count (power-of-two expected by callers; this guard
+    // makes the method robust if a non-even value slips through).
+    ObjectPtr<DenseMapBaseObj> p = make_object<DenseMapBaseObj>();
+    uint64_t n_blocks = CalcNumBlocks(n_slots);
+    Block* block = new Block[n_blocks];
+    p->data_ = block;
+    // assign block deleter so even if we take re-alloc data
+    // in another shared-lib that may have different malloc/free behavior
+    // it will still be safe.
+    p->data_deleter_ = BlockDeleter;
+    p->SetSlotsAndDenseLayoutTag(n_slots);
+    p->size_ = 0;
+    p->fib_shift_ = fib_shift;
+    p->iter_list_head_ = kInvalidIndex;
+    p->iter_list_tail_ = kInvalidIndex;
+    // manually set the type index to specialized subclass
+    // data layout is ensured to be the same except for the type index
+    static_assert(std::is_base_of_v<MapBaseObj, MapObjType>);
+    static_assert(sizeof(MapObjType) == sizeof(MapBaseObj));

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   This `static_assert` is confusing. It compares `sizeof(MapObjType)` with `sizeof(MapBaseObj)`, but this code is within `DenseMapBaseObj`, which is larger than `MapBaseObj` due to its own member variables. While the current usage with `MapObj` as `MapObjType` passes this check (as `sizeof(MapObj) == sizeof(MapBaseObj)`), the assertion is misleading in the context of `DenseMapBaseObj`. It seems to be a copy-paste from `SmallMapBaseObj` where a similar assertion is correct. Consider removing this assertion to avoid confusion, as the type-erasure pattern is handled by the dispatch logic.



##########
include/tvm/ffi/container/map_base.h:
##########
@@ -0,0 +1,1444 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/container/map_base.h
+ * \brief Base container for runtime maps
+ */
+#ifndef TVM_FFI_CONTAINER_MAP_BASE_H_
+#define TVM_FFI_CONTAINER_MAP_BASE_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/container/container_details.h>
+#include <tvm/ffi/memory.h>
+#include <tvm/ffi/object.h>
+#include <tvm/ffi/optional.h>
+
+#include <algorithm>
+#include <limits>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/// \cond Doxygen_Suppress
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+#define TVM_FFI_MAP_FAIL_IF_CHANGED() \
+  TVM_FFI_ICHECK(state_marker == self->state_marker) << "Concurrent modification of the Map";
+#else
+#define TVM_FFI_MAP_FAIL_IF_CHANGED()
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+/// \endcond
+
+/*!
+ * \brief Shared content of all specializations of hash map
+ *
+ * MapBaseObj is transparent to the FFI type system (no type index),
+ * following the same pattern as BytesObjBase.
+ */
+class MapBaseObj : public Object {
+ public:
+  /*! \brief Type of the keys in the hash map */
+  using key_type = Any;
+  /*! \brief Type of the values in the hash map */
+  using mapped_type = Any;
+  /*! \brief Type of value stored in the hash map */
+  using KVType = std::pair<Any, Any>;
+  /// \cond Doxygen_Suppress
+  /*! \brief Type of raw storage of the key-value pair in the hash map */
+  struct KVRawStorageType {
+    TVMFFIAny first;
+    TVMFFIAny second;
+  };
+  /// \endcond
+  /*! \brief Iterator class */
+  class iterator;
+
+  static_assert(std::is_standard_layout_v<KVType>, "KVType is not standard layout");
+  static_assert(sizeof(KVType) == 32, "sizeof(KVType) incorrect");
+
+  /*!
+   * \brief Number of elements in the MapBaseObj
+   * \return The result
+   */
+  size_t size() const { return size_; }
+  /*!
+   * \brief Count the number of times a key exists in the hash map
+   * \param key The indexing key
+   * \return The result, 0 or 1
+   */
+  size_t count(const key_type& key) const;
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The const reference to the value
+   */
+  const mapped_type& at(const key_type& key) const;
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The mutable reference to the value
+   */
+  mapped_type& at(const key_type& key);
+  /*! \return begin iterator */
+  iterator begin() const;
+  /*! \return end iterator */
+  iterator end() const;
+  /*!
+   * \brief Index value associated with a key
+   * \param key The indexing key
+   * \return The iterator of the entry associated with the key, end iterator if not exists
+   */
+  iterator find(const key_type& key) const;
+  /*!
+   * \brief Erase the entry associated with the iterator
+   * \param position The iterator
+   */
+  void erase(const iterator& position);
+  /*!
+   * \brief Erase the entry associated with the key, do nothing if not exists
+   * \param key The indexing key
+   */
+  void erase(const key_type& key) { erase(find(key)); }
+
+  /*!
+   * \brief clear all entries
+   */
+  void clear();
+
+  /// \cond Doxygen_Suppress
+  class iterator {
+   public:
+    using iterator_category = std::forward_iterator_tag;
+    using difference_type = int64_t;
+    using value_type = KVType;
+    using pointer = KVType*;
+    using reference = KVType&;
+/*! \brief Default constructor */
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    iterator() : state_marker(0), index(0), self(nullptr) {}
+#else
+    iterator() : index(0), self(nullptr) {}
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    /*! \brief Compare iterators */
+    bool operator==(const iterator& other) const {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      return index == other.index && self == other.self;
+    }
+    /*! \brief Compare iterators */
+    bool operator!=(const iterator& other) const { return !(*this == other); }
+    /*! \brief De-reference iterators */
+    pointer operator->() const;
+    /*! \brief De-reference iterators */
+    reference operator*() const {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      return *((*this).operator->());
+    }
+    /*! \brief Prefix self increment, e.g. ++iter */
+    iterator& operator++();
+    /*! \brief Prefix self decrement, e.g. --iter */
+    iterator& operator--();
+    /*! \brief Suffix self increment */
+    iterator operator++(int) {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      iterator copy = *this;
+      ++(*this);
+      return copy;
+    }
+    /*! \brief Suffix self decrement */
+    iterator operator--(int) {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      iterator copy = *this;
+      --(*this);
+      return copy;
+    }
+
+   protected:
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    uint64_t state_marker;
+    /*! \brief Construct by value */
+    iterator(uint64_t index, const MapBaseObj* self)
+        : state_marker(self->state_marker), index(index), self(self) {}
+
+#else
+    iterator(uint64_t index, const MapBaseObj* self) : index(index), self(self) {}
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    /*! \brief The position on the array */
+    uint64_t index;
+    /*! \brief The container it points to */
+    const MapBaseObj* self;
+
+    friend class DenseMapBaseObj;
+    friend class SmallMapBaseObj;
+  };
+  /// \endcond
+
+ protected:
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+  uint64_t state_marker;
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+  /*!
+   * \brief Create an empty container
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static inline ObjectPtr<Object> Empty();
+  /*!
+   * \brief Create the map using contents from the given iterators.
+   * \param first Begin of iterator
+   * \param last End of iterator
+   * \tparam MapObjType The type of map object
+   * \tparam IterType The type of iterator
+   * \return ObjectPtr to the map created
+   */
+  template <typename MapObjType, typename IterType>
+  static inline ObjectPtr<Object> CreateFromRange(IterType first, IterType last);
+  /*!
+   * \brief InsertMaybeReHash an entry into the given hash map
+   * \param kv The entry to be inserted
+   * \param map The pointer to the map, can be changed if re-hashing happens
+   * \tparam MapObjType The type of map object
+   */
+  template <typename MapObjType>
+  static inline void InsertMaybeReHash(KVType&& kv, ObjectPtr<Object>* map);
+  /*!
+   * \brief Create an empty container with elements copying from another SmallMapBaseObj
+   * \param from The source container
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static inline ObjectPtr<Object> CopyFrom(MapBaseObj* from);
+
+  /*!
+   * \brief data pointer to the data region of the map.
+   * \note For immutable inplace small map we do not need data_,
+   *       but we keep it here for future compact with mutable container.
+   */
+  void* data_;
+  /*! \brief number of entries in the container */
+  uint64_t size_;
+  /*! \brief number of slots  */
+  uint64_t slots_;
+  /*!
+   * \brief Small layout tag mask
+   * \note The most significant bit is used to indicate the small map layout.
+   */
+  static constexpr uint64_t kSmallTagMask = static_cast<uint64_t>(1) << 63;
+  /*!
+   * \brief Check if the map is a small map
+   * \return True if the map is a small map
+   */
+  bool IsSmallMap() const { return (slots_ & kSmallTagMask) != 0ull; }
+  /*!
+   * \brief Optional data deleter when data is allocated separately
+   *        and its deletion is not managed by MapBaseObj::deleter_.
+   */
+  void (*data_deleter_)(void*) = nullptr;
+  // Reference class
+  friend class SmallMapBaseObj;
+  friend class DenseMapBaseObj;
+
+  template <typename, typename>
+  friend struct TypeTraits;
+};
+
+/*! \brief A specialization of hash map that implements the idea of array-based hash map.
+ * Another reference implementation can be found [1].
+ *
+ * A. Overview
+ *
+ * DenseMapBaseObj did several improvements over traditional separate chaining hash,
+ * in terms of cache locality, memory footprints and data organization.
+ *
+ * A1. Implicit linked list. For better cache locality, instead of using linked list
+ * explicitly for each bucket, we store list data into a single array that spans contiguously
+ * in memory, and then carefully design access patterns to make sure most of them fall into
+ * a single cache line.
+ *
+ * A2. 1-byte metadata. There is only 1 byte overhead for each slot in the array to indexing and
+ * traversal. This can be divided in 3 parts.
+ * 1) Reserved code: (0b11111111)_2 indicates a slot is empty; (0b11111110)_2 indicates protected,
+ * which means the slot is empty but not allowed to be written.
+ * 2) If not empty or protected, the highest bit is used to indicate whether data in the slot is
+ * head of a linked list.
+ * 3) The rest 7 bits are used as the "next pointer" (i.e. pointer to the next element). On 64-bit
+ * architecture, an ordinary pointer can take up to 8 bytes, which is not acceptable overhead when
+ * dealing with 16-byte ObjectRef pairs. Based on a commonly noticed fact that the lists are
+ * relatively short (length <= 3) in hash maps, we follow [1]'s idea that only allows the pointer to
+ * be one of the 126 possible values, i.e. if the next element of i-th slot is (i + x)-th element,
+ * then x must be one of the 126 pre-defined values.
+ *
+ * A3. Data blocking. We organize the array in the way that every 16 elements forms a data block.
+ * The 16-byte metadata of those 16 elements are stored together, followed by the real data, i.e.
+ * 16 key-value pairs.
+ *
+ * B. Implementation details
+ *
+ * B1. Power-of-2 table size and Fibonacci Hashing. We use power-of-two as table size to avoid
+ * modulo for more efficient arithmetics. To make the hash-to-slot mapping distribute more evenly,
+ * we use the Fibonacci Hashing [2] trick.
+ *
+ * B2. Traverse a linked list in the array.
+ * 1) List head. Assume Fibonacci Hashing maps a given key to slot i, if metadata at slot i
+ * indicates that it is list head, then we found the head; otherwise the list is empty. No probing
+ * is done in this procedure. 2) Next element. To find the next element of a non-empty slot i, we
+ * look at the last 7 bits of the metadata at slot i. If they are all zeros, then it is the end of
+ * list; otherwise, we know that the next element is (i + candidates[the-last-7-bits]).
+ *
+ * B3. InsertMaybeReHash an element. Following B2, we first traverse the linked list to see if this
+ * element is in the linked list, and if not, we put it at the end by probing the next empty
+ * position in one of the 126 candidate positions. If the linked list does not even exist, but the
+ * slot for list head has been occupied by another linked list, we should find this intruder another
+ * place.
+ *
+ * B4. Quadratic probing with triangle numbers. In open address hashing, it is provable that probing
+ * with triangle numbers can traverse power-of-2-sized table [3]. In our algorithm, we follow the
+ * suggestion in [1] that also use triangle numbers for "next pointer" as well as sparing for list
+ * head.
+ *
+ * [1] https://github.com/skarupke/flat_hash_map
+ * [2] https://programmingpraxis.com/2018/06/19/fibonacci-hash/
+ * [3] https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/
+ */
+class DenseMapBaseObj : public MapBaseObj {
+ private:
+  /*! \brief The number of elements in a memory block */
+  static constexpr int kBlockCap = 16;
+  /*! \brief Maximum load factor of the hash map */
+  static constexpr double kMaxLoadFactor = 0.99;
+  /*! \brief Binary representation of the metadata of an empty slot */
+  static constexpr uint8_t kEmptySlot = static_cast<uint8_t>(0b11111111);
+  /*! \brief Binary representation of the metadata of a protected slot */
+  static constexpr uint8_t kProtectedSlot = static_cast<uint8_t>(0b11111110);
+  /*! \brief Number of probing choices available */
+  static constexpr int kNumJumpDists = 126;
+  /*! \brief Index indicator to indicate an invalid index */
+  static constexpr uint64_t kInvalidIndex = std::numeric_limits<uint64_t>::max();
+  /*! \brief Head of the implicit linked list */
+  struct ListNode;
+  /*! \brief item type of the dense map, including a kv data and prev/next pointer */
+  struct ItemType {
+    KVType data;
+    uint64_t prev = kInvalidIndex;
+    uint64_t next = kInvalidIndex;
+
+    explicit ItemType(KVType&& data) : data(std::move(data)) {}
+    explicit ItemType(key_type key, mapped_type value) : data(std::move(key), std::move(value)) {}
+  };
+  /*! \brief POD type of a block of memory */
+  struct Block {
+    uint8_t bytes[kBlockCap + kBlockCap * sizeof(ItemType)];
+  };
+  static_assert(sizeof(Block) == kBlockCap * (sizeof(ItemType) + 1), "sizeof(Block) incorrect");
+  static_assert(std::is_standard_layout_v<Block>, "Block is not standard layout");
+
+  /*!
+   * \brief Deleter for the Block
+   * \param data The pointer to the Block
+   */
+  static void BlockDeleter(void* data) { delete[] static_cast<Block*>(data); }
+
+ public:
+  using MapBaseObj::iterator;
+
+  /*!
+   * \brief Return the number of usable slots for Dense layout (MSB clear => identity).
+   * \return The number of usable slots
+   */
+  uint64_t NumSlots() const { return slots_; }
+
+  /*!
+   * \brief Destroy the DenseMapBaseObj
+   */
+  ~DenseMapBaseObj() { this->Reset(); }
+  /*! \return The number of elements of the key */
+  size_t count(const key_type& key) const { return !Search(key).IsNone(); }
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The const reference to the value
+   */
+  const mapped_type& at(const key_type& key) const { return At(key); }
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The mutable reference to the value
+   */
+  mapped_type& at(const key_type& key) { return At(key); }
+  /*!
+   * \brief Index value associated with a key
+   * \param key The indexing key
+   * \return The iterator of the entry associated with the key, end iterator if not exists
+   */
+  iterator find(const key_type& key) const {
+    ListNode node = Search(key);
+    return node.IsNone() ? end() : iterator(node.index, this);
+  }
+  /*!
+   * \brief Erase the entry associated with the iterator
+   * \param position The iterator
+   */
+  void erase(const iterator& position) {
+    uint64_t index = position.index;
+    if (position.self != nullptr && index <= this->NumSlots()) {
+      Erase(ListNode(index, this));
+    }
+  }
+  /*! \return begin iterator */
+  iterator begin() const { return iterator(iter_list_head_, this); }
+  /*! \return end iterator */
+  iterator end() const { return iterator(kInvalidIndex, this); }
+
+  /*!
+   * \brief clear all entries
+   */
+  void clear() {
+    uint64_t n_blocks = CalcNumBlocks(this->NumSlots());
+    for (uint64_t bi = 0; bi < n_blocks; ++bi) {
+      uint8_t* meta_ptr = GetBlock(bi)->bytes;
+      ItemType* data_ptr = reinterpret_cast<ItemType*>(GetBlock(bi)->bytes + kBlockCap);
+      for (int j = 0; j < kBlockCap; ++j, ++meta_ptr, ++data_ptr) {
+        uint8_t& meta = *meta_ptr;
+        if (meta != kProtectedSlot && meta != kEmptySlot) {
+          meta = kEmptySlot;
+          data_ptr->ItemType::~ItemType();
+        }
+      }
+    }
+    size_ = 0;
+    iter_list_head_ = kInvalidIndex;
+    iter_list_tail_ = kInvalidIndex;
+  }
+
+ private:
+  Block* GetBlock(size_t index) const { return static_cast<Block*>(data_) + index; }
+  /*!
+   * \brief Unlink the entry from iterator list
+   * \param node The node to be unlinked
+   * \note This function is usually used before deletion,
+   *       and it does not change data content of the node.
+   */
+  void IterListUnlink(ListNode node) {
+    // update head and tail of iterator list if needed
+    if (node.Item().prev == kInvalidIndex) {
+      iter_list_head_ = node.Item().next;
+    } else {
+      ListNode prev_node(node.Item().prev, this);
+      prev_node.Item().next = node.Item().next;
+    }
+    if (node.Item().next == kInvalidIndex) {
+      iter_list_tail_ = node.Item().prev;
+    } else {
+      ListNode next_node(node.Item().next, this);
+      next_node.Item().prev = node.Item().prev;
+    }
+  }
+  /*!
+   * \brief Insert the entry into tail of iterator list
+   * \param node The node to be inserted
+   * \note this function does not change data content of the node.
+   */
+  void IterListPushBack(ListNode node) {
+    node.Item().prev = iter_list_tail_;
+    node.Item().next = kInvalidIndex;
+    if (iter_list_tail_ != kInvalidIndex) {
+      ListNode prev_node(iter_list_tail_, this);
+      prev_node.Item().next = node.index;
+    }
+    if (iter_list_head_ == kInvalidIndex) {
+      iter_list_head_ = node.index;
+    }
+    iter_list_tail_ = node.index;
+  }
+  /*!
+   * \brief Replace node src by dst in the iter list
+   * \param src The source node
+   * \param dst The destination node, must be empty
+   * \note This function does not change data content of the nodes,
+   *       which needs to be updated by the caller.
+   */
+  void IterListReplaceNodeBy(ListNode src, ListNode dst) {
+    // set link correctly on the dst
+    dst.Item().prev = src.Item().prev;
+    dst.Item().next = src.Item().next;
+    // update prev and next of dst
+    if (dst.Item().prev == kInvalidIndex) {
+      iter_list_head_ = dst.index;
+    } else {
+      ListNode prev_node(dst.Item().prev, this);
+      prev_node.Item().next = dst.index;
+    }
+    if (dst.Item().next == kInvalidIndex) {
+      iter_list_tail_ = dst.index;
+    } else {
+      ListNode next_node(dst.Item().next, this);
+      next_node.Item().prev = dst.index;
+    }
+  }
+  /*!
+   * \brief Search for the given key
+   * \param key The key
+   * \return ListNode that associated with the key
+   */
+  ListNode Search(const key_type& key) const {
+    if (this->size_ == 0) {
+      return ListNode();
+    }
+    for (ListNode iter = GetListHead(AnyHash()(key)); !iter.IsNone(); iter.MoveToNext(this)) {
+      if (AnyEqual()(key, iter.Key())) {
+        return iter;
+      }
+    }
+    return ListNode();
+  }
+  /*!
+   * \brief Search for the given key, throw exception if not exists
+   * \param key The key
+   * \return ListNode that associated with the key
+   */
+  mapped_type& At(const key_type& key) const {
+    ListNode iter = Search(key);
+    if (iter.IsNone()) {
+      TVM_FFI_THROW(KeyError) << "key is not in Map";
+    }
+    return iter.Val();
+  }
+  /*!
+   * \brief Try to insert a key, or do nothing if already exists
+   * \param key The indexing key
+   * \param result The linked-list entry found or just constructed
+   * \return A boolean, indicating if actual insertion happens
+   */
+  bool TryInsert(const key_type& key, ListNode* result) {
+    if (slots_ == 0) {
+      return false;
+    }
+    // required that `iter` to be the head of a linked list through which we can iterator
+    ListNode iter = IndexFromHash(AnyHash()(key));
+    // `iter` can be: 1) empty; 2) body of an irrelevant list; 3) head of the relevant list
+    // Case 1: empty
+    if (iter.IsEmpty()) {
+      iter.NewHead(ItemType(key, Any(nullptr)));
+      this->size_ += 1;
+      *result = iter;
+      return true;
+    }
+    // Case 2: body of an irrelevant list
+    if (!iter.IsHead()) {
+      // we move the elements around and construct the single-element linked list
+      return IsFull() ? false : TrySpareListHead(iter, key, result);
+    }
+    // Case 3: head of the relevant list
+    // we iterate through the linked list until the end
+    // make sure `iter` is the previous element of `next`
+    ListNode next = iter;
+    do {
+      // find equal item, do not insert
+      if (AnyEqual()(key, next.Key())) {
+        // we plan to take next, so we need to unlink it from iterator list
+        IterListUnlink(next);
+        *result = next;
+        return true;
+      }
+      // make sure `iter` is the previous element of `next`
+      iter = next;
+    } while (next.MoveToNext(this));
+    // `iter` is the tail of the linked list
+    // always check capacity before insertion
+    if (IsFull()) {
+      return false;
+    }
+    // find the next empty slot
+    uint8_t jump;
+    if (!iter.GetNextEmpty(this, &jump, result)) {
+      return false;
+    }
+    result->NewTail(ItemType(key, Any(nullptr)));
+    // link `iter` to `empty`, and move forward
+    iter.SetJump(jump);
+    this->size_ += 1;
+    return true;
+  }
+  /*!
+   * \brief Spare an entry to be the head of a linked list.
+   * As described in B3, during insertion, it is possible that the entire linked list does not
+   * exist, but the slot of its head has been occupied by other linked lists. In this case, we need
+   * to spare the slot by moving away the elements to another valid empty one to make insertion
+   * possible.
+   * \param target The given entry to be spared
+   * \param key The indexing key
+   * \param result The linked-list entry constructed as the head
+   * \return A boolean, if actual insertion happens
+   */
+  bool TrySpareListHead(ListNode target, const key_type& key, ListNode* result) {
+    // `target` is not the head of the linked list
+    // move the original item of `target` (if any)
+    // and construct new item on the position `target`
+    // To make `target` empty, we
+    // 1) find `w` the previous element of `target` in the linked list
+    // 2) copy the linked list starting from `r = target`
+    // 3) paste them after `w`
+    // read from the linked list after `r`
+    ListNode r = target;
+    // write to the tail of `w`
+    ListNode w = target.FindPrev(this);
+    // after `target` is moved, we disallow writing to the slot
+    bool is_first = true;
+    uint8_t r_meta, jump;
+    ListNode empty;
+    do {
+      // `jump` describes how `w` is jumped to `empty`
+      // rehash if there is no empty space after `w`
+      if (!w.GetNextEmpty(this, &jump, &empty)) {
+        return false;
+      }
+      // move `r` to `empty`
+      // first move the data over
+      empty.NewTail(ItemType(std::move(r.Data())));
+      // then move link list chain of r to empty
+      // this needs to happen after NewTail so empty's prev/next get updated
+      IterListReplaceNodeBy(r, empty);
+      // explicit call destructor to destroy the item in `r`
+      r.DestructData();
+      // clear the metadata of `r`
+      r_meta = r.Meta();
+      if (is_first) {
+        is_first = false;
+        r.SetProtected();
+      } else {
+        r.SetEmpty();
+      }
+      // link `w` to `empty`, and move forward
+      w.SetJump(jump);
+      w = empty;
+      // move `r` forward as well
+    } while (r.MoveToNext(this, r_meta));
+    // finally we have done moving the linked list
+    // fill data_ into `target`
+    target.NewHead(ItemType(key, Any(nullptr)));
+    this->size_ += 1;
+    *result = target;
+    return true;
+  }
+  /*!
+   * \brief Remove a ListNode
+   * \param iter The node to be removed
+   */
+  void Erase(const ListNode& iter) {
+    this->size_ -= 1;
+    if (!iter.HasNext()) {
+      // `iter` is the last
+      if (!iter.IsHead()) {
+        // cut the link if there is any
+        iter.FindPrev(this).SetJump(0);
+      }
+      // unlink the node from iterator list
+      IterListUnlink(iter);
+      // IMPORTANT: must explicit call destructor `iter` to avoid memory leak
+      // This is because we need to recycle iter's data
+      iter.DestructData();
+      // set the meta data to be empty
+      iter.SetEmpty();
+    } else {
+      ListNode last = iter, prev = iter;
+      for (last.MoveToNext(this); last.HasNext(); prev = last, last.MoveToNext(this)) {
+      }
+      // needs to first unlink iter from the list
+      IterListUnlink(iter);
+      // move data from last to iter
+      iter.Data() = std::move(last.Data());
+      // Move link chain of iter to last as we stores last node to the new iter loc.
+      IterListReplaceNodeBy(last, iter);
+      // IMPORTANT: must explicit call destructor `last` to avoid memory leak
+      // likely we don't need this in this particular case because Any move behavior
+      // keep it here to be safe so code do not depend on specific move behavior of KVType
+      last.DestructData();
+      // set the meta data to be empty
+      last.SetEmpty();
+      prev.SetJump(0);
+    }
+  }
+  /*! \brief Clear the container to empty, release all entries and memory acquired */
+  void Reset() {
+    clear();
+    ReleaseMemory();
+  }
+  /*!
+   * \brief Release the memory acquired by the container without deleting its entries stored inside
+   */
+  void ReleaseMemory() {
+    if (data_ != nullptr) {
+      TVM_FFI_ICHECK(data_deleter_ != nullptr);
+      data_deleter_(data_);
+    }
+    data_ = nullptr;
+    data_deleter_ = nullptr;
+    slots_ = 0;
+    size_ = 0;
+    fib_shift_ = 63;
+  }
+  /*!
+   * \brief Create an empty container
+   * \param fib_shift The fib shift provided
+   * \param n_slots Number of slots required, should be power-of-two
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static ObjectPtr<Object> Empty(uint32_t fib_shift, uint64_t n_slots) {
+    // Ensure even slot count (power-of-two expected by callers; this guard
+    // makes the method robust if a non-even value slips through).
+    ObjectPtr<DenseMapBaseObj> p = make_object<DenseMapBaseObj>();
+    uint64_t n_blocks = CalcNumBlocks(n_slots);
+    Block* block = new Block[n_blocks];
+    p->data_ = block;
+    // assign block deleter so even if we take re-alloc data
+    // in another shared-lib that may have different malloc/free behavior
+    // it will still be safe.
+    p->data_deleter_ = BlockDeleter;
+    p->SetSlotsAndDenseLayoutTag(n_slots);
+    p->size_ = 0;
+    p->fib_shift_ = fib_shift;
+    p->iter_list_head_ = kInvalidIndex;
+    p->iter_list_tail_ = kInvalidIndex;
+    // manually set the type index to specialized subclass
+    // data layout is ensured to be the same except for the type index
+    static_assert(std::is_base_of_v<MapBaseObj, MapObjType>);
+    static_assert(sizeof(MapObjType) == sizeof(MapBaseObj));
+    p->header_.type_index = MapObjType::RuntimeTypeIndex();
+    for (uint64_t i = 0; i < n_blocks; ++i, ++block) {
+      std::fill(block->bytes, block->bytes + kBlockCap, kEmptySlot);
+    }
+    return p;
+  }
+  /*!
+   * \brief Create an empty container with elements copying from another DenseMapBaseObj
+   * \param from The source container
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static ObjectPtr<Object> CopyFrom(DenseMapBaseObj* from) {
+    ObjectPtr<DenseMapBaseObj> p = make_object<DenseMapBaseObj>();
+    uint64_t n_blocks = CalcNumBlocks(from->NumSlots());
+    p->data_ = new Block[n_blocks];
+    // assign block deleter so even if we take re-alloc data
+    // in another shared-lib that may have different malloc/free behavior
+    // it will still be safe.
+    p->data_deleter_ = BlockDeleter;
+    p->SetSlotsAndDenseLayoutTag(from->NumSlots());
+    p->size_ = from->size_;
+    p->fib_shift_ = from->fib_shift_;
+    p->iter_list_head_ = from->iter_list_head_;
+    p->iter_list_tail_ = from->iter_list_tail_;
+    // manually set the type index to specialized subclass
+    // data layout is ensured to be the same except for the type index
+    static_assert(std::is_base_of_v<MapBaseObj, MapObjType>);
+    static_assert(sizeof(MapObjType) == sizeof(MapBaseObj));

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Similar to the `Empty` function, this `static_assert` is confusing within the context of `DenseMapBaseObj` and should likely be removed for clarity. It appears to be a copy-paste from `SmallMapBaseObj` where the size comparison is valid.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REACTOR] Cleanup and improve map array containers [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen merged PR #462:
URL: https://github.com/apache/tvm-ffi/pull/462


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REACTOR] Cleanup and improve map array containers [tvm-ffi]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #462:
URL: https://github.com/apache/tvm-ffi/pull/462#discussion_r2822734580


##########
include/tvm/ffi/container/map_base.h:
##########
@@ -0,0 +1,1444 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/container/map_base.h
+ * \brief Base class for Map container types.
+ */
+#ifndef TVM_FFI_CONTAINER_MAP_BASE_H_
+#define TVM_FFI_CONTAINER_MAP_BASE_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/container/container_details.h>
+#include <tvm/ffi/memory.h>
+#include <tvm/ffi/object.h>
+#include <tvm/ffi/optional.h>
+
+#include <algorithm>
+#include <limits>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/// \cond Doxygen_Suppress
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+#define TVM_FFI_MAP_FAIL_IF_CHANGED() \
+  TVM_FFI_ICHECK(state_marker == self->state_marker) << "Concurrent modification of the Map";
+#else
+#define TVM_FFI_MAP_FAIL_IF_CHANGED()
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+/// \endcond
+
+/*!
+ * \brief Shared content of all specializations of hash map
+ *
+ * MapBaseObj is transparent to the FFI type system (no type index),
+ * following the same pattern as BytesObjBase.
+ */
+class MapBaseObj : public Object {
+ public:
+  /*! \brief Type of the keys in the hash map */
+  using key_type = Any;
+  /*! \brief Type of the values in the hash map */
+  using mapped_type = Any;
+  /*! \brief Type of value stored in the hash map */
+  using KVType = std::pair<Any, Any>;
+  /// \cond Doxygen_Suppress
+  /*! \brief Type of raw storage of the key-value pair in the hash map */
+  struct KVRawStorageType {
+    TVMFFIAny first;
+    TVMFFIAny second;
+  };
+  /// \endcond
+  /*! \brief Iterator class */
+  class iterator;
+
+  static_assert(std::is_standard_layout_v<KVType>, "KVType is not standard layout");
+  static_assert(sizeof(KVType) == 32, "sizeof(KVType) incorrect");
+
+  /*!
+   * \brief Number of elements in the MapBaseObj
+   * \return The result
+   */
+  size_t size() const { return size_; }
+  /*!
+   * \brief Count the number of times a key exists in the hash map
+   * \param key The indexing key
+   * \return The result, 0 or 1
+   */
+  size_t count(const key_type& key) const;
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The const reference to the value
+   */
+  const mapped_type& at(const key_type& key) const;
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The mutable reference to the value
+   */
+  mapped_type& at(const key_type& key);
+  /*! \return begin iterator */
+  iterator begin() const;
+  /*! \return end iterator */
+  iterator end() const;
+  /*!
+   * \brief Index value associated with a key
+   * \param key The indexing key
+   * \return The iterator of the entry associated with the key, end iterator if not exists
+   */
+  iterator find(const key_type& key) const;
+  /*!
+   * \brief Erase the entry associated with the iterator
+   * \param position The iterator
+   */
+  void erase(const iterator& position);
+  /*!
+   * \brief Erase the entry associated with the key, do nothing if not exists
+   * \param key The indexing key
+   */
+  void erase(const key_type& key) { erase(find(key)); }
+
+  /*!
+   * \brief clear all entries
+   */
+  void clear();
+
+  /// \cond Doxygen_Suppress
+  class iterator {
+   public:
+    using iterator_category = std::forward_iterator_tag;
+    using difference_type = int64_t;
+    using value_type = KVType;
+    using pointer = KVType*;
+    using reference = KVType&;
+/*! \brief Default constructor */
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    iterator() : state_marker(0), index(0), self(nullptr) {}
+#else
+    iterator() : index(0), self(nullptr) {}
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    /*! \brief Compare iterators */
+    bool operator==(const iterator& other) const {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      return index == other.index && self == other.self;
+    }
+    /*! \brief Compare iterators */
+    bool operator!=(const iterator& other) const { return !(*this == other); }
+    /*! \brief De-reference iterators */
+    pointer operator->() const;
+    /*! \brief De-reference iterators */
+    reference operator*() const {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      return *((*this).operator->());
+    }
+    /*! \brief Prefix self increment, e.g. ++iter */
+    iterator& operator++();
+    /*! \brief Prefix self decrement, e.g. --iter */
+    iterator& operator--();
+    /*! \brief Suffix self increment */
+    iterator operator++(int) {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      iterator copy = *this;
+      ++(*this);
+      return copy;
+    }
+    /*! \brief Suffix self decrement */
+    iterator operator--(int) {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      iterator copy = *this;
+      --(*this);
+      return copy;
+    }
+
+   protected:
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    uint64_t state_marker;
+    /*! \brief Construct by value */
+    iterator(uint64_t index, const MapBaseObj* self)
+        : state_marker(self->state_marker), index(index), self(self) {}
+
+#else
+    iterator(uint64_t index, const MapBaseObj* self) : index(index), self(self) {}
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    /*! \brief The position on the array */
+    uint64_t index;
+    /*! \brief The container it points to */
+    const MapBaseObj* self;
+
+    friend class DenseMapBaseObj;
+    friend class SmallMapBaseObj;
+  };
+  /// \endcond
+
+ protected:
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+  uint64_t state_marker;
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+  /*!
+   * \brief Create an empty container
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static inline ObjectPtr<Object> Empty();
+  /*!
+   * \brief Create the map using contents from the given iterators.
+   * \param first Begin of iterator
+   * \param last End of iterator
+   * \tparam MapObjType The type of map object
+   * \tparam IterType The type of iterator
+   * \return ObjectPtr to the map created
+   */
+  template <typename MapObjType, typename IterType>
+  static inline ObjectPtr<Object> CreateFromRange(IterType first, IterType last);
+  /*!
+   * \brief InsertMaybeReHash an entry into the given hash map
+   * \param kv The entry to be inserted
+   * \param map The pointer to the map, can be changed if re-hashing happens
+   * \tparam MapObjType The type of map object
+   */
+  template <typename MapObjType>
+  static inline void InsertMaybeReHash(KVType&& kv, ObjectPtr<Object>* map);
+  /*!
+   * \brief Create an empty container with elements copying from another SmallMapBaseObj
+   * \param from The source container
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static inline ObjectPtr<Object> CopyFrom(MapBaseObj* from);
+
+  /*!
+   * \brief data pointer to the data region of the map.
+   * \note For immutable inplace small map we do not need data_,
+   *       but we keep it here for future compact with mutable container.
+   */
+  void* data_;
+  /*! \brief number of entries in the container */
+  uint64_t size_;
+  /*! \brief number of slots  */
+  uint64_t slots_;
+  /*!
+   * \brief Small layout tag mask
+   * \note The most significant bit is used to indicate the small map layout.
+   */
+  static constexpr uint64_t kSmallTagMask = static_cast<uint64_t>(1) << 63;
+  /*!
+   * \brief Check if the map is a small map
+   * \return True if the map is a small map
+   */
+  bool IsSmallMap() const { return (slots_ & kSmallTagMask) != 0ull; }
+  /*!
+   * \brief Optional data deleter when data is allocated separately
+   *        and its deletion is not managed by MapBaseObj::deleter_.
+   */
+  void (*data_deleter_)(void*) = nullptr;
+  // Reference class
+  friend class SmallMapBaseObj;
+  friend class DenseMapBaseObj;
+
+  template <typename, typename>
+  friend struct TypeTraits;
+};
+
+/*! \brief A specialization of hash map that implements the idea of array-based hash map.
+ * Another reference implementation can be found [1].
+ *
+ * A. Overview
+ *
+ * DenseMapBaseObj did several improvements over traditional separate chaining hash,
+ * in terms of cache locality, memory footprints and data organization.
+ *
+ * A1. Implicit linked list. For better cache locality, instead of using linked list
+ * explicitly for each bucket, we store list data into a single array that spans contiguously
+ * in memory, and then carefully design access patterns to make sure most of them fall into
+ * a single cache line.
+ *
+ * A2. 1-byte metadata. There is only 1 byte overhead for each slot in the array to indexing and
+ * traversal. This can be divided in 3 parts.
+ * 1) Reserved code: (0b11111111)_2 indicates a slot is empty; (0b11111110)_2 indicates protected,
+ * which means the slot is empty but not allowed to be written.
+ * 2) If not empty or protected, the highest bit is used to indicate whether data in the slot is
+ * head of a linked list.
+ * 3) The rest 7 bits are used as the "next pointer" (i.e. pointer to the next element). On 64-bit
+ * architecture, an ordinary pointer can take up to 8 bytes, which is not acceptable overhead when
+ * dealing with 16-byte ObjectRef pairs. Based on a commonly noticed fact that the lists are
+ * relatively short (length <= 3) in hash maps, we follow [1]'s idea that only allows the pointer to
+ * be one of the 126 possible values, i.e. if the next element of i-th slot is (i + x)-th element,
+ * then x must be one of the 126 pre-defined values.
+ *
+ * A3. Data blocking. We organize the array in the way that every 16 elements forms a data block.
+ * The 16-byte metadata of those 16 elements are stored together, followed by the real data, i.e.
+ * 16 key-value pairs.
+ *
+ * B. Implementation details
+ *
+ * B1. Power-of-2 table size and Fibonacci Hashing. We use power-of-two as table size to avoid
+ * modulo for more efficient arithmetics. To make the hash-to-slot mapping distribute more evenly,
+ * we use the Fibonacci Hashing [2] trick.
+ *
+ * B2. Traverse a linked list in the array.
+ * 1) List head. Assume Fibonacci Hashing maps a given key to slot i, if metadata at slot i
+ * indicates that it is list head, then we found the head; otherwise the list is empty. No probing
+ * is done in this procedure. 2) Next element. To find the next element of a non-empty slot i, we
+ * look at the last 7 bits of the metadata at slot i. If they are all zeros, then it is the end of
+ * list; otherwise, we know that the next element is (i + candidates[the-last-7-bits]).
+ *
+ * B3. InsertMaybeReHash an element. Following B2, we first traverse the linked list to see if this
+ * element is in the linked list, and if not, we put it at the end by probing the next empty
+ * position in one of the 126 candidate positions. If the linked list does not even exist, but the
+ * slot for list head has been occupied by another linked list, we should find this intruder another
+ * place.
+ *
+ * B4. Quadratic probing with triangle numbers. In open address hashing, it is provable that probing
+ * with triangle numbers can traverse power-of-2-sized table [3]. In our algorithm, we follow the
+ * suggestion in [1] that also use triangle numbers for "next pointer" as well as sparing for list
+ * head.
+ *
+ * [1] https://github.com/skarupke/flat_hash_map
+ * [2] https://programmingpraxis.com/2018/06/19/fibonacci-hash/
+ * [3] https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/
+ */
+class DenseMapBaseObj : public MapBaseObj {
+ private:
+  /*! \brief The number of elements in a memory block */
+  static constexpr int kBlockCap = 16;
+  /*! \brief Maximum load factor of the hash map */
+  static constexpr double kMaxLoadFactor = 0.99;
+  /*! \brief Binary representation of the metadata of an empty slot */
+  static constexpr uint8_t kEmptySlot = static_cast<uint8_t>(0b11111111);
+  /*! \brief Binary representation of the metadata of a protected slot */
+  static constexpr uint8_t kProtectedSlot = static_cast<uint8_t>(0b11111110);
+  /*! \brief Number of probing choices available */
+  static constexpr int kNumJumpDists = 126;
+  /*! \brief Index indicator to indicate an invalid index */
+  static constexpr uint64_t kInvalidIndex = std::numeric_limits<uint64_t>::max();
+  /*! \brief Head of the implicit linked list */
+  struct ListNode;
+  /*! \brief item type of the dense map, including a kv data and prev/next pointer */
+  struct ItemType {
+    KVType data;
+    uint64_t prev = kInvalidIndex;
+    uint64_t next = kInvalidIndex;
+
+    explicit ItemType(KVType&& data) : data(std::move(data)) {}
+    explicit ItemType(key_type key, mapped_type value) : data(std::move(key), std::move(value)) {}
+  };
+  /*! \brief POD type of a block of memory */
+  struct Block {
+    uint8_t bytes[kBlockCap + kBlockCap * sizeof(ItemType)];
+  };
+  static_assert(sizeof(Block) == kBlockCap * (sizeof(ItemType) + 1), "sizeof(Block) incorrect");
+  static_assert(std::is_standard_layout_v<Block>, "Block is not standard layout");
+
+  /*!
+   * \brief Deleter for the Block
+   * \param data The pointer to the Block
+   */
+  static void BlockDeleter(void* data) { delete[] static_cast<Block*>(data); }
+
+ public:
+  using MapBaseObj::iterator;
+
+  /*!
+   * \brief Return the number of usable slots for Dense layout (MSB clear => identity).
+   * \return The number of usable slots
+   */
+  uint64_t NumSlots() const { return slots_; }
+
+  /*!
+   * \brief Destroy the DenseMapBaseObj
+   */
+  ~DenseMapBaseObj() { this->Reset(); }
+  /*! \return The number of elements of the key */
+  size_t count(const key_type& key) const { return !Search(key).IsNone(); }
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The const reference to the value
+   */
+  const mapped_type& at(const key_type& key) const { return At(key); }
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The mutable reference to the value
+   */
+  mapped_type& at(const key_type& key) { return At(key); }
+  /*!
+   * \brief Index value associated with a key
+   * \param key The indexing key
+   * \return The iterator of the entry associated with the key, end iterator if not exists
+   */
+  iterator find(const key_type& key) const {
+    ListNode node = Search(key);
+    return node.IsNone() ? end() : iterator(node.index, this);
+  }
+  /*!
+   * \brief Erase the entry associated with the iterator
+   * \param position The iterator
+   */
+  void erase(const iterator& position) {
+    uint64_t index = position.index;
+    if (position.self != nullptr && index <= this->NumSlots()) {
+      Erase(ListNode(index, this));
+    }
+  }
+  /*! \return begin iterator */
+  iterator begin() const { return iterator(iter_list_head_, this); }
+  /*! \return end iterator */
+  iterator end() const { return iterator(kInvalidIndex, this); }
+
+  /*!
+   * \brief clear all entries
+   */
+  void clear() {
+    uint64_t n_blocks = CalcNumBlocks(this->NumSlots());
+    for (uint64_t bi = 0; bi < n_blocks; ++bi) {
+      uint8_t* meta_ptr = GetBlock(bi)->bytes;
+      ItemType* data_ptr = reinterpret_cast<ItemType*>(GetBlock(bi)->bytes + kBlockCap);
+      for (int j = 0; j < kBlockCap; ++j, ++meta_ptr, ++data_ptr) {
+        uint8_t& meta = *meta_ptr;
+        if (meta != kProtectedSlot && meta != kEmptySlot) {
+          meta = kEmptySlot;
+          data_ptr->ItemType::~ItemType();
+        }
+      }
+    }
+    size_ = 0;
+    iter_list_head_ = kInvalidIndex;
+    iter_list_tail_ = kInvalidIndex;
+  }
+
+ private:
+  Block* GetBlock(size_t index) const { return static_cast<Block*>(data_) + index; }
+  /*!
+   * \brief Unlink the entry from iterator list
+   * \param node The node to be unlinked
+   * \note This function is usually used before deletion,
+   *       and it does not change data content of the node.
+   */
+  void IterListUnlink(ListNode node) {
+    // update head and tail of iterator list if needed
+    if (node.Item().prev == kInvalidIndex) {
+      iter_list_head_ = node.Item().next;
+    } else {
+      ListNode prev_node(node.Item().prev, this);
+      prev_node.Item().next = node.Item().next;
+    }
+    if (node.Item().next == kInvalidIndex) {
+      iter_list_tail_ = node.Item().prev;
+    } else {
+      ListNode next_node(node.Item().next, this);
+      next_node.Item().prev = node.Item().prev;
+    }
+  }
+  /*!
+   * \brief Insert the entry into tail of iterator list
+   * \param node The node to be inserted
+   * \note this function does not change data content of the node.
+   */
+  void IterListPushBack(ListNode node) {
+    node.Item().prev = iter_list_tail_;
+    node.Item().next = kInvalidIndex;
+    if (iter_list_tail_ != kInvalidIndex) {
+      ListNode prev_node(iter_list_tail_, this);
+      prev_node.Item().next = node.index;
+    }
+    if (iter_list_head_ == kInvalidIndex) {
+      iter_list_head_ = node.index;
+    }
+    iter_list_tail_ = node.index;
+  }
+  /*!
+   * \brief Replace node src by dst in the iter list
+   * \param src The source node
+   * \param dst The destination node, must be empty
+   * \note This function does not change data content of the nodes,
+   *       which needs to be updated by the caller.
+   */
+  void IterListReplaceNodeBy(ListNode src, ListNode dst) {
+    // set link correctly on the dst
+    dst.Item().prev = src.Item().prev;
+    dst.Item().next = src.Item().next;
+    // update prev and next of dst
+    if (dst.Item().prev == kInvalidIndex) {
+      iter_list_head_ = dst.index;
+    } else {
+      ListNode prev_node(dst.Item().prev, this);
+      prev_node.Item().next = dst.index;
+    }
+    if (dst.Item().next == kInvalidIndex) {
+      iter_list_tail_ = dst.index;
+    } else {
+      ListNode next_node(dst.Item().next, this);
+      next_node.Item().prev = dst.index;
+    }
+  }
+  /*!
+   * \brief Search for the given key
+   * \param key The key
+   * \return ListNode that associated with the key
+   */
+  ListNode Search(const key_type& key) const {
+    if (this->size_ == 0) {
+      return ListNode();
+    }
+    for (ListNode iter = GetListHead(AnyHash()(key)); !iter.IsNone(); iter.MoveToNext(this)) {
+      if (AnyEqual()(key, iter.Key())) {
+        return iter;
+      }
+    }
+    return ListNode();
+  }
+  /*!
+   * \brief Search for the given key, throw exception if not exists
+   * \param key The key
+   * \return ListNode that associated with the key
+   */
+  mapped_type& At(const key_type& key) const {
+    ListNode iter = Search(key);
+    if (iter.IsNone()) {
+      TVM_FFI_THROW(KeyError) << "key is not in Map";
+    }
+    return iter.Val();
+  }
+  /*!
+   * \brief Try to insert a key, or do nothing if already exists
+   * \param key The indexing key
+   * \param result The linked-list entry found or just constructed
+   * \return A boolean, indicating if actual insertion happens
+   */
+  bool TryInsert(const key_type& key, ListNode* result) {
+    if (slots_ == 0) {
+      return false;
+    }
+    // required that `iter` to be the head of a linked list through which we can iterator
+    ListNode iter = IndexFromHash(AnyHash()(key));
+    // `iter` can be: 1) empty; 2) body of an irrelevant list; 3) head of the relevant list
+    // Case 1: empty
+    if (iter.IsEmpty()) {
+      iter.NewHead(ItemType(key, Any(nullptr)));
+      this->size_ += 1;
+      *result = iter;
+      return true;
+    }
+    // Case 2: body of an irrelevant list
+    if (!iter.IsHead()) {
+      // we move the elements around and construct the single-element linked list
+      return IsFull() ? false : TrySpareListHead(iter, key, result);
+    }
+    // Case 3: head of the relevant list
+    // we iterate through the linked list until the end
+    // make sure `iter` is the previous element of `next`
+    ListNode next = iter;
+    do {
+      // find equal item, do not insert
+      if (AnyEqual()(key, next.Key())) {
+        // we plan to take next, so we need to unlink it from iterator list
+        IterListUnlink(next);
+        *result = next;
+        return true;
+      }
+      // make sure `iter` is the previous element of `next`
+      iter = next;
+    } while (next.MoveToNext(this));
+    // `iter` is the tail of the linked list
+    // always check capacity before insertion
+    if (IsFull()) {
+      return false;
+    }
+    // find the next empty slot
+    uint8_t jump;
+    if (!iter.GetNextEmpty(this, &jump, result)) {
+      return false;
+    }
+    result->NewTail(ItemType(key, Any(nullptr)));
+    // link `iter` to `empty`, and move forward
+    iter.SetJump(jump);
+    this->size_ += 1;
+    return true;
+  }
+  /*!
+   * \brief Spare an entry to be the head of a linked list.
+   * As described in B3, during insertion, it is possible that the entire linked list does not
+   * exist, but the slot of its head has been occupied by other linked lists. In this case, we need
+   * to spare the slot by moving away the elements to another valid empty one to make insertion
+   * possible.
+   * \param target The given entry to be spared
+   * \param key The indexing key
+   * \param result The linked-list entry constructed as the head
+   * \return A boolean, if actual insertion happens
+   */
+  bool TrySpareListHead(ListNode target, const key_type& key, ListNode* result) {
+    // `target` is not the head of the linked list
+    // move the original item of `target` (if any)
+    // and construct new item on the position `target`
+    // To make `target` empty, we
+    // 1) find `w` the previous element of `target` in the linked list
+    // 2) copy the linked list starting from `r = target`
+    // 3) paste them after `w`
+    // read from the linked list after `r`
+    ListNode r = target;
+    // write to the tail of `w`
+    ListNode w = target.FindPrev(this);
+    // after `target` is moved, we disallow writing to the slot
+    bool is_first = true;
+    uint8_t r_meta, jump;
+    ListNode empty;
+    do {
+      // `jump` describes how `w` is jumped to `empty`
+      // rehash if there is no empty space after `w`
+      if (!w.GetNextEmpty(this, &jump, &empty)) {
+        return false;
+      }
+      // move `r` to `empty`
+      // first move the data over
+      empty.NewTail(ItemType(std::move(r.Data())));
+      // then move link list chain of r to empty
+      // this needs to happen after NewTail so empty's prev/next get updated
+      IterListReplaceNodeBy(r, empty);
+      // explicit call destructor to destroy the item in `r`
+      r.DestructData();
+      // clear the metadata of `r`
+      r_meta = r.Meta();
+      if (is_first) {
+        is_first = false;
+        r.SetProtected();
+      } else {
+        r.SetEmpty();
+      }
+      // link `w` to `empty`, and move forward
+      w.SetJump(jump);
+      w = empty;
+      // move `r` forward as well
+    } while (r.MoveToNext(this, r_meta));
+    // finally we have done moving the linked list
+    // fill data_ into `target`
+    target.NewHead(ItemType(key, Any(nullptr)));
+    this->size_ += 1;
+    *result = target;
+    return true;
+  }
+  /*!
+   * \brief Remove a ListNode
+   * \param iter The node to be removed
+   */
+  void Erase(const ListNode& iter) {
+    this->size_ -= 1;
+    if (!iter.HasNext()) {
+      // `iter` is the last
+      if (!iter.IsHead()) {
+        // cut the link if there is any
+        iter.FindPrev(this).SetJump(0);
+      }
+      // unlink the node from iterator list
+      IterListUnlink(iter);
+      // IMPORTANT: must explicit call destructor `iter` to avoid memory leak
+      // This is because we need to recycle iter's data
+      iter.DestructData();
+      // set the meta data to be empty
+      iter.SetEmpty();
+    } else {
+      ListNode last = iter, prev = iter;
+      for (last.MoveToNext(this); last.HasNext(); prev = last, last.MoveToNext(this)) {
+      }
+      // needs to first unlink iter from the list
+      IterListUnlink(iter);
+      // move data from last to iter
+      iter.Data() = std::move(last.Data());
+      // Move link chain of iter to last as we stores last node to the new iter loc.
+      IterListReplaceNodeBy(last, iter);
+      // IMPORTANT: must explicit call destructor `last` to avoid memory leak
+      // likely we don't need this in this particular case because Any move behavior
+      // keep it here to be safe so code do not depend on specific move behavior of KVType
+      last.DestructData();
+      // set the meta data to be empty
+      last.SetEmpty();
+      prev.SetJump(0);
+    }
+  }
+  /*! \brief Clear the container to empty, release all entries and memory acquired */
+  void Reset() {
+    clear();
+    ReleaseMemory();
+  }
+  /*!
+   * \brief Release the memory acquired by the container without deleting its entries stored inside
+   */
+  void ReleaseMemory() {
+    if (data_ != nullptr) {
+      TVM_FFI_ICHECK(data_deleter_ != nullptr);
+      data_deleter_(data_);
+    }
+    data_ = nullptr;
+    data_deleter_ = nullptr;
+    slots_ = 0;
+    size_ = 0;
+    fib_shift_ = 63;
+  }
+  /*!
+   * \brief Create an empty container
+   * \param fib_shift The fib shift provided
+   * \param n_slots Number of slots required, should be power-of-two
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static ObjectPtr<Object> Empty(uint32_t fib_shift, uint64_t n_slots) {
+    // Ensure even slot count (power-of-two expected by callers; this guard
+    // makes the method robust if a non-even value slips through).
+    ObjectPtr<DenseMapBaseObj> p = make_object<DenseMapBaseObj>();
+    uint64_t n_blocks = CalcNumBlocks(n_slots);
+    Block* block = new Block[n_blocks];
+    p->data_ = block;
+    // assign block deleter so even if we take re-alloc data
+    // in another shared-lib that may have different malloc/free behavior
+    // it will still be safe.
+    p->data_deleter_ = BlockDeleter;
+    p->SetSlotsAndDenseLayoutTag(n_slots);
+    p->size_ = 0;
+    p->fib_shift_ = fib_shift;
+    p->iter_list_head_ = kInvalidIndex;
+    p->iter_list_tail_ = kInvalidIndex;
+    // manually set the type index to specialized subclass
+    // data layout is ensured to be the same except for the type index
+    static_assert(std::is_base_of_v<MapBaseObj, MapObjType>);
+    static_assert(sizeof(MapObjType) == sizeof(DenseMapBaseObj));
+    p->header_.type_index = MapObjType::RuntimeTypeIndex();

Review Comment:
   ![critical](https://www.gstatic.com/codereviewagent/critical.svg)
   
   The `static_assert` on line 726 is incorrect and will fail compilation.
   
   `MapObjType` (which will be a type like `tvm::ffi::MapObj`) and `DenseMapBaseObj` do not have the same size. `DenseMapBaseObj` inherits from `MapBaseObj` and adds several data members (`fib_shift_`, `iter_list_head_`, `iter_list_tail_`), making it larger than `MapObj`, which has no additional data members.
   
   This points to a more fundamental issue with the object creation on line 710:
   ```cpp
   ObjectPtr<DenseMapBaseObj> p = make_object<DenseMapBaseObj>();
   ```
   This line will also fail because `DenseMapBaseObj` is not a registered FFI type (it lacks a `_type_index` and related static members), so `make_object` cannot be used on it.
   
   A similar issue is present in the `CopyFrom` method for `DenseMapBaseObj`.
   
   This design seems to assume that an object of type `DenseMapBaseObj` can be created and then have its type index changed to `MapObjType`, which is only safe if they have the same size and layout. Since that's not the case here, the instantiation logic for `DenseMapBaseObj` needs to be revisited.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REACTOR] Cleanup and improve map array containers [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #462:
URL: https://github.com/apache/tvm-ffi/pull/462#issuecomment-3921278204

   
   /gemini review
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REACTOR] Cleanup and improve map array containers [tvm-ffi]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #462:
URL: https://github.com/apache/tvm-ffi/pull/462#discussion_r2822754947


##########
include/tvm/ffi/container/map_base.h:
##########
@@ -0,0 +1,1444 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/container/map_base.h
+ * \brief Base class for Map container types.
+ */
+#ifndef TVM_FFI_CONTAINER_MAP_BASE_H_
+#define TVM_FFI_CONTAINER_MAP_BASE_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/container/container_details.h>
+#include <tvm/ffi/memory.h>
+#include <tvm/ffi/object.h>
+#include <tvm/ffi/optional.h>
+
+#include <algorithm>
+#include <limits>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/// \cond Doxygen_Suppress
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+#define TVM_FFI_MAP_FAIL_IF_CHANGED() \
+  TVM_FFI_ICHECK(state_marker == self->state_marker) << "Concurrent modification of the Map";
+#else
+#define TVM_FFI_MAP_FAIL_IF_CHANGED()
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+/// \endcond
+
+/*!
+ * \brief Shared content of all specializations of hash map
+ *
+ * MapBaseObj is transparent to the FFI type system (no type index),
+ * following the same pattern as BytesObjBase.
+ */
+class MapBaseObj : public Object {
+ public:
+  /*! \brief Type of the keys in the hash map */
+  using key_type = Any;
+  /*! \brief Type of the values in the hash map */
+  using mapped_type = Any;
+  /*! \brief Type of value stored in the hash map */
+  using KVType = std::pair<Any, Any>;
+  /// \cond Doxygen_Suppress
+  /*! \brief Type of raw storage of the key-value pair in the hash map */
+  struct KVRawStorageType {
+    TVMFFIAny first;
+    TVMFFIAny second;
+  };
+  /// \endcond
+  /*! \brief Iterator class */
+  class iterator;
+
+  static_assert(std::is_standard_layout_v<KVType>, "KVType is not standard layout");
+  static_assert(sizeof(KVType) == 32, "sizeof(KVType) incorrect");
+
+  /*!
+   * \brief Number of elements in the MapBaseObj
+   * \return The result
+   */
+  size_t size() const { return size_; }
+  /*!
+   * \brief Count the number of times a key exists in the hash map
+   * \param key The indexing key
+   * \return The result, 0 or 1
+   */
+  size_t count(const key_type& key) const;
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The const reference to the value
+   */
+  const mapped_type& at(const key_type& key) const;
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The mutable reference to the value
+   */
+  mapped_type& at(const key_type& key);
+  /*! \return begin iterator */
+  iterator begin() const;
+  /*! \return end iterator */
+  iterator end() const;
+  /*!
+   * \brief Index value associated with a key
+   * \param key The indexing key
+   * \return The iterator of the entry associated with the key, end iterator if not exists
+   */
+  iterator find(const key_type& key) const;
+  /*!
+   * \brief Erase the entry associated with the iterator
+   * \param position The iterator
+   */
+  void erase(const iterator& position);
+  /*!
+   * \brief Erase the entry associated with the key, do nothing if not exists
+   * \param key The indexing key
+   */
+  void erase(const key_type& key) { erase(find(key)); }
+
+  /*!
+   * \brief clear all entries
+   */
+  void clear();
+
+  /// \cond Doxygen_Suppress
+  class iterator {
+   public:
+    using iterator_category = std::forward_iterator_tag;
+    using difference_type = int64_t;
+    using value_type = KVType;
+    using pointer = KVType*;
+    using reference = KVType&;
+/*! \brief Default constructor */
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    iterator() : state_marker(0), index(0), self(nullptr) {}
+#else
+    iterator() : index(0), self(nullptr) {}
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    /*! \brief Compare iterators */
+    bool operator==(const iterator& other) const {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      return index == other.index && self == other.self;
+    }
+    /*! \brief Compare iterators */
+    bool operator!=(const iterator& other) const { return !(*this == other); }
+    /*! \brief De-reference iterators */
+    pointer operator->() const;
+    /*! \brief De-reference iterators */
+    reference operator*() const {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      return *((*this).operator->());
+    }
+    /*! \brief Prefix self increment, e.g. ++iter */
+    iterator& operator++();
+    /*! \brief Prefix self decrement, e.g. --iter */
+    iterator& operator--();
+    /*! \brief Suffix self increment */
+    iterator operator++(int) {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      iterator copy = *this;
+      ++(*this);
+      return copy;
+    }
+    /*! \brief Suffix self decrement */
+    iterator operator--(int) {
+      TVM_FFI_MAP_FAIL_IF_CHANGED()
+      iterator copy = *this;
+      --(*this);
+      return copy;
+    }
+
+   protected:
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    uint64_t state_marker;
+    /*! \brief Construct by value */
+    iterator(uint64_t index, const MapBaseObj* self)
+        : state_marker(self->state_marker), index(index), self(self) {}
+
+#else
+    iterator(uint64_t index, const MapBaseObj* self) : index(index), self(self) {}
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+    /*! \brief The position on the array */
+    uint64_t index;
+    /*! \brief The container it points to */
+    const MapBaseObj* self;
+
+    friend class DenseMapBaseObj;
+    friend class SmallMapBaseObj;
+  };
+  /// \endcond
+
+ protected:
+#if TVM_FFI_DEBUG_WITH_ABI_CHANGE
+  uint64_t state_marker;
+#endif  // TVM_FFI_DEBUG_WITH_ABI_CHANGE
+  /*!
+   * \brief Create an empty container
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static inline ObjectPtr<Object> Empty();
+  /*!
+   * \brief Create the map using contents from the given iterators.
+   * \param first Begin of iterator
+   * \param last End of iterator
+   * \tparam MapObjType The type of map object
+   * \tparam IterType The type of iterator
+   * \return ObjectPtr to the map created
+   */
+  template <typename MapObjType, typename IterType>
+  static inline ObjectPtr<Object> CreateFromRange(IterType first, IterType last);
+  /*!
+   * \brief InsertMaybeReHash an entry into the given hash map
+   * \param kv The entry to be inserted
+   * \param map The pointer to the map, can be changed if re-hashing happens
+   * \tparam MapObjType The type of map object
+   */
+  template <typename MapObjType>
+  static inline void InsertMaybeReHash(KVType&& kv, ObjectPtr<Object>* map);
+  /*!
+   * \brief Create an empty container with elements copying from another SmallMapBaseObj
+   * \param from The source container
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static inline ObjectPtr<Object> CopyFrom(MapBaseObj* from);
+
+  /*!
+   * \brief data pointer to the data region of the map.
+   * \note For immutable inplace small map we do not need data_,
+   *       but we keep it here for future compact with mutable container.
+   */
+  void* data_;
+  /*! \brief number of entries in the container */
+  uint64_t size_;
+  /*! \brief number of slots  */
+  uint64_t slots_;
+  /*!
+   * \brief Small layout tag mask
+   * \note The most significant bit is used to indicate the small map layout.
+   */
+  static constexpr uint64_t kSmallTagMask = static_cast<uint64_t>(1) << 63;
+  /*!
+   * \brief Check if the map is a small map
+   * \return True if the map is a small map
+   */
+  bool IsSmallMap() const { return (slots_ & kSmallTagMask) != 0ull; }
+  /*!
+   * \brief Optional data deleter when data is allocated separately
+   *        and its deletion is not managed by MapBaseObj::deleter_.
+   */
+  void (*data_deleter_)(void*) = nullptr;
+  // Reference class
+  friend class SmallMapBaseObj;
+  friend class DenseMapBaseObj;
+
+  template <typename, typename>
+  friend struct TypeTraits;
+};
+
+/*! \brief A specialization of hash map that implements the idea of array-based hash map.
+ * Another reference implementation can be found [1].
+ *
+ * A. Overview
+ *
+ * DenseMapBaseObj did several improvements over traditional separate chaining hash,
+ * in terms of cache locality, memory footprints and data organization.
+ *
+ * A1. Implicit linked list. For better cache locality, instead of using linked list
+ * explicitly for each bucket, we store list data into a single array that spans contiguously
+ * in memory, and then carefully design access patterns to make sure most of them fall into
+ * a single cache line.
+ *
+ * A2. 1-byte metadata. There is only 1 byte overhead for each slot in the array to indexing and
+ * traversal. This can be divided in 3 parts.
+ * 1) Reserved code: (0b11111111)_2 indicates a slot is empty; (0b11111110)_2 indicates protected,
+ * which means the slot is empty but not allowed to be written.
+ * 2) If not empty or protected, the highest bit is used to indicate whether data in the slot is
+ * head of a linked list.
+ * 3) The rest 7 bits are used as the "next pointer" (i.e. pointer to the next element). On 64-bit
+ * architecture, an ordinary pointer can take up to 8 bytes, which is not acceptable overhead when
+ * dealing with 16-byte ObjectRef pairs. Based on a commonly noticed fact that the lists are
+ * relatively short (length <= 3) in hash maps, we follow [1]'s idea that only allows the pointer to
+ * be one of the 126 possible values, i.e. if the next element of i-th slot is (i + x)-th element,
+ * then x must be one of the 126 pre-defined values.
+ *
+ * A3. Data blocking. We organize the array in the way that every 16 elements forms a data block.
+ * The 16-byte metadata of those 16 elements are stored together, followed by the real data, i.e.
+ * 16 key-value pairs.
+ *
+ * B. Implementation details
+ *
+ * B1. Power-of-2 table size and Fibonacci Hashing. We use power-of-two as table size to avoid
+ * modulo for more efficient arithmetics. To make the hash-to-slot mapping distribute more evenly,
+ * we use the Fibonacci Hashing [2] trick.
+ *
+ * B2. Traverse a linked list in the array.
+ * 1) List head. Assume Fibonacci Hashing maps a given key to slot i, if metadata at slot i
+ * indicates that it is list head, then we found the head; otherwise the list is empty. No probing
+ * is done in this procedure. 2) Next element. To find the next element of a non-empty slot i, we
+ * look at the last 7 bits of the metadata at slot i. If they are all zeros, then it is the end of
+ * list; otherwise, we know that the next element is (i + candidates[the-last-7-bits]).
+ *
+ * B3. InsertMaybeReHash an element. Following B2, we first traverse the linked list to see if this
+ * element is in the linked list, and if not, we put it at the end by probing the next empty
+ * position in one of the 126 candidate positions. If the linked list does not even exist, but the
+ * slot for list head has been occupied by another linked list, we should find this intruder another
+ * place.
+ *
+ * B4. Quadratic probing with triangle numbers. In open address hashing, it is provable that probing
+ * with triangle numbers can traverse power-of-2-sized table [3]. In our algorithm, we follow the
+ * suggestion in [1] that also use triangle numbers for "next pointer" as well as sparing for list
+ * head.
+ *
+ * [1] https://github.com/skarupke/flat_hash_map
+ * [2] https://programmingpraxis.com/2018/06/19/fibonacci-hash/
+ * [3] https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/
+ */
+class DenseMapBaseObj : public MapBaseObj {
+ private:
+  /*! \brief The number of elements in a memory block */
+  static constexpr int kBlockCap = 16;
+  /*! \brief Maximum load factor of the hash map */
+  static constexpr double kMaxLoadFactor = 0.99;
+  /*! \brief Binary representation of the metadata of an empty slot */
+  static constexpr uint8_t kEmptySlot = static_cast<uint8_t>(0b11111111);
+  /*! \brief Binary representation of the metadata of a protected slot */
+  static constexpr uint8_t kProtectedSlot = static_cast<uint8_t>(0b11111110);
+  /*! \brief Number of probing choices available */
+  static constexpr int kNumJumpDists = 126;
+  /*! \brief Index indicator to indicate an invalid index */
+  static constexpr uint64_t kInvalidIndex = std::numeric_limits<uint64_t>::max();
+  /*! \brief Head of the implicit linked list */
+  struct ListNode;
+  /*! \brief item type of the dense map, including a kv data and prev/next pointer */
+  struct ItemType {
+    KVType data;
+    uint64_t prev = kInvalidIndex;
+    uint64_t next = kInvalidIndex;
+
+    explicit ItemType(KVType&& data) : data(std::move(data)) {}
+    explicit ItemType(key_type key, mapped_type value) : data(std::move(key), std::move(value)) {}
+  };
+  /*! \brief POD type of a block of memory */
+  struct Block {
+    uint8_t bytes[kBlockCap + kBlockCap * sizeof(ItemType)];
+  };
+  static_assert(sizeof(Block) == kBlockCap * (sizeof(ItemType) + 1), "sizeof(Block) incorrect");
+  static_assert(std::is_standard_layout_v<Block>, "Block is not standard layout");
+
+  /*!
+   * \brief Deleter for the Block
+   * \param data The pointer to the Block
+   */
+  static void BlockDeleter(void* data) { delete[] static_cast<Block*>(data); }
+
+ public:
+  using MapBaseObj::iterator;
+
+  /*!
+   * \brief Return the number of usable slots for Dense layout (MSB clear => identity).
+   * \return The number of usable slots
+   */
+  uint64_t NumSlots() const { return slots_; }
+
+  /*!
+   * \brief Destroy the DenseMapBaseObj
+   */
+  ~DenseMapBaseObj() { this->Reset(); }
+  /*! \return The number of elements of the key */
+  size_t count(const key_type& key) const { return !Search(key).IsNone(); }
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The const reference to the value
+   */
+  const mapped_type& at(const key_type& key) const { return At(key); }
+  /*!
+   * \brief Index value associated with a key, throw exception if the key does not exist
+   * \param key The indexing key
+   * \return The mutable reference to the value
+   */
+  mapped_type& at(const key_type& key) { return At(key); }
+  /*!
+   * \brief Index value associated with a key
+   * \param key The indexing key
+   * \return The iterator of the entry associated with the key, end iterator if not exists
+   */
+  iterator find(const key_type& key) const {
+    ListNode node = Search(key);
+    return node.IsNone() ? end() : iterator(node.index, this);
+  }
+  /*!
+   * \brief Erase the entry associated with the iterator
+   * \param position The iterator
+   */
+  void erase(const iterator& position) {
+    uint64_t index = position.index;
+    if (position.self != nullptr && index <= this->NumSlots()) {
+      Erase(ListNode(index, this));
+    }
+  }
+  /*! \return begin iterator */
+  iterator begin() const { return iterator(iter_list_head_, this); }
+  /*! \return end iterator */
+  iterator end() const { return iterator(kInvalidIndex, this); }
+
+  /*!
+   * \brief clear all entries
+   */
+  void clear() {
+    uint64_t n_blocks = CalcNumBlocks(this->NumSlots());
+    for (uint64_t bi = 0; bi < n_blocks; ++bi) {
+      uint8_t* meta_ptr = GetBlock(bi)->bytes;
+      ItemType* data_ptr = reinterpret_cast<ItemType*>(GetBlock(bi)->bytes + kBlockCap);
+      for (int j = 0; j < kBlockCap; ++j, ++meta_ptr, ++data_ptr) {
+        uint8_t& meta = *meta_ptr;
+        if (meta != kProtectedSlot && meta != kEmptySlot) {
+          meta = kEmptySlot;
+          data_ptr->ItemType::~ItemType();
+        }
+      }
+    }
+    size_ = 0;
+    iter_list_head_ = kInvalidIndex;
+    iter_list_tail_ = kInvalidIndex;
+  }
+
+ private:
+  Block* GetBlock(size_t index) const { return static_cast<Block*>(data_) + index; }
+  /*!
+   * \brief Unlink the entry from iterator list
+   * \param node The node to be unlinked
+   * \note This function is usually used before deletion,
+   *       and it does not change data content of the node.
+   */
+  void IterListUnlink(ListNode node) {
+    // update head and tail of iterator list if needed
+    if (node.Item().prev == kInvalidIndex) {
+      iter_list_head_ = node.Item().next;
+    } else {
+      ListNode prev_node(node.Item().prev, this);
+      prev_node.Item().next = node.Item().next;
+    }
+    if (node.Item().next == kInvalidIndex) {
+      iter_list_tail_ = node.Item().prev;
+    } else {
+      ListNode next_node(node.Item().next, this);
+      next_node.Item().prev = node.Item().prev;
+    }
+  }
+  /*!
+   * \brief Insert the entry into tail of iterator list
+   * \param node The node to be inserted
+   * \note this function does not change data content of the node.
+   */
+  void IterListPushBack(ListNode node) {
+    node.Item().prev = iter_list_tail_;
+    node.Item().next = kInvalidIndex;
+    if (iter_list_tail_ != kInvalidIndex) {
+      ListNode prev_node(iter_list_tail_, this);
+      prev_node.Item().next = node.index;
+    }
+    if (iter_list_head_ == kInvalidIndex) {
+      iter_list_head_ = node.index;
+    }
+    iter_list_tail_ = node.index;
+  }
+  /*!
+   * \brief Replace node src by dst in the iter list
+   * \param src The source node
+   * \param dst The destination node, must be empty
+   * \note This function does not change data content of the nodes,
+   *       which needs to be updated by the caller.
+   */
+  void IterListReplaceNodeBy(ListNode src, ListNode dst) {
+    // set link correctly on the dst
+    dst.Item().prev = src.Item().prev;
+    dst.Item().next = src.Item().next;
+    // update prev and next of dst
+    if (dst.Item().prev == kInvalidIndex) {
+      iter_list_head_ = dst.index;
+    } else {
+      ListNode prev_node(dst.Item().prev, this);
+      prev_node.Item().next = dst.index;
+    }
+    if (dst.Item().next == kInvalidIndex) {
+      iter_list_tail_ = dst.index;
+    } else {
+      ListNode next_node(dst.Item().next, this);
+      next_node.Item().prev = dst.index;
+    }
+  }
+  /*!
+   * \brief Search for the given key
+   * \param key The key
+   * \return ListNode that associated with the key
+   */
+  ListNode Search(const key_type& key) const {
+    if (this->size_ == 0) {
+      return ListNode();
+    }
+    for (ListNode iter = GetListHead(AnyHash()(key)); !iter.IsNone(); iter.MoveToNext(this)) {
+      if (AnyEqual()(key, iter.Key())) {
+        return iter;
+      }
+    }
+    return ListNode();
+  }
+  /*!
+   * \brief Search for the given key, throw exception if not exists
+   * \param key The key
+   * \return ListNode that associated with the key
+   */
+  mapped_type& At(const key_type& key) const {
+    ListNode iter = Search(key);
+    if (iter.IsNone()) {
+      TVM_FFI_THROW(KeyError) << "key is not in Map";
+    }
+    return iter.Val();
+  }
+  /*!
+   * \brief Try to insert a key, or do nothing if already exists
+   * \param key The indexing key
+   * \param result The linked-list entry found or just constructed
+   * \return A boolean, indicating if actual insertion happens
+   */
+  bool TryInsert(const key_type& key, ListNode* result) {
+    if (slots_ == 0) {
+      return false;
+    }
+    // required that `iter` to be the head of a linked list through which we can iterator
+    ListNode iter = IndexFromHash(AnyHash()(key));
+    // `iter` can be: 1) empty; 2) body of an irrelevant list; 3) head of the relevant list
+    // Case 1: empty
+    if (iter.IsEmpty()) {
+      iter.NewHead(ItemType(key, Any(nullptr)));
+      this->size_ += 1;
+      *result = iter;
+      return true;
+    }
+    // Case 2: body of an irrelevant list
+    if (!iter.IsHead()) {
+      // we move the elements around and construct the single-element linked list
+      return IsFull() ? false : TrySpareListHead(iter, key, result);
+    }
+    // Case 3: head of the relevant list
+    // we iterate through the linked list until the end
+    // make sure `iter` is the previous element of `next`
+    ListNode next = iter;
+    do {
+      // find equal item, do not insert
+      if (AnyEqual()(key, next.Key())) {
+        // we plan to take next, so we need to unlink it from iterator list
+        IterListUnlink(next);
+        *result = next;
+        return true;
+      }
+      // make sure `iter` is the previous element of `next`
+      iter = next;
+    } while (next.MoveToNext(this));
+    // `iter` is the tail of the linked list
+    // always check capacity before insertion
+    if (IsFull()) {
+      return false;
+    }
+    // find the next empty slot
+    uint8_t jump;
+    if (!iter.GetNextEmpty(this, &jump, result)) {
+      return false;
+    }
+    result->NewTail(ItemType(key, Any(nullptr)));
+    // link `iter` to `empty`, and move forward
+    iter.SetJump(jump);
+    this->size_ += 1;
+    return true;
+  }
+  /*!
+   * \brief Spare an entry to be the head of a linked list.
+   * As described in B3, during insertion, it is possible that the entire linked list does not
+   * exist, but the slot of its head has been occupied by other linked lists. In this case, we need
+   * to spare the slot by moving away the elements to another valid empty one to make insertion
+   * possible.
+   * \param target The given entry to be spared
+   * \param key The indexing key
+   * \param result The linked-list entry constructed as the head
+   * \return A boolean, if actual insertion happens
+   */
+  bool TrySpareListHead(ListNode target, const key_type& key, ListNode* result) {
+    // `target` is not the head of the linked list
+    // move the original item of `target` (if any)
+    // and construct new item on the position `target`
+    // To make `target` empty, we
+    // 1) find `w` the previous element of `target` in the linked list
+    // 2) copy the linked list starting from `r = target`
+    // 3) paste them after `w`
+    // read from the linked list after `r`
+    ListNode r = target;
+    // write to the tail of `w`
+    ListNode w = target.FindPrev(this);
+    // after `target` is moved, we disallow writing to the slot
+    bool is_first = true;
+    uint8_t r_meta, jump;
+    ListNode empty;
+    do {
+      // `jump` describes how `w` is jumped to `empty`
+      // rehash if there is no empty space after `w`
+      if (!w.GetNextEmpty(this, &jump, &empty)) {
+        return false;
+      }
+      // move `r` to `empty`
+      // first move the data over
+      empty.NewTail(ItemType(std::move(r.Data())));
+      // then move link list chain of r to empty
+      // this needs to happen after NewTail so empty's prev/next get updated
+      IterListReplaceNodeBy(r, empty);
+      // explicit call destructor to destroy the item in `r`
+      r.DestructData();
+      // clear the metadata of `r`
+      r_meta = r.Meta();
+      if (is_first) {
+        is_first = false;
+        r.SetProtected();
+      } else {
+        r.SetEmpty();
+      }
+      // link `w` to `empty`, and move forward
+      w.SetJump(jump);
+      w = empty;
+      // move `r` forward as well
+    } while (r.MoveToNext(this, r_meta));
+    // finally we have done moving the linked list
+    // fill data_ into `target`
+    target.NewHead(ItemType(key, Any(nullptr)));
+    this->size_ += 1;
+    *result = target;
+    return true;
+  }
+  /*!
+   * \brief Remove a ListNode
+   * \param iter The node to be removed
+   */
+  void Erase(const ListNode& iter) {
+    this->size_ -= 1;
+    if (!iter.HasNext()) {
+      // `iter` is the last
+      if (!iter.IsHead()) {
+        // cut the link if there is any
+        iter.FindPrev(this).SetJump(0);
+      }
+      // unlink the node from iterator list
+      IterListUnlink(iter);
+      // IMPORTANT: must explicit call destructor `iter` to avoid memory leak
+      // This is because we need to recycle iter's data
+      iter.DestructData();
+      // set the meta data to be empty
+      iter.SetEmpty();
+    } else {
+      ListNode last = iter, prev = iter;
+      for (last.MoveToNext(this); last.HasNext(); prev = last, last.MoveToNext(this)) {
+      }
+      // needs to first unlink iter from the list
+      IterListUnlink(iter);
+      // move data from last to iter
+      iter.Data() = std::move(last.Data());
+      // Move link chain of iter to last as we stores last node to the new iter loc.
+      IterListReplaceNodeBy(last, iter);
+      // IMPORTANT: must explicit call destructor `last` to avoid memory leak
+      // likely we don't need this in this particular case because Any move behavior
+      // keep it here to be safe so code do not depend on specific move behavior of KVType
+      last.DestructData();
+      // set the meta data to be empty
+      last.SetEmpty();
+      prev.SetJump(0);
+    }
+  }
+  /*! \brief Clear the container to empty, release all entries and memory acquired */
+  void Reset() {
+    clear();
+    ReleaseMemory();
+  }
+  /*!
+   * \brief Release the memory acquired by the container without deleting its entries stored inside
+   */
+  void ReleaseMemory() {
+    if (data_ != nullptr) {
+      TVM_FFI_ICHECK(data_deleter_ != nullptr);
+      data_deleter_(data_);
+    }
+    data_ = nullptr;
+    data_deleter_ = nullptr;
+    slots_ = 0;
+    size_ = 0;
+    fib_shift_ = 63;
+  }
+  /*!
+   * \brief Create an empty container
+   * \param fib_shift The fib shift provided
+   * \param n_slots Number of slots required, should be power-of-two
+   * \tparam MapObjType The type of map object
+   * \return The object created
+   */
+  template <typename MapObjType>
+  static ObjectPtr<Object> Empty(uint32_t fib_shift, uint64_t n_slots) {
+    // Ensure even slot count (power-of-two expected by callers; this guard
+    // makes the method robust if a non-even value slips through).
+    ObjectPtr<DenseMapBaseObj> p = make_object<DenseMapBaseObj>();

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `TVM_FFI_ICHECK_GT(n_slots, SmallMapBaseObj::kMaxSize)` check from the original `DenseMapObj::Empty` implementation seems to be missing here. This check is a useful safeguard to ensure that `DenseMapBaseObj` is only used for maps larger than what `SmallMapBaseObj` can handle. It was likely removed due to the reordering of class definitions. I recommend re-adding it using the literal value for `kMaxSize`.
   
   ```c
       TVM_FFI_ICHECK_GT(n_slots, 4 /* SmallMapBaseObj::kMaxSize */);
       ObjectPtr<DenseMapBaseObj> p = make_object<DenseMapBaseObj>();
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REACTOR] Cleanup and improve map array containers [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #462:
URL: https://github.com/apache/tvm-ffi/pull/462#issuecomment-3921260307

   /gemini review


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org