Skip to content

Double tables by default. - #1683

Merged
mergify[bot] merged 1 commit into
tskit-dev:mainfrom
benjeffery:double-tables
Sep 16, 2021
Merged

mergify[bot] merged 1 commit into
tskit-dev:mainfrom
benjeffery:double-tables

Conversation

@benjeffery

Copy link
Copy Markdown
Member

Fixes #5
Fixes #1532

Just node table, for review before copy-pasteathon.

@jeromekelleher jeromekelleher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Some minor comments on the logic arrangement, but the overall design is great.

Comment thread c/tskit/tables.c Resolved
Comment thread c/tskit/tables.c Resolved
@benjeffery

Copy link
Copy Markdown
Member Author

@bhaller We're attempting to improve row allocation in tskit here. Could you have a quick look at this proposal? Basically instead of growing by 1024 rows everytime the table is full it now doubles.

@bhaller

bhaller commented Sep 10, 2021

Copy link
Copy Markdown

Hi folks. @petrelharp and @molpopgen you probably want to be in on this too. I skimmed the diffs but didn't get into them in great detail. The overall concept seems good – avoid a bunch of reallocs. I think the standard C++ library is generally implemented to double when a realloc is needed; it's generally a good approach. However, it does create a danger of rather radically increasing the high-water mark when dealing with large blocks, right? If you have a table that is already taking, say, 5 GB, doubling its size would suddenly take another 5 GB, and you might only use a small portion of that additional space. I can see this potentially having quite negative effects on SLiM, since it is not uncommon for tskit tables to be responsible for the large majority of all of the memory allocated by SLiM.

What do you think of this: double with each realloc, but have a maximum number of rows that you will add at one time; if doubling would add more than that maximum number of rows, then cap the size increase at the maximum rather than doubling. That maximum increment size could be pretty large; I'm not worried about over-allocating memory in the neighborhood of, say, 100 MB. But when it gets much larger than that, it really starts to hurt a bit. I would also note that although minimizing reallocs is a noble goal, I don't think I have ever seen memory reallocation inside tskit show up in any SLiM profile, so this might be a case of premature optimization.

To have more of an opinion than that, I'd probably need to do some metrics-collecting on a run of a big SLiM model. I could log out each time that a table increased in size, and the maximum size it reaches, and that sort of thing, I imagine. It'd be some work, but if it would be useful I could certainly do it.

Here's a question. Does tskit ever shrink the memory taken by tables/columns? Or does the memory allocation only grow, even when you simplify? If the latter – which is the usual strategy – then that would explain why reallocs pretty much never show up in SLiM profiles: you pay a price to grow the tables up to their high-water mark, and from then on the model is chugging along without doing any reallocs at all. In this case, the win from this doubling strategy would only decrease that constant overhead for growing up to the high-water mark, and from then on it wouldn't make any performance difference at all. The lose, on the other hand – the increased memory footprint due to the final doubling, which probably overshoots the true high-water mark considerably – is something you pay for for the whole rest of the run, since the tables never shrink back down.

So my vote would be for a cap on the maximum number of rows added, to try to get the benefits of doubling while minimizing the memory footprint penalty. Sorry if I'm missing something in your diffs here; I saw that you allowed a user-specified increment as an alternative to doubling, but I don't see an increment cap in this design, right?

@molpopgen

Copy link
Copy Markdown
Member

