Skip to content

Multi-file/ AnnData access and torch data loader: AnnCollection and AnnLoader - #416

Merged
ivirshup merged 77 commits into
masterfrom
pytorch
Sep 1, 2021
Merged

ivirshup merged 77 commits into
masterfrom
pytorch

Conversation

@Koncopd

@Koncopd Koncopd commented Aug 9, 2020 •

Copy link
Copy Markdown
Member

This PR brings two new data objects to the main API.

  • anndata.dev.AnnLoader: An interface to pytorch DataLoader.
  • anndata.dev.AnnCollection: An interface to collections of AnnData objects and files, to iterate over and index into.

The PR started out with open-sourced code written by @falexwolf & @yugeji at @Cellarity: #412.

@Koncopd
Koncopd force-pushed the pytorch branch 2 times, most recently from 9ad2def to 07cf53c Compare August 19, 2020 12:58
@Koncopd

Koncopd commented Aug 23, 2020

Copy link
Copy Markdown
Member Author

Hi, @adamgayoso .
I'm developing the dataloader interface for anndata now, here is the draft. We can discuss what is actually needed from this interface, as scVI can be an important use case for this, i suppose.

@adamgayoso

Copy link
Copy Markdown
Member

Hi @Koncopd, this is very intriguing and looks good! There are a few early comments I have.

  1. For our implementation, we opted not to copy any data from the anndata object. I see here that if it's sparse, you can make it dense. We instead make a minibatch dense in the getitem of the torch dataset. This is a bit slower but if your data is massive it could be the only way to do it?
  2. We tried to make it flexible enough such that you can get many tensors from the anndata (e.g., X, and obsm df or ndarray, obs vectors, var vectors etc.) To do this, we have the getitem return a dictionary (btw I think your getitem just needs to return numpy as torch should make them tensors for you, though we handle cuda a bit differently than you). Generally, this flexibility to grab tensors will help us when we implement the option to condition on many covariates
  3. We don't split the anndata into train/test, instead we just specify train/test/val indices in the dataloader to reduce any additional data copying.

I'm not sure you should/need to implement any of my comments. I just think that it's probable we will need a custom implementation anyway. We also need custom code to check that categorical things like labels or RNA-seq batches are encoded consistently. I see here that you use LabelEncoder -- we decided to add .obs fields with the cats and codes for the labels, as well as store the mapping in .uns so that you can "transfer" the codes to a new anndata that potentially has a subset of labels of the source anndata. Honestly not sure what the best way to do this is -- we just wanted to make things user friendly.

@Koncopd

Koncopd commented Aug 24, 2020

Copy link
Copy Markdown
Member Author

Thank you for the comments.
As for 2, i think about implementing batch as an anndata view which can convert arrays to tensors inside getitem.

@adamgayoso

Copy link
Copy Markdown
Member

If I recall, we found that slicing the anndata itself is much slower than each of it's arrays/dfs individually.

@falexwolf

Copy link
Copy Markdown
Member

Just seeing this now, @adamgayoso! Thank you very much! Let's see how much we can adopt and through that, potentially, converge to a canonical solution for interfacing anndata with pytorch. NVIDIA themselves said they're interested in contributing, too.


For our implementation, we opted not to copy any data from the anndata object. I see here that if it's sparse, you can make it dense. We instead make a minibatch dense in the getitem of the torch dataset. This is a bit slower but if your data is massive it could be the only way to do it?

@Koncopd, I thought that this is how we also did it at least in the early chunking iterators?

We don't split the anndata into train/test, instead we just specify train/test/val indices in the dataloader to reduce any additional data copying.

Agreed!

I see here that you use LabelEncoder -- we decided to add .obs fields with the cats and codes for the labels, as well as store the mapping in .uns so that you can "transfer" the codes to a new anndata that potentially has a subset of labels of the source anndata. Honestly not sure what the best way to do this is -- we just wanted to make things user friendly.

