# Autotune failed due to "h5py objects cannot be pickled"

**URL:** <https://discourse.scverse.org/t/autotune-failed-due-to-h5py-objects-cannot-be-pickled/3308>\
**Category:** scvi-tools\
**Created:** [October 20, 2024, 11:20pm UTC](https://discourse.scverse.org/t/autotune-failed-due-to-h5py-objects-cannot-be-pickled/3308 "2024-10-20T23:20:12Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![tangxj](https://avatars.discourse-cdn.com/v4/letter/t/bc8723/32.png) [@tangxj](https://discourse.scverse.org/u/tangxj)\
**Post date:** [October 20, 2024, 11:20pm UTC](https://discourse.scverse.org/t/autotune-failed-due-to-h5py-objects-cannot-be-pickled/3308/1 "2024-10-20T23:20:12Z")

</div>

Hi,

I am trying to tune the parameters. However it failed due to an error saying that “h5py objects cannot be pickled”. I read some related posts saying similar failure due to multiprocessing and reduced the GPU to only 1. But it still failed. Also the tutorial seems doing file with multiple CPUs or GPUs. What should I do to avoid the problem?

I also have the same error (h5py objects cannot be pickled) when I tried to save models using pickle on the cluster, but it worked in the standard python environment.

```
model_cls = scvi.model.SCVI
model_cls.setup_anndata(adata, layer="counts", batch_key="source", size_factor_key="size_factors")

# search space
search_space = {
    "model_params": {"n_hidden": tune.choice([64, 128, 256]), "n_layers": tune.choice([1, 2, 3]),"n_latent": tune.choice([25, 30, 40, 50, 60]),"lr": tune.loguniform(1e-4, 1e-2),"gene_likelihood": tune.choice(["nb", "zinb"])},
    "train_params": {"max_epochs": max_epochs},
}

ray.init(log_to_driver=False)
results = autotune.run_autotune(
    model_cls,
    data=adata,
    metrics="validation_loss",
    mode='min',
    search_space=search_space,
    searcher="hyperopt",
    scheduler="asha",
    num_samples=50,
    resources={"gpu": 1},
)

```

Error message trackback is listed below.

**Traceback (most recent call last):**  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/worker.py”, line 764, in put\_object\*\*  
\*\* serialized\_value = self.get\_serialization\_context().serialize(value)\*\*  
\*\* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/serialization.py”, line 519, in serialize\*\*  
\*\* return self.\_serialize\_to\_msgpack(value)\*\*  
\*\* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/serialization.py”, line 497, in \_serialize\_to\_msgpack\*\*  
\*\* pickle5\_serialized\_object = self.\_serialize\_to\_pickle5(\*\*  
\*\* ^^^^^^^^^^^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/serialization.py”, line 444, in \_serialize\_to\_pickle5\*\*  
\*\* raise e\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/serialization.py”, line 439, in \_serialize\_to\_pickle5\*\*  
\*\* inband = pickle.dumps(\*\*  
\*\* ^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/cloudpickle/cloudpickle.py”, line 1479, in dumps\*\*  
\*\* cp.dump(obj)\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/cloudpickle/cloudpickle.py”, line 1245, in dump\*\*  
\*\* return super().dump(obj)\*\*  
\*\* ^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/h5py/\_hl/base.py”, line 370, in **getnewargs** \*\*  
\*\* raise TypeError(“h5py objects cannot be pickled”)\*\*  
**TypeError: h5py objects cannot be pickled**  
**The above exception was the direct cause of the following exception:**  
**Traceback (most recent call last):**  
\*\* File “~/users/project\_scvi/working/ourdata/run\_autotune.py”, line 92, in \*\*  
\*\* main(args.suffix, args.max\_epochs)\*\*  
\*\* File “~/users/project\_scvi/working/ourdata/run\_autotune.py”, line 81, in main\*\*  
\*\* setup\_and\_tune\_model(adata, max\_epochs)\*\*  
\*\* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/project\_scvi/working/ourdata/run\_autotune.py”, line 47, in setup\_and\_tun\*\*  
**e\_model**  
\*\* results = autotune.run\_autotune(\*\*  
\*\* ^^^^^^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/scvi/autotune/\_tune.py”, line 132, in run\_autotune\*\*  
\*\* experiment.result\_grid = experiment.get\_tuner().fit()\*\*  
\*\* ^^^^^^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/scvi/autotune/\_experiment.py”, line 475, in get\_tuner\*\*  
\*\* trainable = with\_parameters(\_trainable, experiment=self)\*\*  
\*\* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/tune/trainable/util.py”, line 107, in with\_parameters\*\*  
\*\* parameter\_registry.put(prefix + k, v)\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/tune/registry.py”, line 301, in put\*\*  
\*\* self.flush()\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/tune/registry.py”, line 313, in flush\*\*  
\*\* self.references[k] = ray.put(v)\*\*  
\*\* ^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/auto\_init\_hook.py”, line 21, in auto\_init\_wrapper\*\*  
\*\* return fn(_args, **kwargs)**  
\*\* ^^^^^^^^^^^^^^^^^^^_\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/client\_mode\_hook.py”, line 103, in wrapper\*\*  
\*\* return func(_args, **kwargs)**  
\*\* ^^^^^^^^^^^^^^^^^^^^^_\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/worker.py”, line 2772, in put\*\*  
\*\* object\_ref = worker.put\_object(value, owner\_address=serialize\_owner\_address)\*\*  
\*\* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\*\*  
\*\* File “~/users/conda/envs/scvi-env/lib/python3.12/site-packages/ray/\_private/worker.py”, line 773, in put\_object\*\*  
\*\* raise TypeError(msg) from e\*\*  
**TypeError: Could not serialize the put value Experiment scvi\_10e3c6f1-8d59-4062-ab78-fa85b99f136b:**  
**================================================================================**  
**Checking Serializability of Experiment scvi\_10e3c6f1-8d59-4062-ab78-fa85b99f136b**  
**================================================================================**  
**!!! FAIL serialization: h5py objects cannot be pickled**  
\*\* Serializing ‘\_data’ AnnData object with n\_obs × n\_vars = 3967777 × 2000 backed at ‘~/users/project\_scvi/working/ourdata/snRNA\_atlas\_merged\_hvg2k.h5ad’\*\*  
\*\* obs: ‘age’, ‘diagnosis’, ‘cell\_type’, ‘sample\_id’, ‘source’, ‘sex’, ‘size\_factors’, ‘\_scvi\_batch’, ‘\_scvi\_labels’\*\*  
\*\* var: ‘highly\_variable’, ‘highly\_variable\_rank’, ‘means’, ‘variances’, ‘variances\_norm’, ‘highly\_variable\_nbatches’\*\*  
\*\* uns: ‘hvg’, ‘\_scvi\_uuid’, ‘\_scvi\_manager\_uuid’\*\*  
\*\* obsm: ‘X\_pca’, ‘X\_umap’\*\*  
\*\* layers: ‘counts’…\*\*  
\*\* !!! FAIL serialization: h5py objects cannot be pickled\*\*  
\*\* Serializing ‘X’ CSRDataset: backend hdf5, shape (3967777, 2000), data\_dtype float64…\*\*  
\*\* !!! FAIL serialization: h5py objects cannot be pickled\*\*  
\*\* Serializing ‘\_abc\_impl’ \<\_abc.\_abc\_data object at 0x150a689b8e00\>…\*\*  
\*\* !!! FAIL serialization: cannot pickle ‘\_abc.\_abc\_data’ object\*\*  
**================================================================================**  
**Variable:**

\*\* FailTuple(\_abc\_impl [obj=\<\_abc.\_abc\_data object at 0x150a689b8e00\>, parent=CSRDataset: backend hdf5, shape (3967777, 2000), data\_dtype float64])\*\*

**was found to be non-serializable. There may be multiple other undetected variables that were non-serializable.**  
**Consider either removing the instantiation/imports of these variables or moving the instantiation into the scope of the function/class.**

---

<div class="post-metadata">

**Author:** ![cane11](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.scverse.org/cane11/32/241_2.png) [@cane11](https://discourse.scverse.org/u/cane11)\
**Post date:** [October 21, 2024, 2:22am UTC](https://discourse.scverse.org/t/autotune-failed-due-to-h5py-objects-cannot-be-pickled/3308/2 "2024-10-21T02:22:59Z")

</div>

Hi, you use AnnData object in backed mode. Can you verify this?  
\*\* FailTuple(\_abc\_impl [obj=\<\_abc.\_abc\_data object at 0x150a689b8e00\>, parent=CSRDataset: backend hdf5, shape (3967777, 2000), data\_dtype float64])\*\*

Ray can‘t handle backed data. You might be more successful with the dask backend (but it’s not tested in scVI-tools and will likely require work on our end to support).

---

<div class="post-metadata">

**Author:** ![tangxj](https://avatars.discourse-cdn.com/v4/letter/t/bc8723/32.png) [@tangxj](https://discourse.scverse.org/u/tangxj)\
**Post date:** [October 21, 2024, 4:18pm UTC](https://discourse.scverse.org/t/autotune-failed-due-to-h5py-objects-cannot-be-pickled/3308/3 "2024-10-21T16:18:38Z")

</div>

ah yes. I did used backed when I loaded the data. Thank you!  
Now I remove the backed mode and keep everything else. I got a new error saying  
“TypeError: VAE. **init** () got an unexpected keyword argument ‘lr’”.

Am I doing it correctly with “lr”: tune.loguniform(1e-4, 1e-2) in the search\_space statement?

---

<div class="post-metadata">

**Author:** ![ori-kron-wis](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.scverse.org/ori-kron-wis/32/1099_2.png) [@ori-kron-wis](https://discourse.scverse.org/u/ori-kron-wis)\
**Post date:** [October 21, 2024, 5:20pm UTC](https://discourse.scverse.org/t/autotune-failed-due-to-h5py-objects-cannot-be-pickled/3308/5 "2024-10-21T17:20:58Z")

</div>

@tangxj we had similar issue posted in our github repo 2 weeks ago.  
you should check something similar to:

```auto
search_space = {
    "model_params": {"n_hidden": tune.choice([64, 128, 256]), 
                     "n_layers": tune.choice([1, 2, 3, 4]),
                     "n_latent": tune.choice([10, 20, 30, 40, 50]),
                     "gene_likelihood": tune.choice(["nb", "zinb"])
                    },
    "train_params": {"max_epochs": 100,
                    "plan_kwargs": {"lr": tune.loguniform(1e-4, 1e-2)}}}

```

and it should work

---

<div class="post-metadata">

**Author:** ![tangxj](https://avatars.discourse-cdn.com/v4/letter/t/bc8723/32.png) [@tangxj](https://discourse.scverse.org/u/tangxj)\
**Post date:** [October 23, 2024, 4:16pm UTC](https://discourse.scverse.org/t/autotune-failed-due-to-h5py-objects-cannot-be-pickled/3308/6 "2024-10-23T16:16:54Z")

</div>

@ori-kron-wis @cane11 Thank you both for the suggestion very much! It worked and the job has been running for two days and still keeps on running. I examined the current results in the log file (experiment\_state\_\*\*\*.json), it is interesting that the one with minimal validation\_loss out of the 21 runs is:

Item 20: validation\_loss = 1388.1212158203125, experiment\_tag = 21\_gene\_likelihood=zinb,n\_hidden=256,n\_latent=60,n\_layers=2,max\_epochs=200,lr=0.0007

The validation\_loss ranged from 1388 to 1459. Does that mean I should take zinb as the gene likelihood as well as other params?

It seems I was greedy and gave too many options in the search space while I had no idea how long it would take. It seems I might not be able to get the whole tuning finished (my wall time limit was set to 4 days). What would be your suggestion based on your experience? Many thanks!
