Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proof of concept of similarity search with the scivision model #5

Merged
merged 17 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[flake8]
max-line-length=120
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ jobs:
uses: py-actions/flake8@v2
with:
max-line-length: "120"
path: "cyto_ml"
path: cyto_ml
plugins: "flake8-bugbear==22.1.11 flake8-black"
2 changes: 1 addition & 1 deletion .github/workflows/pytest_coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
python-version: ${{ matrix.python-version }}
auto-activate-base: false
- run: pip install pytest-cov
- run: python -m pytest --cov=cyto_ml --cov-report xml:coverage.xml tests/
- run: python -m pytest --cov=cyto_ml --cov-report xml:coverage.xml
- uses: actions/upload-artifact@v4
with:
name: coverage.xml
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.env
**/.ipynb_checkpoints/
**/__pycache__/
vectors/
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ conda create -n cyto_39 python=3.9
conda env update
```

Please note that this is specifically pinned to python 3.9 due to dependency versions; we make experimental use of the [https://sci.vision/#/model/resnet50-plankton](CEFAS plankton model available through SciVision), which in turn uses an older version of pytorch that isn't packaged above python 3.9.
Please note that this is specifically pinned to python 3.9 due to dependency versions; we make experimental use of the [CEFAS plankton model available through SciVision](https://sci.vision/#/model/resnet50-plankton), which in turn uses an older version of pytorch that isn't packaged above python 3.9.

### Object store connection

Expand All @@ -40,7 +40,7 @@ Get started by cloning this repository and running

### Feature extraction

Experiment testing workflows by using [https://sci.vision/#/model/resnet50-plankton](this plankton model from SciVision) to extract features from images for use in similarity search, clustering, etc.
Experiment testing workflows by using [this plankton model from SciVision](https://sci.vision/#/model/resnet50-plankton) to extract features from images for use in similarity search, clustering, etc.

### TBC (object store upload, derived classifiers, etc)

Expand Down
31 changes: 31 additions & 0 deletions cyto_ml/data/intake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Utilities for expressing our dataset as an intake catalog"""


def intake_yaml(
test_url: str,
catalog_url: str,
):
"""
Write a minimal YAML template describing this as an intake datasource
Example: plankton dataset made available through scivision, metadata
https://raw.githubusercontent.com/alan-turing-institute/plankton-cefas-scivision/test_data_catalog/scivision.yml
See the comments below for decisions about its structure
"""
template = f"""
sources:
test_image:
description: Single test image from the plankton collection
origin:
driver: intake_xarray.image.ImageSource
args:
urlpath: ["{test_url}"]
exif_tags: False
plankton:
description: A CSV index of all the images of plankton
origin:
driver: intake.source.csv.CSVSource
args:
urlpath: ["{catalog_url}"]
"""
# coerce_shape: [256, 256]
return template
20 changes: 20 additions & 0 deletions cyto_ml/data/s3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Thin wrapper around the s3 object store with images and metadata"""

import s3fs
from dotenv import load_dotenv
import os

load_dotenv()


def s3_endpoint():
"""Return a reference to the object store,
reading the credentials set in the environment.
"""
fs = s3fs.S3FileSystem(
anon=False,
key=os.environ.get("FSSPEC_S3_KEY", ""),
secret=os.environ.get("FSSPEC_S3_SECRET", ""),
client_kwargs={"endpoint_url": os.environ["ENDPOINT"]},
)
return fs
17 changes: 14 additions & 3 deletions cyto_ml/data/vectorstore.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import chromadb
from chromadb.db.base import UniqueConstraintError
import os
from typing import Optional
import logging

import chromadb
from chromadb.db.base import UniqueConstraintError
from chromadb.config import Settings


logging.basicConfig(level=logging.INFO)
# TODO make this sensibly configurable, not confusingly hardcoded
STORE = os.path.join(os.path.abspath(os.path.dirname(__file__)), "../../vectors")

client = chromadb.PersistentClient(path="./vectors")
client = chromadb.PersistentClient(
path=STORE,
settings=Settings(
anonymized_telemetry=False,
),
)


def vector_store(name: Optional[str] = "test_collection"):
Expand Down
6 changes: 6 additions & 0 deletions cyto_ml/models/scivision.py
Copy link
Collaborator

Choose a reason for hiding this comment

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

test_image_embeddings fails whenever a cuda device is available because prepare_image moves tensors to the default cuda device whereas the scivision model returned by truncate_model lives on the CPU. My feeling is that truncate_model is fine and prepare_image doesn't need to mess with the device. Could we just remove lines 47-49?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Ugh, I didn't test this anywhere with a GPU available.

In past projects we did this spelled out long-hand, e.g. with device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') - awkward if you've got more than one GPU, plus you keep having to remember

https://pytorch.org/tutorials/recipes/recipes/changing_default_device.html - reading that in PyTorch 2 there are cleaner ways of doing it, including a context manager. But this project is pinned to an older torch 1.* because that's required by the older scivision plankton model, cf alan-turing-institute/plankton-cefas-scivision#5

We don't yet have a timeline for testing the new transformer based model, should follow up with Turing Inst folks about that - I'll try to find a handle.

Copy link
Collaborator

Choose a reason for hiding this comment

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

This may be very specific to the ways I've used PyTorch, but I've never really found that moving things between devices generated too much boilerplate, whereas abstracting it away sometimes led to more problems than it solved.

I definitely don't think prepare_image should try to change the device since there are too many situations where you wouldn't want that - e.g. if you had a GPU but it didn't have enough memory for the full dataset.

If we wanted to abstract everything away we might consider using PyTorch Lightning, or otherwise replicating the LightningDataModule. Personally I'd prefer a more minimalist solution though.

Anyway I will have a think and make a new PR to discuss further!

Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,9 @@ def prepare_image(image: DataArray):
tensor_image = tensor_image.cuda()

return tensor_image


def flat_embeddings(features: torch.Tensor):
"""Utility function that takes the features returned by the model in truncate_model
And flattens them into a list suitable for storing in a vector database"""
return list(features[0].squeeze(1).squeeze(1).detach().numpy().astype(float))
11 changes: 10 additions & 1 deletion tests/conftest.py → cyto_ml/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import os
import pytest

from cyto_ml.models.scivision import (
load_model,
truncate_model,
SCIVISION_URL,
)


@pytest.fixture
Expand All @@ -22,3 +26,8 @@ def single_image(image_dir):
@pytest.fixture
def image_batch(image_dir):
return os.path.join(image_dir, "testymctestface_*.tif")


@pytest.fixture
def scivision_model():
return truncate_model(load_model(SCIVISION_URL))
13 changes: 13 additions & 0 deletions cyto_ml/tests/test_image_embeddings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from intake_xarray import ImageSource
from torch import Tensor
from cyto_ml.models.scivision import prepare_image, flat_embeddings


def test_embeddings(scivision_model, single_image):
features = scivision_model(prepare_image(ImageSource(single_image).to_dask()))

assert isinstance(features, Tensor)

embeddings = flat_embeddings(features)

assert len(embeddings) == features.size()[1]
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# test_prepare_image.py
import pytest
import torch
import logging
from intake_xarray import ImageSource
from cyto_ml.models.scivision import prepare_image

Expand All @@ -10,7 +11,7 @@
def test_single_image(single_image):

image_data = ImageSource(single_image).to_dask()
# Prepare the image
# Tensorise the image (potentially normalise if we have useful values)
prepared_image = prepare_image(image_data)

# Check if the shape is correct (batch dimension added)
Expand All @@ -19,15 +20,17 @@ def test_single_image(single_image):

def test_image_batch(image_batch):
"""
Currently expected to fail because dask wants images to share dimensions
Currently expected to fail because dask wants images to share dimensions, ours don't
Needs digging into the (source) data from the FlowCam that gets decollaged
We either pad them (and process a lot of blank space) or stick to single image input
"""
# Load a batch of plankton images

image_data = ImageSource(image_batch).to_dask()

with pytest.raises(ValueError) as err:
prepared_batch = prepare_image(image_data)
print(err)
_ = prepare_image(image_data)
logging.info(err)
# Check if the shape is correct
# assert prepared_batch.shape == torch.Size([64, 89, 36, 3])

Expand Down
21 changes: 21 additions & 0 deletions cyto_ml/tests/test_vector_store.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from cyto_ml.data.vectorstore import vector_store, client
import numpy as np


def test_client_no_telemetry():
assert not client.get_settings()["anonymized_telemetry"]


def test_store():
store = vector_store() # default 'test_collection'
id = "id_1" # insists on a str
filename = "https://example.com/filename.tif"
store.add(
documents=[filename], # we use image location in s3 rather than text content
embeddings=[list(np.random.rand(2048))], # wants a list of lists
ids=[id],
) # wants a list of ids

record = store.get("id_1", include=["embeddings"])
assert record
assert len(record["embeddings"][0]) == 2048
2 changes: 2 additions & 0 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ dependencies:
- dask
- pip:
- pytest
- imagecodecs
- intake # for reading scivision
- torch==1.10.0 # install before cefas_scivision; it needs this version
- scivision
- scikit-image
- setuptools==69.5.1 # because this bug https://github.com/pytorch/serve/issues/3176
- tiffile
Copy link
Collaborator

@jmarshrossney jmarshrossney Jul 21, 2024

Choose a reason for hiding this comment

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

I think tiffile is deprecated and this should now be tifffile (3 fs)!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

but

[~]$ pip install tiffile
Collecting tiffile
  Using cached tiffile-2018.10.18-py2.py3-none-any.whl.metadata (883 bytes)
Collecting tifffile (from tiffile)
  Downloading tifffile-2024.7.21-py3-none-any.whl.metadata (31 kB)
Collecting numpy (from tifffile->tiffile)
  Downloading numpy-2.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (60 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 60.9/60.9 kB 9.7 MB/s eta 0:00:00
Using cached tiffile-2018.10.18-py2.py3-none-any.whl (2.7 kB)
Downloading tifffile-2024.7.21-py3-none-any.whl (225 kB)

???

Copy link
Collaborator

Choose a reason for hiding this comment

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

fair enough!

- git+https://github.com/alan-turing-institute/plankton-cefas-scivision@main # torch version
- chromadb
Copy link
Collaborator

Choose a reason for hiding this comment

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

The latest version of chromadb (0.5.4) causes test_vector_store to fail with an AttributeError because for whatever reason chromadb.api.models.Collection no longer has an attribute model_fields. I'm none the wiser after reading the related issue and don't really want to dig deeper so for now we can just move forward by pinning chromadb==0.5.3.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This looks rooted a transitory issue in chromadb related to version back-incompatibility in pydantic (data validation through type checking) - reading chroma-core/chroma#2503 that team is firmly on the case and 0.5.5 should cause this problem to solve itself (always having version pinned dependencies would be a healthy habit i should adopt, though)

Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think there's much that can be done when this sort of thing happens, unless you're not really interested in broad support and can just lock down all your dependencies, in which case it makes sense to use lockfiles (#14) ! Good to know they're fixing it though.

Loading
Loading