I've done the same in the beginning, but we then switched to LabelEncoder as mapping across datasets with potentially highly divergent labels turned out much easier with less custom code than with categories. We're then storing the "trained" LabelEncoder just with the trained model, and not inside the AnnData. Will discuss this.

@falexwolf

falexwolf commented Oct 29, 2020 •

Copy link
Copy Markdown
Member

A potential calling signature for working with many backed AnnDatas, defining splits, and DataLoaders to iterate through a training split.

# assume relevant data for train, validate, holdout split is in several AnnDatas
h5ads = [fileaname1, fileaname2, fileaname3, ...]  # each of them can be backed

# construct a Pseudo-AnnData object, which doesn't actually concatenate, but merely constructs a common index
adod = AdOnDisk(h5ads)
    # AdOnDisk has joint slots for meta-data accessible through canonical accessors

    # adconcat has one joint index and otherwise simply exposes AnnDatas as attributes
    adod.adata1
    adod.adata2
    adod.adata3

    adod.obs_names  # index across all AnnData objects
    adod.obs              # annotations of all AnnData objects, like split, batch, learned annotations - does not store the previous annotations of the separate AnnData

# create splits within the index of AnnDataConcat
adod.obs['split'] = sklearn.test_train_split(adconcat.shape[0], ...)
# alternatively
adod.add_split(....)  # adds a split column to .obs by calling sklearn.test_train_split

# create a loader for the training split that is defined across several AnnDatas

loader = AnnDataLoader(adod[adod.split=='train'])
    adata or adod : AnnData or AnnDataConcat to construct Loader from
    batch_size=32,
    shuffle=True,

AnnDataLoader.iterate(...)
    X=None: specify what needs to be converted to tensors
    obs=None: specify what needs to be converted to tensors

for batch in loader.iterate(
     layer='X', obs=['label1', 'label2', 'domain']
):  # passing None will convert everything to tensors
      batch.X  # is a tensor
      batch.obs  # is a dictionary/ Namespace fo 1-dim tensors storing columns ['label1', 'label2', 'domain']
      batch.obs.label1  # is a 1-dim tensor

@falexwolf falexwolf changed the title Pytorch dataloader interface Multi-file iterator and torch data loader: AdOnDisk and DataLoader Nov 26, 2020
@falexwolf falexwolf changed the title Multi-file iterator and torch data loader: AdOnDisk and DataLoader Multi-file iterator and torch data loader: AnnDataSet and DataLoader Nov 26, 2020
@falexwolf

Copy link
Copy Markdown
Member

@ivirshup just suggested to cache all batches on disk to save the reindexing time. That's a really, really cool idea!

@falexwolf

Copy link
Copy Markdown
Member

Indexing logic for a batch of data, given a backed adata:

if not cached:
     batch = adata[batch_idcs].copy()  # load observations batch into memory
     batch = batch.to_dense()  # densify
     batch = batch[:, target_variables]  # subset to target variable names defined for AnnDataSet/ AdCollection
     batch.write(cache_path)
else:
     batch = sc.read(cache_path)

# ... apply model to batch

Need to consider whether one should cache each batch individually or the whole concatenated batches together.

@Koncopd

Koncopd commented Dec 3, 2020 •

Copy link
Copy Markdown
Member Author

This should be optional. If we use it with pytorch, then we have batches with random indices which don't repeat, so this caching just slows the process.

@ivirshup

ivirshup commented Dec 4, 2020

Copy link
Copy Markdown
Member

Sergei, my worry was less with the concatenation along obs (which should be fast-ish, assuming csr matrices) but with reindexing along the variables (which will be slow). If objects have been filtered differently or genes are ordered differently then you'd could save a fair amount of time on each batch if it was just cached.

@Koncopd

Koncopd commented Dec 8, 2020

Copy link
Copy Markdown
Member Author

Yes, now i see your point. I will add obs index caching.

@Koncopd
Koncopd force-pushed the pytorch branch 2 times, most recently from 9fe18fc to 46a2fea Compare March 31, 2021 16:54
@Koncopd

