Skip to content

Cache table refs - #2441

Merged
mergify[bot] merged 1 commit into
tskit-dev:mainfrom
jeromekelleher:cache-table-refs
Jul 28, 2022
Merged

mergify[bot] merged 1 commit into
tskit-dev:mainfrom
jeromekelleher:cache-table-refs

Conversation

@jeromekelleher

@jeromekelleher jeromekelleher commented Jul 25, 2022 •

Copy link
Copy Markdown
Member

Stacked on #2439

Closes #2080

Rather than creating new references each time we access tables.edges, this caches the objects in TableCollection. There were a few things that tripped me up along the way, but I think it does lead to simpler code and makes it fairly clear now how we addess (part of, at least) making ts.tables return a view of the TableCollection data.

Benchmarks:

import msprime
import sys
import time

before = time.perf_counter()
ts = msprime.sim_ancestry(
    100000,
    sequence_length=1000000,
    population_size=10_000,
    recombination_rate=1e-8,
    random_seed=1234,
)
ts = msprime.sim_mutations(ts, rate=1e-7, random_seed=1)
print(ts)
duration = time.perf_counter() - before
print(f"Simulation of {ts.num_trees} trees done after {duration:.2f} seconds")

tables = ts.tables
before = time.perf_counter()
for _ in range(10000):
    tables.nodes
    tables.edges
    tables.individuals
    tables.populations
    tables.mutations
    tables.sites
    tables.provenances
    tables.migrations
duration = time.perf_counter() - before
print(f"Pulled out tables in {duration:.2g} seconds")

before = time.perf_counter()
populations = tables.populations
for _ in range(10000):
    populations.metadata_schema
duration = time.perf_counter() - before
print(f"Pulled out metadata_schema in {duration:.2g} seconds")

before = time.perf_counter()
edges = tables.edges
for _ in range(10000):
    edges.left
duration = time.perf_counter() - before
print(f"Pulled out edges.left in {duration:.2g} seconds")

before = time.perf_counter()
for _ in range(1000):
    tables = ts.tables
    # tables.nodes
duration = time.perf_counter() - before
print(f"Pulled out ts.tables in {duration:.2g} seconds")

before = time.perf_counter()
for _ in range(1000):
    nodes = ts.tables.nodes
duration = time.perf_counter() - before
print(f"Pulled out ts.tables.nodes in {duration:.2g} seconds")

NOTE: the last two run 10x fewer iterations as ts.tables is still slowwww.

Results

Current upstream main

╔═══════════════════════════╗
║TreeSequence               ║
╠═══════════════╤═══════════╣
║Trees          │       4885║
╟───────────────┼───────────╢
║Sequence Length│    1000000║
╟───────────────┼───────────╢
║Time Units     │generations║
╟───────────────┼───────────╢
║Sample Nodes   │     200000║
╟───────────────┼───────────╢
║Total Size     │   32.5 MiB║
╚═══════════════╧═══════════╝
╔═══════════╤══════╤═════════╤════════════╗
║Table      │Rows  │Size     │Has Metadata║
╠═══════════╪══════╪═════════╪════════════╣
║Edges      │418790│ 12.8 MiB│          No║
╟───────────┼──────┼─────────┼────────────╢
║Individuals│100000│  2.7 MiB│          No║
╟───────────┼──────┼─────────┼────────────╢
║Migrations │     0│  8 Bytes│          No║
╟───────────┼──────┼─────────┼────────────╢
║Mutations  │ 51949│  1.8 MiB│          No║
╟───────────┼──────┼─────────┼────────────╢
║Nodes      │404076│ 10.8 MiB│          No║
╟───────────┼──────┼─────────┼────────────╢
║Populations│     1│224 Bytes│         Yes║
╟───────────┼──────┼─────────┼────────────╢
║Provenances│     2│  1.6 KiB│          No║
╟───────────┼──────┼─────────┼────────────╢
║Sites      │ 50650│  1.2 MiB│          No║
╚═══════════╧══════╧═════════╧════════════╝

Simulation of 4885 trees done after 1.26 seconds
Pulled out tables in 0.19 seconds
Pulled out metadata_schema in 0.0011 seconds
Pulled out edges.left in 0.99 seconds
Pulled out ts.tables in 3.4 seconds
Pulled out ts.tables.nodes in 4.5 seconds

upsteam-main

This branch

Simulation of 4885 trees done after 1.30 seconds
Pulled out tables in 0.005 seconds
Pulled out metadata_schema in 0.0029 seconds
Pulled out edges.left in 1.1 seconds
Pulled out ts.tables in 3.5 seconds
Pulled out ts.tables.nodes in 7.4 seconds

this-branch

@jeromekelleher

jeromekelleher commented Jul 25, 2022 •

Copy link
Copy Markdown
Member Author

