Package: coreml
CoreMLcoremlis an end-to-end machine learning framework aimed at supporting rapid prototyping. It is built on top ofPyTorchLightningby combining the several components of any ML pipeline, right from definining the dataset object, choosing how to sample each batch, preprocessing your inputs and labels, iterating on different network architectures, applying various weight initializations, running pretrained models, freezing certain layers, changing optimizers, adding learning rate schedulers, and detailed logging, into a simplemodel.fit()framework, similar toscikit-learn. The codebase is very modular making it easily extensible for different tasks, modalities and training recipes, avoiding duplication wherever possible. The contents of the README are as follows:FeaturesSetupQuickstartHow-TosOptimizationNetwork architecturesDatasetsPreprocessingTestingTODOsAuthorsFeaturesSupport for end-to-end training usingPyTorchLightningwith custom training and validation loops.Makes every aspect of the training pipeline configurable.Data preprocessing on GPU usingkornia.Provides the ability to define and change architectures right in the config file.Built-in support for experiment tracking usingWeights & Biases.Enables replicability throughDockercontainers.Defines several new metrics likePrecisionAtRecall,SpecificityAtSensitivityandConfusionMatrix.Logs several classification curves likePRcurve,Sensitivity-Specificitycurve andROCcurve.Explicitly requires data versioning.Supports adding new datasets adhering to a required format.Contains unit tests wherever applicable.SetupClone the project:$gitclonehttps://github.com/dalmia/coreml.gitWeights & BiasesWe usewandbfor experiment tracking. You'll need to have that set up:Install wandb$pipinstallwandbLogin to wandb:$wandbloginYou will be redirected to a link that will show you yourWANDB_API_KEY.Set theWANDB_API_KEYby adding this to your~/.bashrcfile:exportWANDB_API_KEY=YOUR_API_KEYRunsource ~/.bashrc.During training, you'll have an option to turn offwandbas well.DockerWe use Docker containers to ensure replicability of experiments. You can either fetch the Docker image from DockerHub using the following line:$dockerpulladalmia/coreml:v1.0-lightningORYou can build the image using theDockerFile:$dockerbuild-tadalmia/coreml:v1.0-lightning.The repository runs inside a Docker container. When creating the container, you need to mount the directory containing data to/dataand directory where you want to store the ouptuts to/outputon the container. Make the corresponding changes tocreate_container.shto mount the respective directories by changing/path/to/coreml,/path/to/dataand/path/to/outputsto the appropriate values.Use the following command to launch a container:$bashcreate_container.shQuickstartCIFAR10Download and prepare the data$ python tasks/data/classification/CIFAR.pyThis will create a folder namedCIFAR10under the directory mounted at/dataon your container along with default data versions and the required directory structure.Since the codebase only supports binary classification for now, the step above also creates abinary.ymldata version which converts the 10-class problem into a binary classification problem.Run training using the default config:$ python training/train.py -v configs/defaults/binary-cifar-classification.ymlThetraining/train.pyadds a few more flags on top of the ones defined byTrainerfromPyTorchLightningYou can view all the flags that can be passed using-h:root@ip:/workspace/coreml# python training/train.py -h