Koncopd commented May 26, 2021

Copy link
Copy Markdown
Member Author

O, this is ready now in terms of functionality.
A small example is here .

It still needs documentation though.

@falexwolf

Copy link
Copy Markdown
Member

Consider

autodoc_mock_imports = [
    "torch",
]

@codecov

codecov Bot commented Jun 11, 2021 •

Copy link
Copy Markdown

Codecov Report

Merging #416 (fc4b189) into master (ec22e1b) will decrease coverage by 3.33%.
The diff coverage is 63.09%.

@@            Coverage Diff             @@
##           master     #416      +/-   ##
==========================================
- Coverage   86.71%   83.37%   -3.34%     
==========================================
  Files          25       30       +5     
  Lines        3545     4133     +588     
==========================================
+ Hits         3074     3446     +372     
- Misses        471      687     +216     
Impacted Files Coverage Δ
anndata/experimental/pytorch/_annloader.py 22.91% <22.91%> (ø)
anndata/experimental/multi_files/_anncollection.py 70.69% <70.69%> (ø)
anndata/experimental/__init__.py 100.00% <100.00%> (ø)
anndata/experimental/multi_files/__init__.py 100.00% <100.00%> (ø)
anndata/experimental/pytorch/__init__.py 100.00% <100.00%> (ø)
... and 1 more

@Koncopd

Koncopd commented Jun 12, 2021

Copy link
Copy Markdown
Member Author

Here is a simple AnnDataSet example with some simple benchmarks.

@gokceneraslan

Copy link
Copy Markdown
Contributor

Looks cool! Are you guys planning to implement a .write() method too? 🤓

@Koncopd

Koncopd commented Jun 13, 2021

Copy link
Copy Markdown
Member Author

Maybe.
I there is no need of X or layers, it can be done with a.to_adata().write(...).

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

Re @gokceneraslan's comment: as I've discussed with Sergei before, I think this would be useful for combining large datasets without having to do it all in memory. It could also have some performance benefits for iterating over the data so you don't have to keep indexing along the slow axis.

Comments on the tutorial

Not exactly API related, but it looks like both datasets have counts in X, so they should probably be normalized before computing the PCA.

API

Consistency with concat

dataset = AnnDataSet([covid, pbmc], join_vars='inner', join_obs='outer', join_obsm='inner')

It would be nice if this followed the same conventions as concat for specifying joins. I do see how it can be useful to specify different joins for the different collections, but maybe this could be made more general? Maybe we could allow nested input for join, like join={"vars": "inner", "obs": "outer"}?

label seems broken:

This errors:

dataset = AnnDataSet([covid, pbmc], join_vars='inner', label="dataset")
traceback
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-24-f0c875e4c055> in <module>
----> 1 dataset = AnnDataSet([covid, pbmc], join_vars='inner', label="dataset")

~/github/anndata/anndata/dev/multi_files/_anndataset.py in __init__(self, adatas, join_obs, join_obsm, join_vars, label, keys, index_unique, convert, harmonize_dtypes)
    483             self.obs = pd.DataFrame(index=self.obs_names)
    484         if label is not None:
--> 485             self.obs[label] = label_col
    486 
    487         # process obsm inner join

UnboundLocalError: local variable 'label_col' referenced before assignment

None vs empty inner product

On a related note, I noticed you could end up with None for AnnDataSet.obsm. I'd recommend just having it be an empty mapping if it's empty, otherwise you run into issues like this throwing an error:

dataset = AnnDataSet([covid, pbmc], join_vars='inner', join_obs=None)
both_concat = sc.concat({"covid": covid, "pbmc": pbmc}, label="dataset")

sc.pp.pca(both_concat)

dataset.obsm["X_pca"] = both_concat.obsm["X_pca"]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-f2d82e37bf30> in <module>
----> 1 dataset.obsm["X_pca"] = both_concat.obsm["X_pca"].copy()

TypeError: 'NoneType' object does not support item assignment

AnnDataSet indexing

benchmarks

