Package: csc-mlops
A continuous integration and deployment framework for healthcare AI projectsView on PyPI »View repo·Report Bug·Request FeatureOverviewThis project aims to build an effective MLOps framework for the development of AI models in a healthcare setting. The application development framework has three major components:1. MLOps serverThe MLOps server hosts the ML lifecycle management services. An MLFlow instance serves as the management platform, providing experiment tracking and model serving.2. Project TemplateTheproject templateis the starting point for any project using this development framework. This template is flexible enough for any projects and facilitates communication with other parts of the development framework. The figure below illustrates a high level overview of the template and supporting components provided by the MLOps server.3. csc-mlops packageThe csc-mlops python package is available onPyPIand installed by default by theproject template. This package handles communication between the project and the server, performs automated tasks, and includes helper functions and classes to streamline development.These components work together to simplify and automate many of the processes required for controlled app development. A high level schematic of the framework is illustrated below. In this case XNAT is used as a data archive platform, the framework can be adapted to use other data stores.This repository contains the source code for the server and csc-mlops components of the development framework. For further details on the project template component see theproject template repository.Guiding PrinciplesThis is an open source project and all contributions are welcome. Please see thecontribution guidelines.The MLOps serverServer componentsMLFlowOpen source platform to manage the ML lifecycleMINIOHigh performance object storage suiteNGINXReverse proxy serverIt's not essential to have a complete understanding of all of these, but a high-level understanding ofMLFlowin particular will be useful!Getting StartedThe production version of this project is intended to run on a dedicated remote machine on an isolated network. This documentation will often describe the MLOps server, development machine and runner as separate machines, but there is no reason these cannot be the same machine if the network locations point to the localhost.PrerequisitesFirst follow the instructions to installDockeranddocker-compose.Check docker and docker-compose are working by calling passing the help argument on the command line. If the help information is not returned, or an error is given, revisit the docker installation docs.docker--help
docker-compose--helpSetting up the MLOps serverClone and enter the repositorygitclonehttps://github.com/GSTT-CSC/MLOps.gitcdMLOpsThe server should be configured by creating an environment file at/mlflow_server/.env. The environment variable shown are given as an example, and should not be used for a production deployment.Setting these variables is a requirement, the server will fail to start if they are undefined.Please do not use shown values. Consider Writing you own usernames and passwords.# Example env file - fill all required values before usingAWS_ACCESS_KEY_ID=minioUsernameAWS_SECRET_ACCESS_KEY=minioPasswordMLFLOW_S3_IGNORE_TLS=truePOSTGRES_USER=usePOSTGRES_PASSWORD=passPOSTGRES_DB=dbNavigate to the mlflow_server directory and start the service. Any docker images that are not present on your local system will be pulled from dockerhub (which might take a while).cdmlflow_serverdocker-composeup-d--buildTo enable access to the minio artifact storage the host machine needs to be authenticated. Any of the methods supported by boto3 should be compatible, the recommended authentication method is to create anaws credentials file. e.g. for ubuntu/linux[credentials]
AWS_ACCESS_KEY_ID=minioUsername
AWS_SECRET_ACCESS_KEY=minioPasswordUpon a successful build the server should now be up and running locally. By default, the mlflow user interface can be accessed athttp:/localhost:85and minio can be accessed athttps:/localhost:8002.To check if the server is up and running successfully runningdocker psin the terminal lists the running containers, and we should see something like:CONTAINER ID   IMAGE                                      COMMAND                  CREATED             STATUS                       PORTS                                        NAMES
3d51a7580b6f   mlflow_nginx                               "nginx -g 'daemon of…"   About an hour ago   Up About an hour             0.0.0.0:80->80/tcp, 0.0.0.0:8002->8002/tcp   mlflow_nginx
1baa8ff12814   mlflow_app                                 "mlflow server --bac…"   About an hour ago   Up About an hour             5000/tcp                                     mlflow_server
a397b4149c5f   minio/minio:RELEASE.2021-03-17T02-33-02Z   "/usr/bin/docker-ent…"   About an hour ago   Up About an hour (healthy)   9000/tcp, 9002/tcp                           mlflow_server_s3_1
65374369fe4d   postgres:13.1                              "/docker-entrypoint.…"   About an hour ago   Up About an hour (healthy)   5432/tcp,                                    mlflow_dbServer components overviewWhen we randocker-compose upwe started 4 networked containers, each of which serves a purpose within the MLOps framework.NGINX: The nginx container acts as a reverse proxy to control network traffic.MLflow: The MLflow container hosts our MLflow server instance. This server is responsible for tracking and logging the MLOps events sent to it.MINIO: The MINIO container hosts our MINIO server. Here we are using MINIO as a self hosted S3 storage location. The MLflow container interfaces well with S3 storage locations for logging artifacts (models, images, plots etc)postgres: The database server container is visible only to the MLflow container, which logs MLflow entities to the postgres database hosted on this container. MLFlow entities should not be confused with artifacts (stored on MINIO), and are simple values such as metrics, parameters and configuration options which can be efficiently stored in a database.There are twobridge networkswhich connect these containers, named 'frontend' and 'backend'. The backend is used for communication between containers and is not accessible from the host (or remote), the frontend is accesible from the host (or remote) through the NGINX reverse proxy. NGINX will act as our gatekeeper and all requests will pass through it. This enables us to take advantage of NGINX load balancing and authentication in production versions.Experiment tracking with MLflowMLflow is a framework for managing the full lifecycle of AI models. It contains tools to cover each stage of AI model lifecycle it contains 4 major component Tracking, Projects, Models, and a Model Registry. The endpoint for these tools is an MLflow server that cun run on local or remote hardware and handles all aspects of the lifecycle.Currently, we will focus primarily on the tracking and projects components.Tracking refers to tools used to track experiments to record and compare parameters and results. This is done by adding logging snippets to the ML code to record things like hyper-parameters, metrics and artifacts. These entities are then associated with a particular run with a specific git commit. This git commit points to a specific version of the project files. This means that by using MLflow tracking we are able to identifiy the code used to train an AI model and make comparisons following changes to code structure and hyperparameter choices.MLflow uses projects to encapsulate AI tools in a reusable and reproducible way, based primarily on conventions. It also enables us to chain together project workflows meaning we are able to automate a great deal of the model development process.csc-mlops packageThe csc-mlops package can be installed using pip:pip install csc-mlopsExperimentTheExperimentclass is the primary interface between the developers project code and the MLOps  processes. By usingExperimenta number of important processes are automated:Project configuration and registrationCommunication with the MLOps serverEnsures all project code is committed and current with repositoryDocker image built if it can't be found locallyProject logger configuredTo use the Experiment class the project must be run using a syntax such as:frommlops.ExperimentimportExperimentconfig_path='config/config.cfg'exp=Experiment(config_path=config_path)exp.run(docker_args={},entry_point='main')When using theproject templatethis process is performed when executing therun_project.pyscript.For more information on how to define the project configuration using a config.cfg file see theproject templatedocumentationXNAT data handlerAccessing data stored in an XNAT archive is performed through two steps - first the XNAT database is queried for project subjects using the csc-mlops DataBuilderXNAT feature. This list of results is then loaded using the pytorch style data loading transform LoadImageXNATd.1. Create list of data samplesA list of subjects is extracted from the XNAT archive for the specified project. This is done automatically by the helper functionxnat_build_dataset.frommlops.data.tools.toolsimportxnat_build_datasetPROJECT_ID='my_project'xnat_configuration={'server':XNAT_LOCATION,'user':XNAT_USER,'password':XNAT_USER_PASSWORD,'project':XNAT_PROJECT_ID}xnat_data_list=xnat_build_dataset(self.xnat_configuration)Each element in the listxnat_data_listis a dictionary with two keys, Where these fields indicated unique references to each subject.{
    'subject_id': <subject_id>,
    'subject_uri': <subject_uri>
}2. Download relevant data using LoadImageXNATd and actionsA MONAI transformLoadImageXNATdis used to download the data from XNAT, this transform can be used in place of the conventionalLoadImagedtransform provided by MONAI to access local data.A worked example is given below to create a valid dataloader containing the sag_t2_tse scans from XNAT where each subject has two experiments
This first thing that is required is an action function. This is a function that operates on an XNAT SubjectData object and returns the desired ImageScanData object from the archive and the key under which is will be stored in the dataset. For example the function below will extract the 'sag_t2_tse' scans from the archive.deffetch_sag_t2_tse(subject_data:SubjectData=None)->(ImageScanData,str):"""Function that identifies and returns the required xnat ImageData object from a xnat SubjectData objectalong with the 'key' that it will be used to access it."""forexpinsubject_data.experiments:if'MR_2'insubject_data.experiments[exp].label:forscaninsubject_data.experiments[exp].scans:if'sag_t2_tse'insubject_data.experiments[exp].scans[scan].series_description:returnsubject_data.experiments[exp].scans[scan],'sag_t2_tse'In this example, thefetch_sag_t2_tsefunction will loop over all experiments available for the subject, then if one of these experiments has 'MR_2' in the label it will loop over all the scans in this experiment until it finds one with 'sag_t2_tse' in the series_description. The URI to this scan is then extracted and returned along with the key it will be stored under in the data dictionary, in this case 'sag_t2_tse'.We can now pass this action function to theLoadImageXNATdtransform. When passing a list of action functions to theLoadImageXNATdtransform each action function in the list will be performed sequentially. So if multiple datasets are required for each Subject then multiple functions can be used.frommlops.data.transforms.LoadImageXNATdimportLoadImageXNATdfrommonai.transformsimportCompose,ToTensordfromtorch.utils.dataimportDataLoaderfrommonai.dataimportCacheDatasetfromxnat.mixinimportImageScanData,SubjectDatafrommonai.data.utilsimportlist_data_collate# list of actions to be applied sequentiallyactions=[fetch_sag_t2_tse]train_transforms=Compose([LoadImageXNATd(keys=['subject_uri'],actions=actions,xnat_configuration=xnat_configuration),ToTensord(keys=['sag_t2_tse'])])dataset=CacheDataset(data=xnat_data_list,transform=train_transforms)data_loader=DataLoader(dataset,batch_size=1,shuffle=True,num_workers=0,collate_fn=list_data_collate)If further transforms are required they can be added to theComposetransform list as usual.Additional ToolsAdditional tools designed to be used with MLOps are located in thetoolsfolder.Data toolkitTools for collecting information about large data stores.RoadmapSee theopen issuesfor a list of proposed features (and known issues).ContributingFork or clone the ProjectSince all code changes are staged on thedevelopbranch before releases you will need to checkout this branch first (git checkout -b develop)Create your Feature Branch off ofdevelop(git checkout -b feature/AmazingFeature)Commit your Changes (git commit -m 'Add some AmazingFeature')Push to the remote (git push origin feature/AmazingFeature)Open a Pull Request and specify that you want to merge your feature branch into thedevelopbranchTestingWhen contributing, you arestronglyencouraged to write tests for any functions or classes you add. Please uses pytest and add your tests to an appropriate location in thetestsdirectory, which also contains some examples to get you started.AcknowledgementsREADME template by othneildrew