Skip to content

Fixed some issues related to intermediate nodes and retrieval/immunization - #1733

Merged
matlabbe merged 7 commits into
introlab:masterfrom
borongyuan:IntermediateNode
Jul 14, 2026
Merged

matlabbe merged 7 commits into
introlab:masterfrom
borongyuan:IntermediateNode

Conversation

@borongyuan

Copy link
Copy Markdown
Contributor

Hi @matlabbe,

We found that when intermediate node was enabled and data recorder mode was used, WM continued to grow even with Rtabmap/MemoryThr set to 1 or 2. This is mainly because the size of WM was used directly when calculating the number of immunized nodes. Since there are intermediate nodes in WM, the number of maxLocalLocationsImmunized is greatly amplified. When counting the number of immunized nodes later, intermediate nodes are skipped, which results in more nodes being immunized and unable to be transferred to LTM. In the previous fix, the method for calculating the size of WM was not updated, so you also mentioned in the PR #1687 that Rtabmap/MemoryThr needs to be manually scaled.

I've added two fixes this time: one is the outer layer fix in Rtabmap.cpp, and the other is the inner layer fix in Memory.cpp. When RGBD/LocalImmunizationRatio, RGBD/MaxLocalRetrieved, and Rtabmap/MaxRetrieved are all 0, the retrieval/immunization part can actually be skipped entirely. It is safest for us to skip the outer layer before the inner fix is ​​fully evaluated and validated. Then I added the getWorkingMemSize() method to the Memory class, which allows ignoreIntermediateNodes when calculating the size. The previous code actually contained a comment for getWorkingMemSize(), so adding this method would be the most appropriate solution.

} // if(_memory->getWorkingMemSize())

WM contains a virtual node, and after consideration, I think it should not be included when calculating the size. This will make subsequent processing simpler. The only virtual node is inserted at the end of Memory::loadDataFromDb(), which is inside Memory::init(). Therefore, during system operation, WM should always contain a unique virtual node. This implementation should be safe. If you feel there is a risk, we can add some assertions. I have carefully considered whether intermediate nodes should be ignored when obtaining the size of WM in various places, but I may still make some mistakes, so please confirm during the review.

Additionally, there may be an issue with the following call to Memory::reactivateSignatures().