I was surprised to see the benchmarks for indexing. Looking into it a bit, I think a large amount of the timing difference comes from the default anndata object call removing unused categories from the generated dataframe. We could reconsider this behavior, though arguably the dataframes should be lazily generated anyways.

Example (easier to see with snakeviz)
%prun -s cumtime covid[np.random.choice(ds_covid.shape[0], 200, replace=False)]
         18873 function calls (18614 primitive calls) in 0.022 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.022    0.022 {built-in method builtins.exec}
        1    0.000    0.000    0.022    0.022 <string>:1(<module>)
        1    0.000    0.000    0.020    0.020 anndata.py:1106(__getitem__)
        1    0.000    0.000    0.020    0.020 anndata.py:282(__init__)
        1    0.000    0.000    0.020    0.020 anndata.py:325(_init_as_view)
        2    0.000    0.000    0.016    0.008 anndata.py:1111(_remove_unused_categories)
       19    0.000    0.000    0.006    0.000 frame.py:3147(__setitem__)
       19    0.000    0.000    0.006    0.000 frame.py:3231(_set_item)

Semantics

It's a little unclear to me what the semantics of the AnnDataSetView object are supposed to be. Could you clarify this?

For example, X is just a matrix, but obs and obsm are some kind of view? What are these views meant to do?

On the implementation side, these views look like they are creating circular references which can be bad for garbage collection.

Backed datasets giving incorrect results:

It looks like indexing the AnnDataSet made of backed objects is returning incorrect data for X

Example

Setup:

both_concat = sc.concat({"covid": covid, "pbmc": pbmc}, label="dataset")

assert both_concat.obs_names.equals(dataset.obs_names)
assert both_concat.var_names.equals(dataset.var_names)

# Backed AnnDataSet
pbmc_b = sc.read('pbmc_seurat_v4.h5ad', backed='r')
covid_b = sc.read('covid_cite.h5ad', backed='r')

dataset_b = AnnDataSet([covid_b , pbmc_b], join_vars='inner', join_obs=None, join_obsm='inner')

assert dataset_b.var_names.equals(both_concat.var_names)
assert dataset_b.obs_names.equals(both_concat.obs_names)

Checking indexing:

for _ in range(10):
    idx = np.random.choice(both_concat.shape[0], 200, replace=False)
    # This should be zero if they are equivalent
    print((dataset_b[idx].X != both_concat.X[idx, :]).sum())
838873
811316
813318
841387
790324
802966
777457
787657
797884
777062

Regular datasets giving incorrect results as well

Going back and checking the in memory example, the same problem occurs. It looks like it has to do with the order of the indices. If idx is sorted, values seem to be correct.

Evidence
dataset = AnnDataSet([covid, pbmc], join_vars='inner', join_obs='outer', join_obsm='inner')
both_concat = sc.concat({"covid": covid, "pbmc": pbmc}, label="dataset")

for _ in range(10):
    idx = np.random.choice(both_concat.shape[0], 200, replace=False)

    dataset_v = dataset[idx]
    full_v = both_concat[idx]

    assert dataset_v.obs_names.equals(full_v.obs_names)
    assert dataset_v.var_names.equals(full_v.var_names)

    print("not equal: ", (dataset[idx].X != both_concat.X[idx, :]).sum())
    print("nnz: ", (dataset[idx].X != 0).sum(), (both_concat[idx].X != 0).sum())

    idx.sort()

    print("not equal: ", (dataset[idx].X != both_concat.X[idx, :]).sum())
    print("nnz: ", (dataset[idx].X != 0).sum(), (both_concat[idx].X != 0).sum())

    print()
not equal:  653818
nnz:  441385 441385
not equal:  0
nnz:  441385 441385

not equal:  623411
nnz:  422718 422718
not equal:  0
nnz:  422718 422718

not equal:  639472
nnz:  432783 432783
not equal:  0
nnz:  432783 432783

not equal:  632192
nnz:  428748 428748
not equal:  0
nnz:  428748 428748

