Torch
Use pip install datachain[torch] and then import from datachain.torch to use the
PyTorch functionality.
DataChain.to_pytorch converts a
chain into a PyTorch Dataset for downstream tasks like model training or inference.
The classes and methods below help manipulate data from the chain for PyTorch.
clip_similarity_scores
Calculate CLIP similarity scores between one or more images and/or text.
Parameters:
-
images(Union[Image, list[Image]] | None) –Images to use as inputs.
-
text(str | list[str] | None) –Text to use as inputs.
-
model(Any) –Model from clip or open_clip packages.
-
preprocess(Callable) –Image preprocessor to apply.
-
tokenizer(Callable) –Text tokenizer.
-
prob(bool, default:False) –Compute softmax probabilities.
-
image_to_text(bool, default:True) –Whether to compute for image-to-text or text-to-image. Ignored if only one of the images or text provided.
-
device(str | device | None, default:None) –Device to use. Default is None - use model's device.
Example
Using https://github.com/openai/CLIP
Using https://github.com/mlfoundations/open_clip
Using https://huggingface.co/docs/transformers/en/model_doc/clip
Image -> list of text
List of images -> text
List of images -> list of text
List of images -> list of images
List of text -> list of text
Text -> list of images
Show scores as softmax probabilities
Source code in datachain/lib/clip.py
convert_image
Resize, transform, and otherwise convert an image.
Parameters:
-
img(Image) –PIL.Image object.
-
mode(str, default:'RGB') –PIL.Image mode.
-
size(tuple[int, int], default:None) –Size in (width, height) pixels for resizing.
-
transform(Callable, default:None) –Torchvision transform or huggingface processor to apply.
-
encoder(Callable, default:None) –Encode image using model.
-
device(str or device, default:None) –Device to use.
Source code in datachain/lib/image.py
convert_images
Resize, transform, and otherwise convert one or more images.
Parameters:
-
images((Image, list[Image])) –PIL.Image object or list of objects.
-
mode(str, default:'RGB') –PIL.Image mode.
-
size(tuple[int, int], default:None) –Size in (width, height) pixels for resizing.
-
transform(Callable, default:None) –Torchvision transform or huggingface processor to apply.
-
encoder(Callable, default:None) –Encode image using model.
-
device(str or device, default:None) –Device to use.
Source code in datachain/lib/image.py
convert_text
Tokenize and otherwise transform text.
Parameters:
-
text(str) –Text to convert.
-
tokenizer(Callable, default:None) –Tokenizer to use to tokenize objects.
-
tokenizer_kwargs(dict, default:None) –Additional kwargs to pass when calling tokenizer.
-
encoder(Callable, default:None) –Encode text using model.
-
device(str or device, default:None) –Device to use.
Source code in datachain/lib/text.py
label_to_int
Given a value and list of classes, return the index of the value's class.