usage: train.py [-h] [--logger [LOGGER]]
                [--checkpoint_callback [CHECKPOINT_CALLBACK]]
                [--early_stop_callback [EARLY_STOP_CALLBACK]]
                [--default_root_dir DEFAULT_ROOT_DIR]
                [--gradient_clip_val GRADIENT_CLIP_VAL]
                [--process_position PROCESS_POSITION] [--num_nodes NUM_NODES]
                [--num_processes NUM_PROCESSES] [--gpus GPUS]
                [--auto_select_gpus [AUTO_SELECT_GPUS]]
                [--tpu_cores TPU_CORES] [--log_gpu_memory LOG_GPU_MEMORY]
                [--progress_bar_refresh_rate PROGRESS_BAR_REFRESH_RATE]
                [--overfit_batches OVERFIT_BATCHES]
                [--track_grad_norm TRACK_GRAD_NORM]
                [--check_val_every_n_epoch CHECK_VAL_EVERY_N_EPOCH]
                [--fast_dev_run [FAST_DEV_RUN]]
                [--accumulate_grad_batches ACCUMULATE_GRAD_BATCHES]
                [--max_epochs MAX_EPOCHS] [--min_epochs MIN_EPOCHS]
                [--max_steps MAX_STEPS] [--min_steps MIN_STEPS]
                [--limit_train_batches LIMIT_TRAIN_BATCHES]
                [--limit_val_batches LIMIT_VAL_BATCHES]
                [--limit_test_batches LIMIT_TEST_BATCHES]
                [--val_check_interval VAL_CHECK_INTERVAL]
                [--log_save_interval LOG_SAVE_INTERVAL]
                [--row_log_interval ROW_LOG_INTERVAL]
                [--distributed_backend DISTRIBUTED_BACKEND]
                [--sync_batchnorm [SYNC_BATCHNORM]] [--precision PRECISION]
                [--weights_summary WEIGHTS_SUMMARY]
                [--weights_save_path WEIGHTS_SAVE_PATH]
                [--num_sanity_val_steps NUM_SANITY_VAL_STEPS]
                [--truncated_bptt_steps TRUNCATED_BPTT_STEPS]
                [--resume_from_checkpoint RESUME_FROM_CHECKPOINT]
                [--profiler [PROFILER]] [--benchmark [BENCHMARK]]
                [--deterministic [DETERMINISTIC]]
                [--reload_dataloaders_every_epoch [RELOAD_DATALOADERS_EVERY_EPOCH]]
                [--auto_lr_find [AUTO_LR_FIND]]
                [--replace_sampler_ddp [REPLACE_SAMPLER_DDP]]
                [--terminate_on_nan [TERMINATE_ON_NAN]]
                [--auto_scale_batch_size [AUTO_SCALE_BATCH_SIZE]]
                [--prepare_data_per_node [PREPARE_DATA_PER_NODE]]
                [--amp_backend AMP_BACKEND] [--amp_level AMP_LEVEL]
                [--val_percent_check VAL_PERCENT_CHECK]
                [--test_percent_check TEST_PERCENT_CHECK]
                [--train_percent_check TRAIN_PERCENT_CHECK]
                [--overfit_pct OVERFIT_PCT] -v VERSION [-n NUM_WORKERS]
                [--id ID] [--wandb] [--seed SEED]

Trains a model