not equal:  670835
nnz:  453948 453948
not equal:  0
nnz:  453948 453948

not equal:  681459
nnz:  458249 458249
not equal:  0
nnz:  458249 458249

not equal:  628125
nnz:  437684 437684
not equal:  0
nnz:  437684 437684

not equal:  669581
nnz:  451142 451142
not equal:  0
nnz:  451142 451142

not equal:  621809
nnz:  422294 422294
not equal:  0
nnz:  422294 422294

not equal:  653981
nnz:  437701 437701
not equal:  0
nnz:  437701 437701

If it's not sorted, I think the values start being wrong at the first row where the datasets aren't in their original order. E.g. in this example, the rows have the wrong values for all rows following the first integer in idx that maps to the pbmc dataset.

Probably not worth reading too much into the combined benchmarking results until this is fixed.

Naming

I'm starting to agree more with @falexwolf about the name being confusing. In particular, this line is just weird:

dataset.obs['dataset'] = pd.Series(dtype='O')

I think there's to much confusion about what a "dataset" is here, since each AnnData is a dataset, but they're combined into an AnnDataSet.

@Koncopd

Koncopd commented Jun 15, 2021

Copy link
Copy Markdown
Member Author

@ivirshup thank you for the comments, i have fixed the bugs and updated the example with benchmarks.

@Koncopd

Koncopd commented Jun 15, 2021

Copy link
Copy Markdown
Member Author

Here is an example of AnnDataLoader usage with 2 adatas.

@ivirshup

Copy link
Copy Markdown
Member

i have fixed the bugs and updated the example with benchmarks.

Could you add tests for these before I look into this more? I'd like to know that these stay fixed through further updates. Plus, tests are a good way to find bugs.

Related: I think there might be an issue with access to the .obs of an AnnDataSet, as they appear to be returning numpy arrays instead of pandas Series.

@falexwolf falexwolf changed the title Multi-file iterator and torch data loader: AnnDataSet and DataLoader Multi-file/ AnnData access and torch data loader: AnnCollection and AnnDataLoader Jul 26, 2021
@falexwolf

Copy link
Copy Markdown
Member

This is all progressing well!

I realize that the following attribute does not seem to be documented?

convert = {'obs':
           {'orig.ident': lambda s: enc.transform(s.to_numpy()[: , None]),
            labels: lambda c: enc_ct.transform(c.to_numpy()[: , None])[:, :-1]
           }
          }

dataset.convert = convert

How do we think about that? https://icb-anndata--416.com.readthedocs.build/en/416/anndata.dev.AnnDataSet.html

@Koncopd

Koncopd commented Jul 26, 2021 •

Copy link
Copy Markdown
Member Author

It is documented here.
Also convert option in your link.

@falexwolf

Copy link
Copy Markdown
Member

Thanks! I've just hidden AnnDataSetView from the main API; users should not have to know it.

Can you add a link to this feature from AnnDataSet itself, even if it's just a property of the view?

I would suggest to make this a property of AnnDataSet that errors as long as it's not yet a view, and becomes functional once it's a view.

And then only have the AnnDataSet.convert property documented.

@Koncopd

Koncopd commented Jul 26, 2021

Copy link
Copy Markdown
Member Author