//============================================================
// RETRIEVAL 3/3 : Load signatures from the database
//============================================================
if(reactivatedIds.size())
{
// Not important if the loop closure hypothesis don't have all its neighbors loaded,
// only a loop closure link is added...
signaturesRetrieved = _memory->reactivateSignatures(
reactivatedIds,
_maxRetrieved+(unsigned int)retrievalLocalIds.size(), // add path retrieved
timeRetrievalDbAccess);

When the second parameter of Memory::reactivateSignatures() is 0, it does not mean that there is no reactivation, but rather that there is unlimited reactivation. Since reactivatedIds is empty in our configuration, RETRIEVAL 3/3 will be skipped, so this method will not be called. However, this part may need to be checked and fixed later.

I need to submit a PR with existing modifications first, because I see that you are adding support for OpenCV 5, and the modifications also involve this part of the code. Submitting earlier allows for earlier review and merging, reducing the workload of handling conflicts later.

@matlabbe

Copy link
Copy Markdown
Member

What is the use case that is failing for you?

Rtabmap/CreateIntermediateNodes=true
Rtabmap/MemoryThr=?
RGBD/LocalImmunizationRatio=0
RGBD/MaxLocalRetrieved=0
Rtabmap/MaxRetrieved=0
... ???

I think in #1687 I made sure it was doing Transfer/Retrieval (what is expected from the papers) like if intermediate nodes were not used (the count of retrieved nodes or transferred nodes are based on the non-intermediate nodes). I can doublecheck though. For the recording version with Rtabmap/MemoryThr=1 or 2, why even using intermediate nodes? Rtabmap/DetectionRate can be set to 0 to record everything (with Kp/MaxFeatures=-1). I can retest intermediate nodes in data recording mode, though it was not supposed to be used together.

Not convinced we need to change the way working memory size is used (and counting the virtual or not). In particular, for thousands of nodes, we may spend significant time in getWorkingMemSize(), if it is also called multiple times per iteration. I would rater track with a local variable the number of intermediate nodes in Memory during update/retrieval/transfer. However, the only place I see we would want to know about the intermediate nodes is to avoid to scale manually Rtabmap/MemoryThr parameter.

For RGBD/LocalImmunizationRatio, I didn't check explicitly, but it should behave similarly having intermediate nodes or not, because it is a ratio and the numbers compared would include the intermediate nodes if used, or not if not used.

@borongyuan

Copy link
Copy Markdown
Contributor Author

What is the use case that is failing for you?

I tested it using the latest release version of RTAB-Map (v0.23.7), with the following configuration.

Kp\BadSignRatio = 0.0
Mem\BinDataKept = true
Mem\RecentWmRatio = 0.0
Mem\RehearsalSimilarity = 1.0
Mem\STMSize = 1
RGBD\AngularUpdate = 0
RGBD\LinearUpdate = 0
RGBD\LocalImmunizationRatio = 0.0
RGBD\LoopCovLimited = true
RGBD\MaxLocalRetrieved = 0
RGBD\ProximityBySpace = false
Rtabmap\CreateIntermediateNodes = true
Rtabmap\DetectionRate = 1.0
Rtabmap\MaxRetrieved = 0
Rtabmap\MemoryThr = 2
Vis\PnPSplitLinearCovComponents = true
Vis\PnPVarianceMedianRatio = 2
g2o\PixelVariance = 2.0

The statistics show that Immunized locally is 0, but Immunized globally increases, and WM size also increases. Fortunately, they do not appear to grow indefinitely under this configuration, but rather fluctuate within the range of tens to hundreds. Since we set Mem\RehearsalSimilarity = 1.0 and Mem\STMSize = 1, the input data frame rate is 20 Hz, and the STM size in the statistics is 20 or 21, which is as expected. However, if we change Mem\STMSize back to 10 and enable rehearsal, the size of the STM will continue to grow indefinitely.
截图 2026-07-10 12-12-39

I think in #1687 I made sure it was doing Transfer/Retrieval (what is expected from the papers) like if intermediate nodes were not used (the count of retrieved nodes or transferred nodes are based on the non-intermediate nodes).

There should be no problem with counting in Transfer/Retrieval processing. Transfer/Retrieval skips processing intermediate nodes directly and instead processes the intermediate nodes connected to them while processing regular nodes, which is a very good approach. The problem lies in the calculation of maxLocalLocationsImmunized. Because _memory->getWorkingMem().size() includes intermediate nodes, maxLocalLocationsImmunized is magnified by about 20 times during our runtime. Then, comparing the actual number of regular nodes processed with this will result in an unexpected number of regular nodes being processed.

//============================================================
// RETRIEVAL 1/3 : Loop closure neighbors reactivation
//============================================================
int retrievalId = _highestHypothesis.first;
std::list<int> reactivatedIds;
double timeGetNeighborsTimeDb = 0.0;
double timeGetNeighborsSpaceDb = 0.0;
int immunizedGlobally = 0;
int immunizedLocally = 0;
int maxLocalLocationsImmunized = 0;
if(_maxTimeAllowed != 0 || _maxMemoryAllowed != 0)
{
// with memory management, we have to immunize some nodes
maxLocalLocationsImmunized = _localImmunizationRatio * float(_memory->getWorkingMem().size());
}

Since _memory->allNodesInWM() is false, the following code will always be executed. When calling _memory->getNeighborsId(), even though the passed-in _maxRetrieved is 0, this only prevents the node from being retrieved from the LTM. Since the neighbors are already in the WM, they are immunized.

if(!(_memory->allNodesInWM() && maxLocalLocationsImmunized == 0) && signature->getWeight()>=0)
{
if(retrievalId > 0)
{
//Load neighbors
ULOGGER_INFO("Retrieving locations... around id=%d", retrievalId);
int neighborhoodSize = (int)_bayesFilter->getPredictionLC().size()-1;
UASSERT(neighborhoodSize >= 0);
ULOGGER_DEBUG("margin=%d maxRetieved=%d", neighborhoodSize, _maxRetrieved);
UTimer timeGetN;
unsigned int nbLoadedFromDb = 0;
std::set<int> reactivatedIdsSet;
std::map<int, int> neighbors;
int nbDirectNeighborsInDb = 0;
// priority in time
// Direct neighbors TIME
ULOGGER_DEBUG("In TIME");
neighbors = _memory->getNeighborsId(retrievalId,
neighborhoodSize,
_maxRetrieved,
true,
true,
false,
true,
std::set<int>(),
&timeGetNeighborsTimeDb);

For the recording version with Rtabmap/MemoryThr=1 or 2, why even using intermediate nodes? Rtabmap/DetectionRate can be set to 0 to record everything (with Kp/MaxFeatures=-1).

This is still due to the reason I mentioned in #1697. Some users are now using RTAB-Map for embodied AI data acquisition. The trajectories they are collecting are getting longer and longer, from tens of seconds at the beginning to tens of minutes now. They even collect tracks from multiple devices simultaneously and then merge them using rtabmap-reprocess. If we treat all nodes as regular nodes, the amount of data will be enormous. This also makes offline loop closure detection and merging much slower. Furthermore, the behavior of Bayesian filtering and loop closure detection can even change due to the high similarity between neighbor nodes. Enabling intermediate nodes simply makes the recorded trajectories more continuous; they participate in graph optimization but not in loop closure detection. I noticed that commit d069bec added the setIMU() method, which may even be used to record higher frequency trajectories in the future. In our custom VIO, although the image data is only 20 Hz, we will provide high-frequency pose output according to the IMU frequency, which is usually 200 Hz. We will obtain neural network features from the OAK camera. Both the front-end and back-end will skip feature detection, so setting Kp/MaxFeatures have no effect. Feature data is transmitted to RTAB-Map along with image data via rtabmap_msgs/RGBDImage. This eliminates the need to enable neural network support when compiling RTAB-Map, and prebuilt RTAB-Map distributed by ROS can be directly used.

Not convinced we need to change the way working memory size is used (and counting the virtual or not). In particular, for thousands of nodes, we may spend significant time in getWorkingMemSize(), if it is also called multiple times per iteration. I would rater track with a local variable the number of intermediate nodes in Memory during update/retrieval/transfer.

In our current applications, either for general applications where intermediate nodes are disabled and Rtabmap\MemoryThr is set to 1000, or for data recording where intermediate nodes are enabled and Rtabmap\MemoryThr is set to 1 or 2. Calling getWorkingMemSize(true) will perform an iteration, but the performance impact should not be significant. In the new C++ standard, std::count_if can also be used, but its time complexity is also O(N), which is not much different from direct traversal.

@borongyuan

Copy link
Copy Markdown
Contributor Author

The statistics show that Immunized locally is 0, but Immunized globally increases, and WM size also increases. Fortunately, they do not appear to grow indefinitely under this configuration, but rather fluctuate within the range of tens to hundreds.

Some additional analysis on this:
In RETRIEVAL 1/3, the neighbors of retrievalId are inserted into reactivatedIds.
In RETRIEVAL 2/3, since _maxLocalRetrieved is 0, retrievalLocalIds.size() < _maxLocalRetrieved, no new data is inserted into reactivatedIds.
In RETRIEVAL 3/3, reactivatedIds.size() > 0, and _memory->reactivateSignatures() is called. Since a maxLoaded value of 0 effectively means unlimited reactivation/reloading, all reactivatedIds are added to immunizedLocations.

rtabmap/corelib/src/Memory.cpp

Lines 6966 to 6985 in bc724a2

std::set<int> Memory::reactivateSignatures(const std::list<int> & ids, unsigned int maxLoaded, double & timeDbAccess)
{
// get the signatures, if not in the working memory, they
// will be loaded from the database in an more efficient way
// than how it is done in the Memory
UDEBUG("");
UTimer timer;
std::list<int> idsToLoad;
std::list<int> idsInQueue;
std::map<int, int>::iterator wmIter;
for(std::list<int>::const_iterator i=ids.begin(); i!=ids.end(); ++i)
{
if(!this->getSignature(*i) && !uContains(idsToLoad, *i))
{
if(!maxLoaded || idsToLoad.size() < maxLoaded)
{
idsToLoad.push_back(*i);
UINFO("Loading location %d from database...", *i);
}

Comment thread corelib/src/Rtabmap.cpp Resolved
@matlabbe

Copy link
Copy Markdown
Member

I played with these changes for a while, looks good! I just improved the getWorkingMemSize() complexity when requesting without intermediate nodes. There was a loop O(N) on the working memory size map, and then a lookup in a map, producing a total of O(N log (N)). With a cached variable to track the number of intermediate nodes, we can have O(1).

You may doublecheck if everything is still working for you, then I'll merge.

… intermediate nodes count. Added two new statistics to track number of intermediate nodes in STM and WM.
@borongyuan

Copy link
Copy Markdown
Contributor Author

I have revised the condition for counting intermediate nodes. This code will treat invalid nodes with a weight of -9 as intermediate nodes. This can even cause _stMemIntermediateNodesCount to become negative. The reason is that setWeight(-9) appears not only in Memory::moveToTrash(), but also in Memory::rehearsalMerge(). If rehearsal is enabled, there will already be invalid nodes in the STM before calling Memory::moveToTrash().

rtabmap/corelib/src/Memory.cpp

Lines 2759 to 2776 in 531b8a4

void Memory::moveToTrash(Signature * s, bool keepLinkedToGraph, std::list<int> * deletedWords)
{
//UDEBUG("id=%d", s?s->id():0);
if(s)
{
// Keep the WM/STM intermediate-node counters in sync now, before the weight
// may be set to -9 below.
if(s->getWeight() < 0)
{
if(this->isInWM(s->id()))
{
--_workingMemIntermediateNodesCount;
}
else if(this->isInSTM(s->id()))
{
--_stMemIntermediateNodesCount;
}
}

截图 2026-07-13 22-06-15

@matlabbe

Copy link
Copy Markdown
Member

LGTM!

@matlabbe
matlabbe merged commit 0f56dd4 into introlab:master Jul 14, 2026
27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants