• This repository has been archived on 09/Oct/2023
  • Stars
    star
    1,733
  • Rank 26,695 (Top 0.6 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 3 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Your PyTorch AI Factory - Flash enables you to easily configure and run complex AI recipes for over 15 tasks across 7 data domains

Your PyTorch AI Factory


InstallationFlash in 3 StepsDocsContributeCommunityWebsiteLicense

PyPI - Python Version PyPI Status Slack license

CI testing codecov Documentation Status DOI


Flash makes complex AI recipes for over 15 tasks across 7 data domains accessible to all.
In a nutshell, Flash is the production grade research framework you always dreamed of but didn't have time to build.

Getting Started

From PyPI:

pip install lightning-flash

See our installation guide for more options.

Flash in 3 Steps

Step 1. Load your data

All data loading in Flash is performed via a from_* classmethod on a DataModule. To decide which DataModule to use and which from_* methods are available, it depends on the task you want to perform. For example, for image segmentation where your data is stored in folders, you would use the from_folders method of the SemanticSegmentationData class:

from flash.image import SemanticSegmentationData

dm = SemanticSegmentationData.from_folders(
    train_folder="data/CameraRGB",
    train_target_folder="data/CameraSeg",
    val_split=0.1,
    image_size=(256, 256),
    num_classes=21,
)

Step 2: Configure your model

Our tasks come loaded with pre-trained backbones and (where applicable) heads. You can view the available backbones to use with your task using available_backbones. Once you've chosen one, create the model:

from flash.image import SemanticSegmentation

print(SemanticSegmentation.available_heads())
# ['deeplabv3', 'deeplabv3plus', 'fpn', ..., 'unetplusplus']

print(SemanticSegmentation.available_backbones('fpn'))
# ['densenet121', ..., 'xception'] # + 113 models

print(SemanticSegmentation.available_pretrained_weights('efficientnet-b0'))
# ['imagenet', 'advprop']

model = SemanticSegmentation(
  head="fpn", backbone='efficientnet-b0', pretrained="advprop", num_classes=dm.num_classes)

Step 3: Finetune!

from flash import Trainer

trainer = Trainer(max_epochs=3)
trainer.finetune(model, datamodule=datamodule, strategy="freeze")
trainer.save_checkpoint("semantic_segmentation_model.pt")

PyTorch Recipes

Make predictions with Flash!

Serve in just 2 lines:

from flash.image import SemanticSegmentation

model = SemanticSegmentation.load_from_checkpoint("semantic_segmentation_model.pt")
model.serve()

or make predictions from raw data directly.

from flash import Trainer

trainer = Trainer(strategy='ddp', accelerator="gpu", gpus=2)
dm = SemanticSegmentationData.from_folders(predict_folder="data/CameraRGB")
predictions = trainer.predict(model, dm)

Flash Training Strategies

Training strategies are PyTorch SOTA Training Recipes which can be utilized with a given task.

Check out this example where the ImageClassifier supports 4 Meta Learning Algorithms from Learn2Learn. This is particularly useful if you use this model in production and want to make sure the model adapts quickly to its new environment with minimal labelled data.

from flash.image import ImageClassifier

model = ImageClassifier(
    backbone="resnet18",
    optimizer=torch.optim.Adam,
    optimizer_kwargs={"lr": 0.001},
    training_strategy="prototypicalnetworks",
    training_strategy_kwargs={
        "epoch_length": 10 * 16,
        "meta_batch_size": 4,
        "num_tasks": 200,
        "test_num_tasks": 2000,
        "ways": datamodule.num_classes,
        "shots": 1,
        "test_ways": 5,
        "test_shots": 1,
        "test_queries": 15,
    },
)

In detail, the following methods are currently implemented:

Flash Optimizers / Schedulers

With Flash, swapping among 40+ optimizers and 15+ schedulers recipes are simple. Find the list of available optimizers, schedulers as follows:

from flash.image import ImageClassifier

ImageClassifier.available_optimizers()
# ['A2GradExp', ..., 'Yogi']

ImageClassifier.available_schedulers()
# ['CosineAnnealingLR', 'CosineAnnealingWarmRestarts', ..., 'polynomial_decay_schedule_with_warmup']

Once you've chosen, create the model:

#### The optimizer of choice can be passed as
from flash.image import ImageClassifier

# - String value
model = ImageClassifier(backbone="resnet18", num_classes=2, optimizer="Adam", lr_scheduler=None)

# - Callable
model = ImageClassifier(backbone="resnet18", num_classes=2, optimizer=functools.partial(torch.optim.Adadelta, eps=0.5), lr_scheduler=None)

# - Tuple[string, dict]: (The dict takes in the optimizer kwargs)
model = ImageClassifier(backbone="resnet18", num_classes=2, optimizer=("Adadelta", {"epa": 0.5}), lr_scheduler=None)

#### The scheduler of choice can be passed as a
# - String value
model = ImageClassifier(backbone="resnet18", num_classes=2, optimizer="Adam", lr_scheduler="constant_schedule")

# - Callable
model = ImageClassifier(backbone="resnet18", num_classes=2, optimizer="Adam", lr_scheduler=functools.partial(CyclicLR, step_size_up=1500, mode='exp_range', gamma=0.5))

# - Tuple[string, dict]: (The dict takes in the scheduler kwargs)
model = ImageClassifier(backbone="resnet18", num_classes=2, optimizer="Adam", lr_scheduler=("StepLR", {"step_size": 10}))

You can also register you own custom scheduler recipes beforeahand and use them shown as above:

from flash.image import ImageClassifier

@ImageClassifier.lr_schedulers_registry
def my_steplr_recipe(optimizer):
    return torch.optim.lr_scheduler.StepLR(optimizer, step_size=10)

model = ImageClassifier(backbone="resnet18", num_classes=2, optimizer="Adam", lr_scheduler="my_steplr_recipe")

Flash Transforms

Flash includes some simple augmentations for each task by default, however, you will often want to override these and control your own augmentation recipe. To this end, Flash supports custom transformations with the InputTransform. The InputTransform is like a callback for transforms, with hooks that can be used to apply transforms to samples or batches, on and off the device / accelerator. In addition, hooks can be specialized to apply transforms only to the input or target. With these hooks, complex transforms like MixUp can be implemented with ease. Here's an example (with an albumentations transform thrown in too!):

import torch
import numpy as np
import albumentations
from flash import InputTransform
from flash.image import ImageClassificationData
from flash.image.classification.input_transform import AlbumentationsAdapter


def mixup(batch, alpha=1.0):
    images = batch["input"]
    targets = batch["target"].float().unsqueeze(1)

    lam = np.random.beta(alpha, alpha)
    perm = torch.randperm(images.size(0))

    batch["input"] = images * lam + images[perm] * (1 - lam)
    batch["target"] = targets * lam + targets[perm] * (1 - lam)
    return batch


class MixUpInputTransform(InputTransform):

    def train_input_per_sample_transform(self):
        return AlbumentationsAdapter(albumentations.HorizontalFlip(p=0.5))

    # This will be applied after transferring the batch to the device!
    def train_per_batch_transform_on_device(self):
        return mixup


datamodule = ImageClassificationData.from_folders(
    train_folder="data/train",
    transform=MixUpInputTransform,
    batch_size=2,
)

Flash Zero - PyTorch Recipes from the Command Line!

Flash Zero is a zero-code machine learning platform built directly into lightning-flash using the Lightning CLI.

To get started and view the available tasks, run:

  flash --help

For example, to train an image classifier for 10 epochs with a resnet50 backbone on 2 GPUs using your own data, you can do:

  flash image_classification --trainer.max_epochs 10 --trainer.gpus 2 --model.backbone resnet50 from_folders --train_folder {PATH_TO_DATA}

Kaggle Notebook Examples

Contribute!

The lightning + Flash team is hard at work building more tasks for common deep-learning use cases. But we're looking for incredible contributors like you to submit new tasks!

Join our Slack and/or read our CONTRIBUTING guidelines to get help becoming a contributor!

Note: Flash is currently being tested on real-world use cases and is in active development. Please open an issue if you find anything that isn't working as expected.


Community

Flash is maintained by our core contributors.

For help or questions, join our huge community on Slack!


Citations

We’re excited to continue the strong legacy of opensource software and have been inspired over the years by Caffe, Theano, Keras, PyTorch, torchbearer, and fast.ai. When/if additional papers are written about this, we’ll be happy to cite these frameworks and the corresponding authors.

Flash leverages models from many different frameworks in order to cover such a wide range of domains and tasks. The full list of providers can be found in our documentation.


License

Please observe the Apache 2.0 license that is listed in this repository.

More Repositories

1

lightning-bolts

Toolbox of models, callbacks, and datasets for AI/ML researchers.
Python
1,547
star
2

lightning-transformers

Flexible components pairing 🤗 Transformers with ⚡ Pytorch Lightning
Python
591
star
3

stable-diffusion-deploy

Learn to serve Stable Diffusion models on cloud infrastructure at scale. This Lightning App shows load-balancing, orchestrating, pre-provisioning, dynamic batching, GPU-inference, micro-services working together via the Lightning Apps framework.
Python
328
star
4

Echo

Production-ready audio and video transcription app that can run on your laptop or in the cloud.
TypeScript
67
star
5

lightning-GPT

Train and run GPTs with Lightning
Python
63
star
6

lightning-Covid19

Classification for covid-19 chest X-ray images using Lightning
Python
56
star
7

paper-AAVAE

Python
46
star
8

Research-template

Quickest way to share everything about your research within a single app
Jupyter Notebook
37
star
9

lightning-diffusion_component

Python
25
star
10

DiffusionWithAutoscaler

DiffusionWithAutoscaler
Python
23
star
11

Pose-app

A Lightning app for animal pose estimation.
Python
18
star
12

Training-Studio_app

Lightning HPO & Training Studio App
Python
17
star
13

Research-poster

Quickest way to share everything about your research within a single app
Python
16
star
14

Triton-Server_component

Triton Server Component for lightning.ai
Python
14
star
15

lightning-quick-start

Python
12
star
16

InVideo-search_app

Python
12
star
17

CVPR22-MAE_research-poster

Jupyter Notebook
11
star
18

Flashy_app

Perform Image/Text Classification with ⚡ Flash built using ⚡ AI
Python
10
star
19

open-bio-ml-workshop

Python
9
star
20

Serve_component

Python
9
star
21

HackerNews_app

Jupyter Notebook
8
star
22

lightning-gpt3

Python
7
star
23

dataumbrella22-intro-pytorch

Code for Data Umbrella Talk "Intro to PyTorch and LightningLite
Jupyter Notebook
6
star
24

API-Access-UI_component

TypeScript
6
star
25

Slack-Command-Bot-component

With this component you can create a Slack bot and enable interactivity with the Slash Commands.
Python
5
star
26

Jupyter_component

Jupyter notebook component
Python
5
star
27

Text-Prediction_component

Python
4
star
28

Text-Classification-component

Python
4
star
29

lightning-template-react

TypeScript
4
star
30

AnimeGAN-v2_research-poster

Jupyter Notebook
4
star
31

Redis_component

Redis component for lightning
Python
4
star
32

MarkDown-poster_component

This component lets you make posters from Markdown files.
Python
4
star
33

CodeRunner_app

A sample app which uses Monaco Editor integration, and runs the script on frame from webcam
Python
4
star
34

Finetune-miniLM

Python
4
star
35

Hate-Speech-Detection_app

Python
4
star
36

lightning-Bagua

Lightning Training strategy for Bagua
Python
3
star
37

DeepChecks_app

Deepchecks App with Lightning
Python
3
star
38

lightning-LLMs

Python
3
star
39

Collaborate_app

JavaScript
3
star
40

TLDR-component

Components for training large language models
Python
3
star
41

Telegram-Messenger_component

Python
3
star
42

JupyterLite_component

Jupyter Lite instance runs completely in your browser, powered by Pyodide
Python
3
star
43

FaceNet_research-poster

Jupyter Notebook
3
star
44

Gradio-template

Python
3
star
45

ODSC

tutorial for converting PyTorch to Lightning
Jupyter Notebook
3
star
46

Dalle-mini-poster

🥑 Dalle Mini Poster App | Generate Images from Text Prompt ⚡️
Jupyter Notebook
2
star
47

ICML22-BLIP_research-poster

Python
2
star
48

YOLOv5_research-poster

This app is a research poster demo of YoloV5 Object Detection model by Ultralytics. It showcases a notebook, a blog, and a model demo where you can upload photos to get a bounding box visualized output image.
Jupyter Notebook
2
star
49

video-streaming_component

Python
2
star
50

BigQuery_component

Python
2
star
51

grid-tutorials

Python
2
star
52

ICML22-OFA_research-poster

Jupyter Notebook
2
star
53

Finetune-miniLM-gallery

Python
1
star
54

lightning-aws

Python
1
star
55

Flash-Serve_component

LAI component for FlashServe
Python
1
star
56

AWS-s3_component

Lightning component to interact with s3.
Python
1
star
57

lightning-Galvatron

Python
1
star
58

Sample_component

Python
1
star
59

Youtube_component

Used to interface with youtube
Python
1
star
60

tgr

Python
1
star