Actually i will make it a property (it isn't now), it even should not give any errors on access or setting.

@Koncopd

Koncopd commented Jul 26, 2021

Copy link
Copy Markdown
Member Author

@falexwolf
It seems that hidden doesn't work, it breaks the docs. You also deleted read_hdf from the docs, was it deliberate?

@falexwolf

Copy link
Copy Markdown
Member

You also deleted read_hdf from the docs, was it deliberate?

Yes, was deliberate! It's legacy that clutters the page. Isaac wanted to deprecate it in the code soon, anyway.

Strange that hidden doesn't work, I've been using it a lot for hiding non-top level objects from the main APIs, but still generating a page to reference from sub-pages deeper in the hierarchy. We'll converge this.

# AnnDataLoader has the same arguments as DataLoader, but uses BatchIndexSampler by default
class AnnDataLoader(DataLoader):
"""\
PyTorch DataLoader for AnndData objects.

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.

Typo!

Comment thread anndata/dev/__init__.py Outdated
@@ -0,0 +1,2 @@
from .multi_files import AnnDataSet

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.

Both of the submodules should be private so that users do not see the lookups: ._multi_files and ._pytorch.

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

harmonize_dtypes

harmonize_dtypes
If True, all retrieved arrays from subset objects will have the same dtype.

When would you want this to be false? What does that look like? Object arrays? Depends on the subset retrieved?

join_obs, join_obsm, vs convert={"obs": ..., "obsm": })

Why not have either special keyword arguments for convert_obs, or allow join={"obs": ...., "obsm": ...}

Comment on lines +37 to +38
np.testing.assert_allclose(_dense(dat_view.X), _dense(adt_view.X))
np.testing.assert_allclose(dat_view.obsm["o_test"], adt_view.obsm["o_test"])

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.

Why only close?

le.fit(dat[:].obs["a_test"])

obs_no_convert = dat[:].obs["a_test"]
convert = dict(obs={"a_test": lambda a: le.transform(a)})

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.

Suggested change
convert = dict(obs={"a_test": lambda a: le.transform(a)})
convert = dict(obs={"a_test": le.transform})



@pytest.mark.parametrize("adatas", [np.array], indirect=True)
def test_convert(adatas):

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.

Could you check conversion for other elements as well?

from sklearn.preprocessing import LabelEncoder
from anndata.dev.multi_files import AnnDataSet

_dense = lambda a: a.toarray() if issparse(a) else a

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've got the helper: anndata.utils.asarray for doing this



@pytest.mark.parametrize("adatas", [np.array, csr_matrix], indirect=True)
def test_full_selection(adatas):

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.

If you'd like to test for subsetting (and making sure you've covered more cases) I'd suggest looking at test_views.py and the subset_func fixture.

@Koncopd

Koncopd commented Jul 28, 2021 •

Copy link
Copy Markdown
Member Author

convert is kind of uniform across attributes and\or keys (you provide an attribute name, a key and a converter function), but join_obs and join_obsm have different sets of possible values (None, 'inner' for the latter, 'outer', 'inner', None for the former). And convert is not only an initialization option but also a property of both objects (AnnDataSet and view).

@Koncopd

Koncopd commented Jul 28, 2021 •

Copy link
Copy Markdown
Member Author

For harmonize_dtypes what is meant for example when you have 2 adatas and .X for the first has dtype float32 and for the second float64. When you create AnnDataSet with harmonize_dtypes=True every subselection will give you .X with dtype float64, even when the subset is only from the first adata. This obviously has to copy the subset of .X during dtype conversion.
You can have harmonize_dtypes=False to avoid this conversion of dtypes when you don't care, for example when you need only to have a sum along axis as in the example with size factors, or any iterative preprocessing for which dtypes are not important.

@Koncopd

Koncopd commented Jul 28, 2021

Copy link
Copy Markdown
Member Author

As discussed with @falexwolf and @ivirshup AnnDataLoader was renamed to AnnLoader and AnnDataSet to AnnCollection. In the tutorials also. This is the final naming.

@Koncopd Koncopd changed the title Multi-file/ AnnData access and torch data loader: AnnCollection and AnnDataLoader Multi-file/ AnnData access and torch data loader: AnnCollection and AnnLoader Jul 29, 2021
@ivirshup

ivirshup commented Sep 1, 2021

Copy link
Copy Markdown
Member

So, after discussion with @falexwolf, it sounds like it's more useful to have this merged since other people are going to be working with it. Planning on doing that once the CI checks pass.

I've made one major change, which is renaming the .dev module to .experimental so it fits with what we're doing for scanpy (scverse/scanpy#1715).

@ivirshup
ivirshup merged commit 451f73b into master Sep 1, 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.

6 participants