Repository navigation
Conversation
9ad2def to
07cf53c
Compare
|
Hi, @adamgayoso . |
|
Hi @Koncopd, this is very intriguing and looks good! There are a few early comments I have.
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 |
|
Thank you for the comments. |
|
If I recall, we found that slicing the anndata itself is much slower than each of it's arrays/dfs individually. |
|
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.
@Koncopd, I thought that this is how we also did it at least in the early chunking iterators?
Agreed!
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. |
|
A potential calling signature for working with many backed AnnDatas, defining splits, and DataLoaders to iterate through a training split. |
|
@ivirshup just suggested to cache all batches on disk to save the reindexing time. That's a really, really cool idea! |
|
Indexing logic for a batch of data, given a backed Need to consider whether one should cache each batch individually or the whole concatenated batches together. |
|
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. |
|
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. |
|
Yes, now i see your point. I will add obs index caching. |
9fe18fc to
46a2fea
Compare
|
O, this is ready now in terms of functionality. It still needs documentation though. |
|
Consider |
Codecov Report
@@ 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
|
|
Here is a simple AnnDataSet example with some simple benchmarks. |
|
Looks cool! Are you guys planning to implement a .write() method too? 🤓 |
|
Maybe. |
There was a problem hiding this comment.
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 assignmentNone 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 assignmentAnnDataSet 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.
|
@ivirshup thank you for the comments, i have fixed the bugs and updated the example with benchmarks. |
|
Here is an example of |
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 |
|
This is all progressing well! I realize that the following attribute does not seem to be documented? How do we think about that? https://icb-anndata--416.com.readthedocs.build/en/416/anndata.dev.AnnDataSet.html |
|
It is documented here. |
|
Thanks! I've just hidden Can you add a link to this feature from 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. |
|
Actually i will make it a property (it isn't now), it even should not give any errors on access or setting. |
|
@falexwolf |
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. |
can deprecate somewhere else
| @@ -0,0 +1,2 @@ | |||
| from .multi_files import AnnDataSet | |||
There was a problem hiding this comment.
Both of the submodules should be private so that users do not see the lookups: ._multi_files and ._pytorch.
ivirshup
left a comment
There was a problem hiding this comment.
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": ...}
| 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"]) |
| le.fit(dat[:].obs["a_test"]) | ||
|
|
||
| obs_no_convert = dat[:].obs["a_test"] | ||
| convert = dict(obs={"a_test": lambda a: le.transform(a)}) |
There was a problem hiding this comment.
| 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): |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
|
|
|
For |
|
As discussed with @falexwolf and @ivirshup |
|
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 |
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.