Note: it's not clear why ts.tables.nodes is 2X slower here than in main. Maybe it's running garbage collection or something?Not obvious why the memory would drop slowly downwards otherwise. Something to look into I guess (but I'm not overly worried).

@codecov

codecov Bot commented Jul 25, 2022 •

Copy link
Copy Markdown

Codecov Report

Merging #2441 (dd1d24c) into main (98dacf5) will decrease coverage by 0.00%.
The diff coverage is 100.00%.

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2441      +/-   ##
==========================================
- Coverage   93.43%   93.43%   -0.01%     
==========================================
  Files          28       28              
  Lines       27347    27337      -10     
  Branches     1253     1247       -6     
==========================================
- Hits        25551    25541      -10     
  Misses       1762     1762              
  Partials       34       34              
Flag Coverage Δ
c-tests 92.26% <ø> (ø)
lwt-tests 89.05% <ø> (ø)
python-c-tests 71.37% <100.00%> (-0.02%) ⬇️
python-tests 98.94% <100.00%> (-0.01%) ⬇️

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

Impacted Files Coverage Δ
python/tskit/tables.py 98.95% <100.00%> (-0.01%) ⬇️
python/tskit/trees.py 98.72% <100.00%> (ø)

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 98dacf5...dd1d24c. Read the comment docs.

@jeromekelleher

Copy link
Copy Markdown
Member Author

Current version means we parse the metadata schema every time we decode a row, so this will be very bad for row-access performance.

@jeromekelleher
jeromekelleher marked this pull request as draft July 27, 2022 14:02
@jeromekelleher

Copy link
Copy Markdown
Member Author

Actually, I think the performance of this is fine. Here's my benchmark:

import time
import tskit
import msprime

demography = msprime.Demography.stepping_stone_model([100] * 100, migration_rate=0.0)
for k in range(100):
    demography[k].name = f"awesome_pop_{k}"
    demography[k].description = "This population is totally awesome"
    demography[k].extra_metadata = {f"x_{j}": list(range(j)) for j in range(100)}
ts = msprime.sim_ancestry({0: 2}, demography=demography, random_seed=1)

# print(ts.tables.populations)
before = time.perf_counter()
for _ in range(100):
    for pop in ts.populations():
        # print(pop.metadata)
        # x = pop.metadata
        pass
duration = time.perf_counter() - before

print(f"ts.populations in {duration:.2g} seconds")

# print(ts.tables.populations)
before = time.perf_counter()
for _ in range(100):
    for pop in ts.populations():
        # print(pop.metadata)
        x = pop.metadata
        pass
duration = time.perf_counter() - before
print(f"ts.populations decode metadata in {duration:.2g} seconds")

tables = ts.tables
# print(ts.tables.populations)
before = time.perf_counter()
for _ in range(100):
    for pop in tables.populations:
        # print(pop.metadata)
        # x = pop.metadata
        pass
duration = time.perf_counter() - before
print(f"tables.populations in {duration:.2g} seconds")

tables = ts.tables
# print(ts.tables.populations)
before = time.perf_counter()
for _ in range(100):
    for pop in tables.populations:
        # print(pop.metadata)
        x = pop.metadata
        pass
duration = time.perf_counter() - before
print(f"tables.populations decode metadata in {duration:.2g} seconds")

For upstream/main we get:

ts.populations in 0.02 seconds
ts.populations decode metadata in 2.7 seconds
tables.populations in 0.026 seconds
tables.populations decode metadata in 2.7 seconds

For this branch we get:

ts.populations in 0.02 seconds                                                                                                                                                                                                                
ts.populations decode metadata in 2.7 seconds                                                                                                                                                                                                 
tables.populations in 0.028 seconds                                                                                                                                                                                                           
tables.populations decode metadata in 2.7 seconds      

So, there's no difference really when we're decoding significant amounts of metadata. The reason it doesn't matter that we're not caching the parsed metadata schema is because we have a functools.lru_cache on the parse_metadata_schema function. So, we incur the cost of creating the unicode string and looking up that cache each time, but I bet that's not much different to any other mechanism we'd come up with, and it's a lot simpler.

What do you think @benjeffery - should we try other benchmarks here?

@jeromekelleher
jeromekelleher marked this pull request as ready for review July 27, 2022 16:52
@benjeffery

Copy link
Copy Markdown
Member

Ahhh, interesting. The LRU cache was added to improve replicate performance after the initial TableCollection metadata implementation that has the instance-level cache. I think we can completely remove the instance level caching with little penalty then. I'll review this now.

@benjeffery benjeffery 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.

Much simpler, LGTM!

Closes tskit-dev#2439

Removes the caching layer for metadata schemas as it was causing
consistency problems and wasn't doing anything in the most common case
anyway (accessing tables.individuals, e.g.)
@mergify
mergify Bot merged commit 12812b0 into tskit-dev:main Jul 28, 2022
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.

Cache table references

2 participants