The doubling strategy is what fwdpp/fwdpy11 use, because all data are written to vector. I've done comparisons to slim for models with exponential growth and loads of recombination. Stuff like Tennessen with 4Nr = 1e5 and N is the ancestral N. The final N of the model is ~1e6. fwdpy11's peak memory is less (I don't recall how much offhand), suggesting tables aren't the answer, I think?

The doubling amortizes allocation costs on average, so sometimes you hit bad luck like you describe. There's no free lunch. (But 1.5 is also common, too, and I think is what Java does?) One way to avoid the base luck is a "reserve" setup. I think if you call tsk_edge_table_expand_main_columns (hope I got that right...) with a reasonable guess early on, you'll dodge large amounts of unused memory.

IIRC, simplification currently buffers edges in a temporary linked list and then copying them back into the tables?

@bhaller

bhaller commented Sep 11, 2021

Copy link
Copy Markdown

The doubling strategy is what fwdpp/fwdpy11 use, because all data are written to vector. I've done comparisons to slim for models with exponential growth and loads of recombination. Stuff like Tennessen with 4Nr = 1e5 and N is the ancestral N. The final N of the model is ~1e6. fwdpy11's peak memory is less (I don't recall how much offhand), suggesting tables aren't the answer, I think?

These tests are with simplification happening at what interval? Exactly the same for SLiM and fwdpy? Of course the peak memory usage will depend very strongly upon how often simplification happens, so if it doesn't match then the comparison is apples to oranges. And if simplification is happening at all frequently, then memory usage may no longer be dominated by the size of the tables anyway. The most relevant tests, for our purposes here, would involve infrequent simplification, or no simplification at all. Anyhow, SLiM's table metadata is doubtless larger than fwdpy's, so yes, if the comparison is apples to apples then SLiM's tskit memory usage is probably larger; that makes perfect sense. But that doesn't mean that the size of the tables is not a problem, right?

The doubling amortizes allocation costs on average, so sometimes you hit bad luck like you describe. There's no free lunch. (But 1.5 is also common, too, and I think is what Java does?)

Yes, there's no free lunch; but it seems reasonable to me, and worth some small speed penalty that probably gets paid only a couple of times in an entire run, to ensure that you eat lunch rather than lunch eating you. :-> I don't see any reason to just keep on doubling ad infinitum, even when that doubling, e.g., takes you from 5 GB to 10 GB (or worse). Far better to go to 6 GB, and if you need more, go to 7 GB, etc. (Or probably even somewhat smaller maximum increments than that, in my opinion.) Yes, if you do end up needing all 10 GB then you'll pay the price of doing some additional memory copies, until you reach the high water mark. To me that is clearly better than sometimes chewing up 5 GB more memory than you needed; that can make the difference between being able to run a model in the memory available on a cluster, and not being able to. That is not true at smaller sizes, where doubling is a very reasonable strategy; who really cares if you go from 5 MB to 10 MB and that's more than you needed? But it seems clear that there is a limit to how long you want to pursue that strategy.

One way to avoid the base luck is a "reserve" setup. I think if you call tsk_edge_table_expand_main_columns (hope I got that right...) with a reasonable guess early on, you'll dodge large amounts of unused memory.

Unless you're working with a very predictable model or a known random seed, it doesn't seem realistic to me to expect users to be able to accurately guess how many rows their tskit tables are going to need. Am I misunderstanding what you're proposing?

IIRC, simplification currently buffers edges in a temporary linked list and then copying them back into the tables?

Sorry, not following the relevance here...?

@molpopgen

Copy link
Copy Markdown
Member

The doubling strategy is what fwdpp/fwdpy11 use, because all data are written to vector. I've done comparisons to slim for models with exponential growth and loads of recombination. Stuff like Tennessen with 4Nr = 1e5 and N is the ancestral N. The final N of the model is ~1e6. fwdpy11's peak memory is less (I don't recall how much offhand), suggesting tables aren't the answer, I think?

These tests are with simplification happening at what interval? Exactly the same for SLiM and fwdpy? Of course the peak memory usage will depend very strongly upon how often simplification happens, so if it doesn't match then the comparison is apples to oranges. And if simplification is happening at all frequently, then memory usage may no longer be dominated by the size of the tables anyway. The most relevant tests, for our purposes here, would involve infrequent simplification, or no simplification at all. Anyhow, SLiM's table metadata is doubtless larger than fwdpy's, so yes, if the comparison is apples to apples then SLiM's tskit memory usage is probably larger; that makes perfect sense. But that doesn't mean that the size of the tables is not a problem, right?

All apples to apples

The doubling amortizes allocation costs on average, so sometimes you hit bad luck like you describe. There's no free lunch. (But 1.5 is also common, too, and I think is what Java does?)

Yes, there's no free lunch; but it seems reasonable to me, and worth some small speed penalty that probably gets paid only a couple of times in an entire run, to ensure that you eat lunch rather than lunch eating you. :-> I don't see any reason to just keep on doubling ad infinitum, even when that doubling, e.g., takes you from 5 GB to 10 GB (or worse). Far better to go to 6 GB, and if you need more, go to 7 GB, etc. (Or probably even somewhat smaller maximum increments than that, in my opinion.) Yes, if you do end up needing all 10 GB then you'll pay the price of doing some additional memory copies, until you reach the high water mark. To me that is clearly better than sometimes chewing up 5 GB more memory than you needed; that can make the difference between being able to run a model in the memory available on a cluster, and not being able to. That is not true at smaller sizes, where doubling is a very reasonable strategy; who really cares if you go from 5 MB to 10 MB and that's more than you needed? But it seems clear that there is a limit to how long you want to pursue that strategy.

One way to avoid the base luck is a "reserve" setup. I think if you call tsk_edge_table_expand_main_columns (hope I got that right...) with a reasonable guess early on, you'll dodge large amounts of unused memory.

Unless you're working with a very predictable model or a known random seed, it doesn't seem realistic to me to expect users to be able to accurately guess how many rows their tskit tables are going to need. Am I misunderstanding what you're proposing?

The implementer can predict it--you can guess how many births and crossovers there should be on average until you simplify again.

IIRC, simplification currently buffers edges in a temporary linked list and then copying them back into the tables?

Sorry, not following the relevance here...?

You asked if memory was being reused or not.

@bhaller

bhaller commented Sep 11, 2021 •

Copy link
Copy Markdown

All apples to apples

OK, that's good. As I wrote, in that case it is unsurprising that SLiM takes more memory since it keeps more metadata, but that does not mean that the size of the tables is unimportant.

Unless you're working with a very predictable model or a known random seed, it doesn't seem realistic to me to expect users to be able to accurately guess how many rows their tskit tables are going to need. Am I misunderstanding what you're proposing?

The implementer can predict it--you can guess how many births and crossovers there should be on average until you simplify again.

In a very predictable model you can indeed predict that, yes. Can you predict that in a model involving non-linear population size fluctuations, or density-dependent fecundity with local adaptation, or evolution of recombination rates, or local extinctions and/or evolutionary rescue in response to climate change, or...?

IIRC, simplification currently buffers edges in a temporary linked list and then copying them back into the tables?

Sorry, not following the relevance here...?

You asked if memory was being reused or not.

Well, I asked if the size of the tables ever shrank. If simplification deallocates the previous edge columns and allocates new ones sized to fit the post-simplification size, then that means yes, they can shrink. But if it just copies the edges back into the existing column buffers, then the table would not shrink, right? But in any event, the important case here is the case in which simplification is infrequent or nonexistent; if simplification is keeping the high-water mark small then it doesn't really matter whether the tables can shrink or not, nor is the doubling behavior likely to matter.

Here's the point in a nutshell. The high-water mark is what matters; it's what determines whether a model runs on a given cluster or not. If changing to doubling raises the high-water mark of a given model enough that it goes from fitting in the user's cluster to not fitting, that is a huge lose. Yes, the user might be able to offset that problem by simplifying more often – but given how much simplification already dominates large models, I would bet quite a bit that the additional time spent doing more frequent simplifications would vastly outweigh the small time savings coming from avoiding a few memory copies en route to the high water mark. It's not going to be even close to worth it. For smaller models that fit completely into memory either way, it will provide some marginal speedup, no doubt. But that is not worth the large penalty that the big models will pay, in terms of either a greatly increased high-water mark or a greatly increased amount of time spent in simplification.

@petrelharp

Copy link
Copy Markdown
Contributor

What do you think of this: double with each realloc, but have a maximum number of rows that you will add at one time; if doubling would add more than that maximum number of rows, then cap the size increase at the maximum rather than doubling.

I like this proposal!

@molpopgen

Copy link
Copy Markdown
Member

Can you predict that in a model involving non-linear population size fluctuations, or density-dependent fecundity with local adaptation, or evolution of recombination rates, or local extinctions and/or evolutionary rescue in response to climate change, or...?

You don't need to be very accurate. I've done a lot of experimentation with models with population sizes are random numbers over time, etc.. Things are pretty good.

Capping may not affect the high water mark--if you hit your cap, you may still get a transient doubling in memory while your current array is being copied to its new location, and that'll be your peak for the run, right?

@bhaller

bhaller commented Sep 11, 2021

Copy link
Copy Markdown

Can you predict that in a model involving non-linear population size fluctuations, or density-dependent fecundity with local adaptation, or evolution of recombination rates, or local extinctions and/or evolutionary rescue in response to climate change, or...?

You don't need to be very accurate. I've done a lot of experimentation with models with population sizes are random numbers over time, etc.. Things are pretty good.

Shrug. Some models will be trivially predictable; some will be predictable with a little work/thought; some will be predictable only by pre-flighting; some won't be predictable at all even with a pre-flight because of large variance in the memory usage between independent runs of the model. One could debate how common these different scenarios might be, but really it will depend upon what kinds of problems one is interested in modeling. In any case it seems better to have a memory usage policy that doesn't require the user to make such a guess in the first place, simply to avoid consuming gigabytes of extra memory unnecessarily. Why make the user guess if you can just have a better memory usage policy in the first place?

Capping may not affect the high water mark--if you hit your cap, you may still get a transient doubling in memory while your current array is being copied to its new location, and that'll be your peak for the run, right?

Sure, all kinds of things might affect the program's high water mark, in addition to whatever the high water mark for the tables themselves might be. The fact remains, though, that raising the high water mark for the tables themselves by gigabytes of unused memory is clearly a bad thing, right?

It seems like you're arguing against the policy that I proposed, but it's not clear to me why. Is there a significant drawback to what I proposed? Is there a significant advantage to simple doubling, plus letting the user guess at what the high water mark might be in order to avoid bad outcomes from doubling?

@molpopgen

Copy link
Copy Markdown
Member

Why make the user guess if you can just have a better memory usage policy in the first place?

Developer, not "user" in the usual sense of the term. In the end, I don't reserve at all, as I found it to only make differences in the tails of distributions of RAM use.

If the group wants to cap, then fine. Anyone working with the C API has already long been able to manage all the memory manually in any case, via the expand family. But we're going back and forth about problems on paper, and there's no evidence that there would be an average effect. Mark Twain comes to mind here... ;)

@bhaller

bhaller commented Sep 11, 2021

Copy link
Copy Markdown

Why make the user guess if you can just have a better memory usage policy in the first place?

Developer, not "user" in the usual sense of the term. In the end, I don't reserve at all, as I found it to only make differences in the tails of distributions of RAM use.

If the group wants to cap, then fine. Anyone working with the C API has already long been able to manage all the memory manually in any case, via the expand family.

Users of SLiM are not "developers", and they're not working with the C API, but they will inherit the effects of these policy choices, indirectly.

But we're going back and forth about problems on paper, and there's no evidence that there would be an average effect. Mark Twain comes to mind here... ;)

How could this policy choice not make a difference? I'm really puzzled as to what you're arguing for here, and why. (And... why Mark Twain?)

@molpopgen

Copy link
Copy Markdown
Member

How could this policy choice not make a difference? I'm really puzzled as to what you're arguing for here, and why. (And... why Mark Twain?)

The doubling is a very common thing for general-purpose containers to do, passing off finer-grained control to the developer via other function. I was, however, incorrect--the expand functions are not public, but they could be. It is simple, and well-understood to double or 1.5x an existing container. I have a bad habit of reading the .c files rather than the .h.

I've done a lot in the past to compare these two strategies myself in various contexts, and the excess allocated capacity is generally small.

Mark Twain -- the quote is clearly about discussing implementations in the absence of testing!

@bhaller

bhaller commented Sep 11, 2021

Copy link
Copy Markdown

How could this policy choice not make a difference? I'm really puzzled as to what you're arguing for here, and why. (And... why Mark Twain?)

The doubling is a very common thing for general-purpose containers to do, passing off finer-grained control to the developer via other function. I was, however, incorrect--the expand functions are not public, but they could be. It is simple, and well-understood to double or 1.5x an existing container. I have a bad habit of reading the .c files rather than the .h.

Sure, one could make the expand functions public, and then expose them with public API in places like SLiM that wrap tskit, and then put the onus onto the end user to calculate what the expected usage of their model is (when that is even possible to calculate). I just don't see, again, why that is preferable to simply adopting a memory usage policy that avoids the problem in the first place. But this is starting to feel like beating a dead horse.

I've done a lot in the past to compare these two strategies myself in various contexts, and the excess allocated capacity is generally small.

If you're taking 5 GB, and then you double, you're taking 10 GB. If you only needed 5.5 GB, then you've just wasted 4.5 GB. I don't see any reason to think that this sort of outcome would be any less likely than any other outcome. If the usage were averaged across many objects, each of which was doubling its capacity independently on demand, I could see a rationale for that behavior tending not to waste an extreme amount of memory; it will average out (and that is why, in general, it's a perfectly reasonable strategy for the STL as a default behavior). However, when when the usage is highly concentrated in just one object – the edge table, perhaps – then it is trivial to demonstrate that doubling will very often result in the wastage of a large amount of memory, up to 50% – the argument above suffices. That might average out across many runs of the model, making the average wastage tolerable, but that doesn't help the particular run of the model that happens to hit the worst case of 50% wastage; that run of the model may fail to fit on the user's cluster, even if the other runs fit. But if just one run doesn't fit, then the whole model doesn't fit – you can't just exclude the runs that don't fit, because then you're biasing your results. So the worst case is actually what matters here.

Mark Twain -- the quote is clearly about discussing implementations in the absence of testing!

Ah, you didn't have the link on "Mark Twain" the first time you wrote it. :->

Well, hmm, I'd say jumping into implementation without thinking through the design consequences first tends to just waste time and produce bad outcomes – but I don't have a Mark Twain quote handy for that. :->

Anyhow, I think I've said my piece, so I'm going to take a step back for now. Thanks all.

@molpopgen

molpopgen commented Sep 11, 2021 •

Copy link
Copy Markdown
Member

One motivating example is here.

Output from the shell script (POSIX only, not BSD):

C++
default behavior: 100000000 134217728
3.75 3149420
default behavior until 20000000  then increase capacity by 5000000 : 100000000 100000000
9.81 4456920
C
vanilla 100000000 134217728
2.70 2345996
vanilla until 20000000, then linear by 5000000 = 100000000 103554432
2.72 2345788

I didn't succeed in making the 2 implementations exactly the same, and I suspect the C version may be optimizing something away? But if you are concerned about the peak memory use, either for OOM issue or being killed on a cluster by exceeding resourced, the peak RAM from a "double until X, then increased by a fixed amount Y thereafter", often has similar or greater peak ram values. This is the experience that I was referring to above. Sorry if you feel you are beating a dead horse, but this stuff is often not very intuitive.

@bhaller

bhaller commented Sep 11, 2021

Copy link
Copy Markdown

One motivating example is here.

Output from the shell script (POSIX only, not BSD):

C++
default behavior: 100000000 134217728
3.75 3149420
default behavior until 20000000  then increase capacity by 5000000 : 100000000 100000000
9.81 4456920
C
vanilla 100000000 134217728
2.70 2345996
vanilla until 20000000, then linear by 5000000 = 100000000 103554432
2.72 2345788

I didn't succeed in making the 2 implementations exactly the same, and I suspect the C version may be optimizing something away? But if you are concerned about the peak memory use, either for OOM issue or being killed on a cluster by exceeding resourced, the peak RAM from a "double until X, then increased by a fixed amount Y thereafter", often has similar or greater peak ram values. This is the experience that I was referring to above. Sorry if you feel you are beating a dead horse, but this stuff is often not very intuitive.

Hmm. I don't find this example convincing, sorry. It looks like the threshold-increment C case runs in essentially the same time as the doubling ("vanilla") C case (so the additional memory copies are unimportant), and has a lower peak usage (in this specific example the difference is not large, but of course that will depend upon the numbers used). Importantly, it also has a substantially lower final usage, as shown by the final allocated capacity – so if anything else were also allocating memory at the same time, which would be the case in real-world usage, it could do its allocation out of the freed space without increasing the high-water mark at all. That extra margin for other allocations is a large fraction of the total memory usage. Looks like a big win for threshold-increment.

The C++ code... well, who knows what's going on under the hood there. The behavior of that implementation will be completely dependent upon the underlying STL implementation, which is trying to do its own memory allocation optimizations – who knows what they might be – and is therefore probably pulling the rug out from under you in some way. Certainly it is much slower than the C code, in both versions, showing that it is doing a bunch of stuff behind the scenes that is not visible at the API level. I would expect to get very different results for this C++ code on different platforms or with different compilers (whereas I'd expect the C code to perform quite consistently). All I take that to show is that (a) the STL's algorithms are often sub-optimal because they are general-purpose, and (b) they can behave in surprising, platform-dependent ways. Which is a good take-home lesson – high-level object kits can be a poor choice for high-performance coding tasks – but irrelevant to the discussion here, which is about C code.

@petrelharp

Copy link
Copy Markdown
Contributor

What do you think of this: double with each realloc, but have a maximum number of rows that you will add at one time; if doubling would add more than that maximum number of rows, then cap the size increase at the maximum rather than doubling.

I still like this proposal. Thanks for the extra input. Concretely, I'd propose to double until 500K rows, and increase in chunks of 500K after that. From a very quick check, 40K rows is about 1Mb for some tables (nodes, edges), so this would be increasing in chunks of no more than around 12Mb per table. This is modest, but on the other hand 500K is a lot.

@grahamgower

Copy link
Copy Markdown
Member

I agree with @bhaller here about preferring a modest overallocation, rather than always doubling. E.g. for the general purpose list data structure in Python, cPython over allocates by len(list)*1.25 (and other minor details, like ensuring nice alignment). Unless the behaviour of tskit table expansion in real world simulations is pathological compared to the demands of a general purpose programming language's list, I'd suggest not inventing a new overallocation strategy.
https://github.com/python/cpython/blob/5277ffe12d492939544ff9c54a3aaf448b913fb3/Objects/listobject.c#L61-L70

@molpopgen

Copy link
Copy Markdown
Member

I still think we need to measure. Here's another data point--let's just add 100 million nodes and edges to a table collection and measure.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <err.h>

#include <tskit/tables.h>

#define check_tsk_error(val)                                                            \
    if (val < 0)                                                                        \
        {                                                                               \
            errx(EXIT_FAILURE, "line %d: %s", __LINE__, tsk_strerror(val));             \
        }

void
simulate(tsk_table_collection_t *tables, int T)
{
    tsk_id_t node_id;
    int t;
    for (t = T - 1; t >= 0; t--)
        {
            node_id = tsk_node_table_add_row(&tables->nodes, 0, T, TSK_NULL, TSK_NULL,
                                             NULL, 0);
            tsk_edge_table_add_row(&tables->edges, 0, 1, node_id, node_id + 1, NULL,
                                   0); // yes, this is invalid
        }
}

int
main(int argc, char **argv)
{
    int ret;
    tsk_table_collection_t tables;

    ret = tsk_table_collection_init(&tables, 0);
    check_tsk_error(ret);
    simulate(&tables, 100000000);
    tsk_table_collection_free(&tables);
    return 0;
}

Compile it with -O3 -DNDEBUG against current main and this PR:

/usr/bin/time -f "%e %M" ./sim_main 
57.20 5861816
/usr/bin/time -f "%e %M" ./sim_doublingpr 
20.74 5861876

The current strategy of increasing by 1,024 rows at a time, for this naive example, is a ~200% runtime cost and saves 60Kb of peak RAM. This is measuring what top calls RES--actuall memory consumed/written to. The VIRT (total memory space for the process) is 1GB higher for this PR -- 7 vs 6, or ~17%. The VIRT is a funny beast--RES is what causes OOM/swap/resource-based-kills, and VIRT is more like what the OS has said your process can have fast access to, if it needs it. (I'm writing this from memory, and it is probably a bit sloppy.)

@grahamgower's point is well-taken. Many standard allocators use multipliers < 2.

@bhaller

bhaller commented Sep 12, 2021

Copy link
Copy Markdown

I still think we need to measure. Here's another data point--let's just add 100 million nodes and edges to a table collection and measure.

I'm all in favor of measurement, and this is a good and informative test. Of course it's important to keep in mind that this test only measures the initial cost of growing up to the high-water mark, though. You pay a price for that growth up front, but once you're there, if the tables never shrink, you pay no additional speed cost going forward – but if you overallocated, you pay that cost forever after. Something to keep in mind, although in this case spending 60K to save 37 seconds is clearly worthwhile. :->

The current strategy of increasing by 1,024 rows at a time, for this naive example, is a ~200% runtime cost and saves 60Kb of peak RAM. This is measuring what top calls RES--actuall memory consumed/written to. The VIRT (total memory space for the process) is 1GB higher for this PR -- 7 vs 6, or ~17%. The VIRT is a funny beast--RES is what causes OOM/swap/resource-based-kills, and VIRT is more like what the OS has said your process can have fast access to, if it needs it. (I'm writing this from memory, and it is probably a bit sloppy.)

Groovy. This clearly shows that a change from the current strategy can bring significant benefits, which is good to have confirmation on.

@grahamgower's point is well-taken. Many standard allocators use multipliers < 2.

Indeed. At smaller sizes, a multiplier even larger than 2 is probably optimal; the amount of memory wasted if you overallocate is unimportant if you're just talking about a couple K or even a couple MB. At larger sizes, the optimal multiplier probably gets smaller and smaller, as the importance of not overallocating grows larger; you (presumably) become increasingly willing to sacrifice a little speed (en route to the high-water mark) in return for more precise memory usage. Switching to a fixed size increment above a chosen threshold is really kind of a hand-wave towards that fact. The larger you get, the smaller (in multiplicative terms) that fixed-increment size increase becomes, reflecting that shift in priority away from maximum speed and toward minimum memory usage.

A reasonable algorithm, it seems to me, might therefore (a) Start with a large multiplier, 4x or even bigger; (b) Switch to a fixed increment at a given threshold value; and (c) Use a threshold value and a fixed-increment size such that at that crossover point, the size increase is approximately, say, 2x, so that initially you are switching from quadrupling to doubling. Then, as the table size gets progressively larger, the multiplier will further drop from 2x towards (asymptotically) 1x because the fixed increment will be a smaller and smaller percentage of the current table size. The best values for these parameters is certainly amenable to testing, although ultimately it's a subjective judgement call because it depends upon the value that you, personally, place on speed versus optimal allocation size; there is no absolute right answer here.

So, like I said, I'm all in favor of measurement as long as it's relevant to real-world usage; field-testing of alternatives would be great. But again, keep in mind that the speed penalty is only incurred en route to the high-water mark, so for large simulations that run for a significant number of generations it is probably almost completely irrelevant. In my opinion the optimality of allocation is probably much more important, for the big models where any of this really matters.

@bhaller

bhaller commented Sep 12, 2021

Copy link
Copy Markdown

...Unless the behaviour of tskit table expansion in real world simulations is pathological compared to the demands of a general purpose programming language's list, I'd suggest not inventing a new overallocation strategy.

Well, I wouldn't use the word "pathological", but it is certainly somewhat unusual for a single data structure to completely dominate the memory usage of an app, and occupy many gigabytes of memory. That fact is what makes me think that we can do better than simple doubling. The case of tskit tables really is unusual, and is not the type of usage pattern that general-purpose object-kit data structures are optimized for.

@molpopgen

molpopgen commented Sep 12, 2021 via email

Copy link
Copy Markdown
Member

@molpopgen

molpopgen commented Sep 12, 2021 via email

Copy link
Copy Markdown
Member

@bhaller

bhaller commented Sep 12, 2021

Copy link
Copy Markdown

Dealing with the overallocation poses an interesting challenge. Say we detect we've been way overallocated for some time, and our logic says it is time to deal with it. We will temporarily spike RES in order to implement what c++ calls "shrink to fit". If we are surfing on the edge of disaster, we may cross it at this point. So, whatever we do at that point probably has to be optional in the way that skrink to fit is, being a request that can be denied. All of these considerations get much uglier if we consider testing 64 processes on a 64 core machine, with each pushing the resource limits.
…

Shrink-to-fit seems like a completely different problem, and has not been part of the discussion thus far. I agree that it is probably not the right approach, for various reasons including the one you give; it's better (if possible) to allocate closer to optimality in the first place, which is what we've been discussing.

@molpopgen

Copy link
Copy Markdown
Member

This illustrates the difference between the two methods, and between VIRT and RES memory. It also explains why I am unconcerned about "excess" allocation.

Take the previous example, compile against the doubling pr again, after modifying it to write to all of the excess capacity allocated. (From above, recall that this excess capacity is VIRT, not RES).

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <err.h>

#include <tskit/tables.h>

#define check_tsk_error(val)                                                            \
    if (val < 0) {                                                                      \
        errx(EXIT_FAILURE, "line %d: %s", __LINE__, tsk_strerror(val));                 \
    }

void
simulate(tsk_table_collection_t *tables, int T)
{
    tsk_id_t node_id;
    int t;
    size_t i;
    for (t = T - 1; t >= 0; t--) {
        node_id
            = tsk_node_table_add_row(&tables->nodes, 0, T, TSK_NULL, TSK_NULL, NULL, 0);
        tsk_edge_table_add_row(&tables->edges, 0, 1, node_id, node_id + 1, NULL,
            0); // yes, this is invalid
    }
    fprintf(stdout, "%ld %ld\n", tables->edges.num_rows, tables->edges.max_rows);
    fprintf(stdout, "%ld %ld\n", tables->nodes.num_rows, tables->nodes.max_rows);

    // This is not undefined behavior, as the memory is allocated.
    // But it is definitely a bad idea!
    for (i = tables->nodes.num_rows; i < tables->nodes.max_rows; ++i) {
        node_id
            = tsk_node_table_add_row(&tables->nodes, 0, T, TSK_NULL, TSK_NULL, NULL, 0);
    }
    for (i = tables->edges.num_rows; i < tables->edges.max_rows; ++i) {
        tsk_edge_table_add_row(&tables->edges, 0, 1, node_id, node_id + 1, NULL,
            0); // yes, this is invalid
    }
}

int
main(int argc, char **argv)
{
    int ret;
    tsk_table_collection_t tables;

    ret = tsk_table_collection_init(&tables, 0);
    check_tsk_error(ret);
    simulate(&tables, 100000000);
    tsk_table_collection_free(&tables);
    return 0;
}

This modification converts the memory from VIRT to RES, which is seen in the output:

/usr/bin/time -f "%e %M" ./sim_doublingpr 
100000000 100000769
100000000 134217728
19.63 6797744

Before, that final number was 6GB, not 7, because we hadn't yet written to the allocated memory.

Using a tool like heaptrack, we see that the VIRT use is 7GB, which is the same as before! This is why I am unconcerned about these "excess" allocations--they are not part of RES until you write to the memory.

An additional exercise is to put while(1) {} at the end of the function and then run many of these processes at once. (replace the writing to the allocated buffers at the end of the first loop) On my laptop with 32GB, I can safely run 5 of them: 5 process * 6GB RES = 30GB. Note that 5 * 7GB virt is almost equal to the total amount of RAM + swap on my system, but I'm not swapping at all! You can safely allocate more virtual memory than there is physical memory on your machine. (I don't know if there's a limit to how far you can push that, though.)

But, if I run 5 processes with the above modification AND the while(1) {} loop, taking 7GB total RES for each process. bad
things happen and at least 1 job gets killed due to OOM.

@bhaller

bhaller commented Sep 12, 2021

Copy link
Copy Markdown

...Using a tool like heaptrack, we see that the VIRT use is 7GB, which is the same as before! This is why I am unconcerned about these "excess" allocations--they are not part of RES until you write to the memory...

These details are almost certainly platform-dependent, and should not be relied on. Yes, on some platforms it may be OK to allocate a 500GB block as long as you never write to it; and on some platforms it may even be OK to allocate a 500GB block and write to it, as long as you only write to the beginning of it. But as far as I'm aware, such behaviors are not guaranteed by the standard C allocator functions, and they probably vary from platform to platform, and even from version to version of a platform. It's nice when they happen to reduce your memory usage, but it seems like a bad idea to overallocate on the assumption that they will save you.

After all, if you could always rely on this mechanism to save you when you overallocate, then why grow the tables at all? Why not just allocate the tables with, say, 100 trillion rows to start with, and just assume that the OS will actually only give you the memory for the portion of the tables that you use? That would be a bad idea, right?

@molpopgen

Copy link
Copy Markdown
Member

100 trillion rows to start with, and just assume that the OS will actually only give you the memory for the portion of the tables that you use? That would be a bad idea, right?

That's a good question. The reason is that ~all of the VIRT becomes RES once you touch the first element. (At least if you make extreme examples like allocate zillions of doubles and then set x[0].) I didn't show that in the above, but it is easy to verify (on Linux, and I think macOS shows the same behavior).

@bhaller

bhaller commented Sep 13, 2021

Copy link
Copy Markdown

100 trillion rows to start with, and just assume that the OS will actually only give you the memory for the portion of the tables that you use? That would be a bad idea, right?

That's a good question. The reason is that ~all of the VIRT becomes RES once you touch the first element. (At least if you make extreme examples like allocate zillions of doubles and then set x[0].) I didn't show that in the above, but it is easy to verify (on Linux, and I think macOS shows the same behavior).

OK, so then I guess I'm missing something. What's the relevance of any of this for tskit, in that case? Because tskit will certainly touch the first element of all of the tables. So then if tskit overallocates, all the VIRT becomes RES, and the user suffers the memory penalty of overallocating. If over-allocating 100 trillion rows is a bad idea because the VIRT becomes RES, then over-allocating, say, 5GB worth of rows is also a bad idea, because the VIRT also becomes RES. No?

@molpopgen

molpopgen commented Sep 13, 2021 via email

Copy link
Copy Markdown
Member

@bhaller

bhaller commented Sep 13, 2021

Copy link
Copy Markdown

It will only touch the next thing if it needs to. In the original example, comparing the main branch to the current pull request the final resident size was the same. If that's all you ever do, then the total memory consumption is the same for the two. There's only a difference if more edges are added. And then, the memory difference is under 20%, which is much smaller than this hypothetical 100%.
…

So, if I'm understanding you correctly, you're saying that we don't need to worry about overallocation, because if we never write any new data into the tables, the overallocation won't actually hurt us? I'm not finding that argument convincing, sorry.

@molpopgen

Copy link
Copy Markdown
Member

No,, that isn't what I'm saying. Quite far from it, in fact. The point is that the hypothetical catastrophe is unlikely. (The 5g can can only happen once exactly 6 are allocated, due to powers of 2, etc.) Linear increases won't solve much, and hurt performance.Changing the exponent may, but needs testing.

@bhaller

bhaller commented Sep 13, 2021

Copy link
Copy Markdown

No,, that isn't what I'm saying. Quite far from it, in fact. The point is that the hypothetical catastrophe is unlikely. (The 5g can can only happen once exactly 6 are allocated, due to powers of 2, etc.) Linear increases won't solve much, and hurt performance.Changing the exponent may, but needs testing.

You wrote above that "The reason is that ~all of the VIRT becomes RES once you touch the first element. (At least if you make extreme examples like allocate zillions of doubles and then set x[0].)" If ~all of the VIRT becomes RES once you touch the first element, as you wrote, then I'm finding it difficult to understand why overallocation is not a problem. You agree that overallocating 100 trillion rows up front would be a bad idea, right? If so, then why is overallocating a smaller number of rows, like say 5GB worth of rows, not a bad idea? It feels like we're going in circles here.

@molpopgen

Copy link
Copy Markdown
Member

You wrote above that "The reason is that ~all of the VIRT becomes RES once you touch the first element. (At least if you make extreme examples like allocate zillions of doubles and then set x[0].)" If ~all of the VIRT becomes RES once you touch the first element, as you wrote, then I'm finding it difficult to understand why overallocation is not a problem. You agree that overallocating 100 trillion rows up front would be a bad idea, right? If so, then why is overallocating a smaller number of rows, like say 5GB worth of rows, not a bad idea? It feels like we're going in circles here.

I have given a precise case where a problem can occur. there's a 1GB "excess" in the current doubling scheme. It only causes a problem in some cases, and those are simple to reason about--if you need much of that 1GB, there's no problem. If you need some of it, and there's a crash, that's a problem.

I further hypothesize that it'll be hard to get very big (VIRT-RES), but I encourage you to try. Also, I encourage you (and all the other commenters) to make modifications to this PR to minimize that excess and measure the runtime tradeoffs (preferably by changing the exponent, and not going to some linear scheme--we want to avoid heap churn). There will be a balance between heap churn and runtime, but the runtime implications are likely negligible--these 40 seconds in a data set of 6GB of edges probably implies that the allocations are not the important operations impacting performance. The point is to stop talking hypotheticals and concrete cases. Or, if one doestwant to worry about "an extra 5GB" in the VIRT, make it concrete and provide the example. Once we have that, we can make progress. Finally, some of the above comments made it clear that some commenters did not have a clear picture of how how memory allocations behave in *nix systems, so one had to get into the VIRT/RES measurements (although via an oversimplification, as VIRT also includes the size of opened files, etc..).

@petrelharp

Copy link
Copy Markdown
Contributor

Gee, thanks for the explanation of the RES/VIRT distinction, Kevin - I had no idea about this (and remain fuzzy about exactly when the memory moves from VIRT into RES...). Indeed, it seems that slurm limits are set based on RES (although VIRT limits are also possible): https://lists.schedmd.com/pipermail/slurm-users/2018-November/002245.html

I'm not going to run experiments (sorry), but I guess I'm still in favor of the suggestion above to double up to some large number then cap at that point - it seems like the penalty will be minimal-to-zero (if we go linear at a much larger number than 1024). But I am not going to have any more opinions here.

@benjeffery

benjeffery commented Sep 13, 2021 •

Copy link
Copy Markdown
Member Author

Thanks for the discussion everyone, I learnt a lot!

I agree that it would be good to start with a larger multiple and reduce it, but the aim of this PR is a "good enough" implementation that improves the situation. If anyone is motivated to run experiments with refinements we can PR them later.

For now I suggest we double with a cap at an increase of 2M. My reasoning here is that for the edge table that is about a 50MB chunk which seems reasonable and is testable on CI.

@benjeffery

Copy link
Copy Markdown
Member Author

@jeromekelleher Copy-pasteathon complete.

@benjeffery
benjeffery force-pushed the double-tables branch 2 times, most recently from e609d3c to 13c1e82 Compare September 14, 2021 13:09
@codecov

codecov Bot commented Sep 14, 2021 •

Copy link
Copy Markdown

Codecov Report

Merging #1683 (691f1b5) into main (d9523c7) will increase coverage by 0.02%.
The diff coverage is 100.00%.

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1683      +/-   ##
==========================================
+ Coverage   93.33%   93.36%   +0.02%     
==========================================
  Files          27       27              
  Lines       24250    24235      -15     
  Branches     1089     1089              
==========================================
- Hits        22634    22627       -7     
+ Misses       1581     1573       -8     
  Partials       35       35              
Flag Coverage Δ
c-tests 92.10% <100.00%> (+0.05%) ⬆️
lwt-tests 89.25% <ø> (ø)
python-c-tests 94.50% <ø> (ø)
python-tests 98.75% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
c/tskit/core.h 100.00% <ø> (ø)
c/tskit/tables.c 90.19% <100.00%> (+0.09%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update d9523c7...691f1b5. Read the comment docs.

@jeromekelleher

Copy link
Copy Markdown
Member

Just worked my way through this thread after being away a few days - phew, that's a lot of information!

I think we could have avoided quite a lot of debate here by noting that the the changes we're making are to the default allocation strategy. The way it works is to have a max_rows_increment value for each table, and if this value is 0 (the default) we use doubling. Otherwise we increase the size by max_rows_increment. So, if you want to keep the current behaviour, then set max_rows_increment to 1024, and you're done.

SLiM is an important user for the tskit C API @bhaller, so please be assured that we won't make changes that result in performance regressions (and if we do, we'll fix them). As a power-user who wants to keep a tight lid on the table memory consumption, then I think setting the max_rows_increment manually within the SLiM C++ code is perfectly reasonable. To answer your questions above, I think the reason the current approach works well in SLiM is because memory usage does reach a high-water mark pretty quickly, and from there adding rows is very efficient.

The point of tagging the 1.0 API is to make the tskit C API stable and useable for situations other than SLiM (and forward simulation in general), and we hope that it'll be used in a wide variety of applications. Then, the new default approach of doubling up to a reasonable limit is a much better default than the current "add 1024 rows". As @molpopgen has shown convincingly above, this is a good general strategy when you don't know much about usage patterns.

Sound good?

@jeromekelleher jeromekelleher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks @benjeffery! Minor comments.

Comment thread c/CHANGELOG.rst Outdated
**Features**

- The default behaviour for table size growth is now to double the current size of the table.
This can be overriden by setting `max_rows_increment`. (:user:`benjeffery`, :issue:`5`, :pr:`1683`,)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add a note here:

To keep the current behaviour, use (e.g.) tsk_edge_table_set_max_rows_increment(tables->edges, 1024), which results in adding space for 1024 additional rows each time we run out of space in the edge table.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added

Comment thread c/tskit/tables.c
/* Add some constraints to prevent very small or very large allocations */
if (new_max_rows < 1024) {
new_max_rows = 1024;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a quick note here would help:

/* Prevent allocating more than ~2 million additional rows */

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added

Comment thread c/tskit/tables.c
}
new_max_rows = TSK_MAX(new_max_rows, num_rows + additional_rows);
} else {
/* Use user increment value */

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this overflow branch isn't tested?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed with an extra test

Comment thread python/tests/test_tables.py Outdated
# Setting zero or not argument both denote the default.
# Setting zero implies doubling
table = self.table_class()
print(table)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

stray print

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DAMMIT!

Fixed.

@bhaller

bhaller commented Sep 15, 2021

Copy link
Copy Markdown

Just worked my way through this thread after being away a few days - phew, that's a lot of information!

@jeromekelleher :->

I think we could have avoided quite a lot of debate here by noting that the the changes we're making are to the default allocation strategy. The way it works is to have a max_rows_increment value for each table, and if this value is 0 (the default) we use doubling. Otherwise we increase the size by max_rows_increment. So, if you want to keep the current behaviour, then set max_rows_increment to 1024, and you're done.

SLiM is an important user for the tskit C API @bhaller, so please be assured that we won't make changes that result in performance regressions (and if we do, we'll fix them). As a power-user who wants to keep a tight lid on the table memory consumption, then I think setting the max_rows_increment manually within the SLiM C++ code is perfectly reasonable. To answer your questions above, I think the reason the current approach works well in SLiM is because memory usage does reach a high-water mark pretty quickly, and from there adding rows is very efficient.

The point of tagging the 1.0 API is to make the tskit C API stable and useable for situations other than SLiM (and forward simulation in general), and we hope that it'll be used in a wide variety of applications. Then, the new default approach of doubling up to a reasonable limit is a much better default than the current "add 1024 rows". As @molpopgen has shown convincingly above, this is a good general strategy when you don't know much about usage patterns.

Sound good?

I'm not sure that was the issue in the debate, Jerome. I'm all in favor of doubling rather than a fixed increment; indeed, above I advocated for something faster than doubling, like quadrupling. So I don't plan on overriding the new default behavior in SLiM; I think it will be beneficial. The issue was whether to keep doubling ad infinitum, or to switch to a fixed increment above a certain threshold to prevent over-allocation. I was advocating switching to a fixed increment above a certain threshold (which I gather is the plan now), whereas (if I understood correctly) Kevin was advocating for doubling ad infinitum. My goal is the same as yours: that the tskit C API be optimal for a wide variety of applications, including forward simulation in general; I was citing usage in SLiM merely as an example of typical usage, as I don't think it is particularly different/special in what it needs from tskit. :->

@jeromekelleher

Copy link
Copy Markdown
Member

Gotcha, thanks Ben. I think we're all in agreement then 😄

@bhaller

bhaller commented Sep 15, 2021

Copy link
Copy Markdown

Gotcha, thanks Ben. I think we're all in agreement then 😄

I don't think Kevin is convinced...

@benjeffery

Copy link
Copy Markdown
Member Author

All fixed up.

@mergify
mergify Bot merged commit 73ece3a into tskit-dev:main Sep 16, 2021
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.

Add boundary checks for table size Change default expansion behaviour for tables to doubling

6 participants