optional arguments:
  -h, --help            show this help message and exit
  --logger [LOGGER]     autogenerated by pl.Trainer
  --checkpoint_callback [CHECKPOINT_CALLBACK]
                        autogenerated by pl.Trainer
  --early_stop_callback [EARLY_STOP_CALLBACK]
                        autogenerated by pl.Trainer
  --default_root_dir DEFAULT_ROOT_DIR
                        autogenerated by pl.Trainer
  --gradient_clip_val GRADIENT_CLIP_VAL
                        autogenerated by pl.Trainer
  --process_position PROCESS_POSITION
                        autogenerated by pl.Trainer
  --num_nodes NUM_NODES
                        autogenerated by pl.Trainer
  --num_processes NUM_PROCESSES
                        autogenerated by pl.Trainer
  --gpus GPUS           autogenerated by pl.Trainer
  --auto_select_gpus [AUTO_SELECT_GPUS]
                        autogenerated by pl.Trainer
  --tpu_cores TPU_CORES
                        autogenerated by pl.Trainer
  --log_gpu_memory LOG_GPU_MEMORY
                        autogenerated by pl.Trainer
  --progress_bar_refresh_rate PROGRESS_BAR_REFRESH_RATE
                        autogenerated by pl.Trainer
  --overfit_batches OVERFIT_BATCHES
                        autogenerated by pl.Trainer
  --track_grad_norm TRACK_GRAD_NORM
                        autogenerated by pl.Trainer
  --check_val_every_n_epoch CHECK_VAL_EVERY_N_EPOCH
                        autogenerated by pl.Trainer
  --fast_dev_run [FAST_DEV_RUN]
                        autogenerated by pl.Trainer
  --accumulate_grad_batches ACCUMULATE_GRAD_BATCHES
                        autogenerated by pl.Trainer
  --max_epochs MAX_EPOCHS
                        autogenerated by pl.Trainer
  --min_epochs MIN_EPOCHS
                        autogenerated by pl.Trainer
  --max_steps MAX_STEPS
                        autogenerated by pl.Trainer
  --min_steps MIN_STEPS
                        autogenerated by pl.Trainer
  --limit_train_batches LIMIT_TRAIN_BATCHES
                        autogenerated by pl.Trainer
  --limit_val_batches LIMIT_VAL_BATCHES
                        autogenerated by pl.Trainer
  --limit_test_batches LIMIT_TEST_BATCHES
                        autogenerated by pl.Trainer
  --val_check_interval VAL_CHECK_INTERVAL
                        autogenerated by pl.Trainer
  --log_save_interval LOG_SAVE_INTERVAL
                        autogenerated by pl.Trainer
  --row_log_interval ROW_LOG_INTERVAL
                        autogenerated by pl.Trainer
  --distributed_backend DISTRIBUTED_BACKEND
                        autogenerated by pl.Trainer
  --sync_batchnorm [SYNC_BATCHNORM]
                        autogenerated by pl.Trainer
  --precision PRECISION
                        autogenerated by pl.Trainer
  --weights_summary WEIGHTS_SUMMARY
                        autogenerated by pl.Trainer
  --weights_save_path WEIGHTS_SAVE_PATH
                        autogenerated by pl.Trainer
  --num_sanity_val_steps NUM_SANITY_VAL_STEPS
                        autogenerated by pl.Trainer
  --truncated_bptt_steps TRUNCATED_BPTT_STEPS
                        autogenerated by pl.Trainer
  --resume_from_checkpoint RESUME_FROM_CHECKPOINT
                        autogenerated by pl.Trainer
  --profiler [PROFILER]
                        autogenerated by pl.Trainer
  --benchmark [BENCHMARK]
                        autogenerated by pl.Trainer
  --deterministic [DETERMINISTIC]
                        autogenerated by pl.Trainer
  --reload_dataloaders_every_epoch [RELOAD_DATALOADERS_EVERY_EPOCH]
                        autogenerated by pl.Trainer
  --auto_lr_find [AUTO_LR_FIND]
                        autogenerated by pl.Trainer
  --replace_sampler_ddp [REPLACE_SAMPLER_DDP]
                        autogenerated by pl.Trainer
  --terminate_on_nan [TERMINATE_ON_NAN]
                        autogenerated by pl.Trainer
  --auto_scale_batch_size [AUTO_SCALE_BATCH_SIZE]
                        autogenerated by pl.Trainer
  --prepare_data_per_node [PREPARE_DATA_PER_NODE]
                        autogenerated by pl.Trainer
  --amp_backend AMP_BACKEND
                        autogenerated by pl.Trainer
  --amp_level AMP_LEVEL
                        autogenerated by pl.Trainer
  --val_percent_check VAL_PERCENT_CHECK
                        autogenerated by pl.Trainer
  --test_percent_check TEST_PERCENT_CHECK
                        autogenerated by pl.Trainer
  --train_percent_check TRAIN_PERCENT_CHECK
                        autogenerated by pl.Trainer
  --overfit_pct OVERFIT_PCT
                        autogenerated by pl.Trainer
  -v VERSION, --version VERSION
                        path to the experiment config file
  -n NUM_WORKERS, --num_workers NUM_WORKERS
                        number of CPU workers to use
  --id ID               experiment ID in wandb
  --wandb               whether to use wandb
  --seed SEED           seed for the experimentHow-TosThis section demonstrates the power of everything being parameterized by a config. Refer toconfigs/defaults/binary-cifar.ymlas the base config file on top of which we demonstrate the individual components.Optimizationoptimizer:name:SGDargs:lr:0.001momentum:0.9nesterov:truescheduler:name:StepLRinit_params:gamma:0.9step_size:1opt_params:interval:epochloss:train:name:binary-cross-entropyparams:reduction:noneval:name:binary-cross-entropyparams:reduction:nonetest:name:binary-cross-entropyparams:reduction:noneThe above example shows how to set various hyperparameters like the batch size, number of epochs, optimizer, learning rate scheduler and the loss function. The interesting aspect is how the optimizer, learning rate scheduler and the loss function is directly defined in the config file. This is possible because of theFactory Design Patternused throughout the codebase. Foroptimizer, we currently support:SGDAdamAdamWHowever, other optimization functions can be simply added by registering their corresponding builders incoreml/modules/optimization.py. For each optimizer,argscontains any parameters required by their correspondingPyTorchdefinition.Similarly, we support multiple learning rate schedulers defined inPyTorchalong parameterizing whether the scheduler's step should take place after each batch or after each epoch. This is controlled by the keyinterval, which can be one of['epoch', 'step']. The keymonitorcan be set to decide what parameter should be monitored for the scheduler's step. In the above example, the validationlossis being monitored. Currently, we suport the following schedulers:ReduceLROnPlateauStepLRCyclicLROneCycleLRMultiStepLRWe also parameterize the loss function to be used and allow for different loss functions for training and validation. The need for making them different could arise in various situations. One such example is applying label smoothing during training but not during validation.Network architecturesThe network architecture can be completely defined in the config itself:network:name:neural_netparams:config:-name:Conv2dparams:in_channels:3out_channels:64kernel_size:3-name:BatchNorm2dparams:num_features:64-name:ReLUparams:{}-name:Conv2dparams:in_channels:64out_channels:64kernel_size:3-name:BatchNorm2dparams:num_features:64-name:ReLUparams:{}-name:AdaptiveAvgPool2dparams:output_size:-1-1-name:Flattenparams:{}-name:Linearparams:in_features:64out_features:64-name:ReLUparams:{}-name:Linearparams:in_features:64out_features:1Theconfigkey takes as input a list of dictionaries, with each dictionary specifying a layer or a backbone network. Yes, if you want to use a pretrained ResNet, you can simply plug it in as a backbone layer:network:name:neural_netparams:config:-name:resnet50params:pretrained:truein_channels:3-name:AdaptiveAvgPool2dparams:output_size:-1-1-name:Flattenparams:{}-name:Linearparams:in_features:2048out_features:1Currently, we support a lot of backbones:Resnetvariations:resnet18,resnet34,resnet50,resnet101,resnet152,resnext50_32x4d,resnext101_32x8dVGGNetvariations:vgg11,vgg11_bn,vgg13,vgg13_bn,vgg16,vgg16_bn,vgg19_bn,vgg19EfficientNetvariations:efficientnet-b0,efficientnet-b4,efficientnet-b7The implementations for theResnetandVGGNetbased backbones have been taken fromtorchvision.modelsand those based onEfficientNetare supported bythisPyTorch implementation.Support for other backbones can be similarly added tocoreml/modules/backbone.DatasetsThe datasets to use can be specified as follows:dataset:name:classification_datasetconfig:-name:CIFAR10version:binaryparams:{}Here,nameis used to decide whichtorch.utils.data.Datasetobject to use, as defined incoreml/data/__init__.py.configtakes a list of dataset configs. Each dataset config is a dictionary withnameas the name of the dataset folder under/dataandversionbeing the specific dataset version to use, present in/data/{name}/processed/versions.paramscontains additional arguments that can be passed to the dataset object, as defined incoreml/data. When values are passed toparams, they are specified fortrain/val/testseparately:dataset:name:classification_datasetconfig:-name:CIFAR10versionparams:train:fraction:0.1val:fraction:0.5PreprocessingInput transformOne the input is loaded, the pipeline for processing the input before it is fed into a batch, can be specified in the config as:signal_transform:train:-name:Permuteparams:order:-2-0-1val:-name:Permuteparams:order:-2-0-1The pipeline for each split (train/val) is specified separately. For each split, a list of dictonaries are given. Each dictionary
represents one transform, as defined incoreml/data/transforms.py, using thenameof the transform and the arguments for that transform.Annotation transformThe raw annotations might have to be transformed before processing as well. This is specified in the config as:target_transform:name:classificationparams:classes:-0-1The specific target transform is selected fromannotation_factoryinsidecoreml/data/transforms.pyTestingWe useunittestfor all our tests. Simply run the following inside the Docker container:$ python -m unittest discover testsTODOsTracking inputs on W&B (currentlytorch.catkills the process when the inputs are large).Add augmentationsLabel Smoothing for BCEIncorporate models fromtimm(pytorch-image-models)Training with TPUsTraining with multiple GPUsNative TTAStochastic Weight AveragingDemos for various thingsSupport for audio classificationClassification analyzer (similar to fast.ai)Discriminative fine-tuning (seethis)Add benchmarks for multiple datasetsAdd documentation for using new datasets and configuring different parts of the pipelineAuthorsAman DalmiaPiyush Bagad