diff --git a/.gitattributes b/.gitattributes index fef20c0ab801b53e6ead6d6683d5a1230e2a906a..3906dd2262419d0695f82f70890adbf8f6624251 100644 --- a/.gitattributes +++ b/.gitattributes @@ -126,3 +126,4 @@ docker/intel_code/llama13b/Model-References/PyTorch/nlp/DeepSpeedExamples/Megatr docker/intel_code/llama13b/Model-References/PyTorch/nlp/DeepSpeedExamples/Megatron-DeepSpeed_old/wandb/run-20240424_103821-kdru3pwo/logs/debug-internal.log filter=lfs diff=lfs merge=lfs -text docker/intel_code/llama13b/Model-References/PyTorch/examples/computer_vision/data/MNIST/raw/t10k-images-idx3-ubyte filter=lfs diff=lfs merge=lfs -text docker/intel_code/llama13b/Model-References/PyTorch/examples/computer_vision/data/MNIST/raw/train-images-idx3-ubyte filter=lfs diff=lfs merge=lfs -text +utilities/l3-routes filter=lfs diff=lfs merge=lfs -text diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/.gitignore b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c75dc7c3dfd3d4c20ba9848d5abf189b26b0f4e7 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/.gitignore @@ -0,0 +1 @@ +logs/* diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/5-cross-validation.sh b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/5-cross-validation.sh new file mode 100644 index 0000000000000000000000000000000000000000..1b4ddfbd03e92c8e6335e138bd60d602a90faa99 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/5-cross-validation.sh @@ -0,0 +1,14 @@ +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# +# This script runs 5-fold cross-validation of UNet3D topology for 16000 iterations on single HLS +# Usage: +# bash 5-cross-validation.sh +mpirun --allow-run-as-root --bind-to core --map-by socket:PE=6 --np 8 $PYTHON main.py --use_horovod --data_dir $1 --model_dir $2/fold_0 --log_dir $2/fold_0 --batch_size $3 --dtype $4 --fold 0 --tensorboard_logging --log_all_workers > $2/result_$4_fold0.log +mpirun --allow-run-as-root --bind-to core --map-by socket:PE=6 --np 8 $PYTHON main.py --use_horovod --data_dir $1 --model_dir $2/fold_1 --log_dir $2/fold_1 --batch_size $3 --dtype $4 --fold 1 --tensorboard_logging --log_all_workers > $2/result_$4_fold1.log +mpirun --allow-run-as-root --bind-to core --map-by socket:PE=6 --np 8 $PYTHON main.py --use_horovod --data_dir $1 --model_dir $2/fold_2 --log_dir $2/fold_2 --batch_size $3 --dtype $4 --fold 2 --tensorboard_logging --log_all_workers > $2/result_$4_fold2.log +mpirun --allow-run-as-root --bind-to core --map-by socket:PE=6 --np 8 $PYTHON main.py --use_horovod --data_dir $1 --model_dir $2/fold_3 --log_dir $2/fold_3 --batch_size $3 --dtype $4 --fold 3 --tensorboard_logging --log_all_workers > $2/result_$4_fold3.log +mpirun --allow-run-as-root --bind-to core --map-by socket:PE=6 --np 8 $PYTHON main.py --use_horovod --data_dir $1 --model_dir $2/fold_4 --log_dir $2/fold_4 --batch_size $3 --dtype $4 --fold 4 --tensorboard_logging --log_all_workers > $2/result_$4_fold4.log + +$PYTHON runtime/parse_results.py --model_dir $2 --env result_$4 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/LICENSE b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..fb9ed3577fd6f2d97e52e06a8fc80fd50ea1cc69 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/LICENSE @@ -0,0 +1,203 @@ +Copyright (c) 2021 Habana Labs, Ltd. an Intel Company + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/README.md b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f4070e1e5961671f4a0498454d47f75cc873cb12 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/README.md @@ -0,0 +1,316 @@ +# UNet3D for TensorFlow 2 + +This directory provides a script and recipe to train a 3D-UNet medical image segmentation model for TensorFlow 2.x to achieve state of the art accuracy, and is tested and maintained by Habana. For further information on performance, refer to [Habana Model Performance Data page](https://developer.habana.ai/resources/habana-training-models/#performance). + +For further information on training deep learning models using Gaudi, refer to [developer.habana.ai](https://developer.habana.ai/resources/). + +## Table of Contents + +* [Model-References](../../../README.md) +* [Model overview](#model-overview) +* [Setup](#setup) +* [Training and Examples](#training-and-examples) +* [Advanced](#advanced) +* [Supported Configuration](#supported-configuration) +* [Changelog](#changelog) + +## Model Overview + +The U-Net model is a convolutional neural network for 3D image segmentation. This repository contains a UNet3D implementation introduced in [3D U-Net: Learning Dense Volumetric Segmentation from Sparse Annotation](https://arxiv.org/pdf/1606.06650), with modifications described in [No New-Net](https://arxiv.org/pdf/1809.10483). It is based on [UNet3D Medical Image Segmentation for TensorFlow 1.x](https://github.com/NVIDIA/DeepLearningExamples/tree/master/TensorFlow/Segmentation/UNet_3D_Medical) repository. + +### Model Architecture + +UNet3D was first introduced by Olaf Ronneberger, Philip Fischer and Thomas Brox in [UNet3D Learning Dense Volumetric Segmentation from Sparse Annotation](https://arxiv.org/pdf/1606.06650). In this repository we host a UNet3D version adapted by Fabian Isensee et al. to brain tumor segmentation. UNet3D allows for seamless segmentation of 3D volumes, with high accuracy and performance, and can be adapted to solve many different segmentation problems. + +The following figure shows the construction of the UNet3D model and its different components. UNet3D is composed of a contractive and an expanding path, that aims at building a bottleneck in its centermost part through a combination of convolution and pooling operations. After this bottleneck, the image is reconstructed through a combination of convolutions and upsampling. Skip connections are added with the goal of helping the backward flow of gradients in order to improve the training. + +![U-Net3D](images/unet3d.png) + +UNet3D consists of a contractive (left-side) and expanding (right-side) path. It repeatedly applies un-padded convolutions followed by max pooling for downsampling. Every step in the expanding path consists of an upsampling of the feature maps and a concatenation with the correspondingly cropped feature map from the contractive path. + +### Model Changes + +The following are the major changes that were implemented to the original model from [UNet3D Medical Image Segmentation for TensorFlow 1.x](https://github.com/NVIDIA/DeepLearningExamples/tree/master/TensorFlow/Segmentation/UNet_3D_Medical): + +* Changed some scripts to run the model on Gaudi. This includes loading habana tensorflow modules. +* Converted all the scripts to Tensorflow 2.x version. +* Added support for using bfloat16 precision instead of float16. +* Added further TensorBoard and performance logging options. +* Removed GPU specific files (examples/*, Dockerfile etc.) and some unused codes. +* Added further synthetic data and tensor dumping options. +* Enabled the tf.data.experimental.prefetch_to_device for HPU device to improve performance. + +### Default Configuration + +- Execution mode: train and evaluate +- Batch size: 2 +- Data type: bfloat16 +- Maximum number of steps: 16000 +- Learning rate: 0.0002 +- Loss: dice+ce +- Normalization block: instancenorm +- Include background in predictions and labels: False +- Number of Horovod workers (HPUs): 1 +- Data augmentation: True +- Using XLA: True +- Resume training from checkpoint: False +- Logging losses and performance every N steps: 100 +- Tensorboard logging: False +- Logging data from every worker: False + +## Setup + +Please follow the instructions provided in the [Gaudi Installation Guide](https://docs.habana.ai/en/latest/Installation_Guide/GAUDI_Installation_Guide.html) to set up the environment including the `$PYTHON` environment variable. To achieve the best performance, please follow the methods outlined in the [Optimizing Training Platform guide](https://docs.habana.ai/en/latest/TensorFlow/Model_Optimization_TensorFlow/Optimization_Training_Platform.html). +The guides will walk you through the process of setting up your system to run the model on Gaudi. + +### Clone Habana Model-References + +In the docker container, clone this repository and switch to the branch that matches your SynapseAI version. You can run the [`hl-smi`](https://docs.habana.ai/en/latest/Management_and_Monitoring/System_Management_Tools_Guide/System_Management_Tools.html#hl-smi-utility-options) utility to determine the SynapseAI version. + +```bash +git clone https://github.com/HabanaAI/Model-References /root/Model-References +cd /root/Model-References/TensorFlow/computer_vision/UNet3D +``` + +**Note:** If Model-References repository path is not in the PYTHONPATH, make sure you update it: +```bash +export PYTHONPATH=$PYTHONPATH:/root/Model-References +``` + +### Download and Pre-process the Dataset + +1. To obtain the dataset, register on [Brain Tumor Segmentation 2019 dataset](https://www.med.upenn.edu/cbica/brats-2019/) website. The data should be downloaded and placed where `/dataset` in the container is mounted. The `dataset/preprocess_data.py` script will convert the raw data into tfrecord format used for training and evaluation. + +2. To launch the script, run: + +```bash +$PYTHON dataset/preprocess_data.py -i /dataset -o /dataset_preprocessed -v +``` + +### Install Model Requirements + +1. In the docker container, go to the UNet3D directory: + +```bash +cd /root/Model-References/TensorFlow/computer_vision/UNet3D +``` + +2. Install the required packages using pip: + +```bash +$PYTHON -m pip install -r requirements.txt +``` + +## Training and Examples + +### Single Card and Multi-Card Training Examples + +**Run training on 1 HPU:** + +```bash +$PYTHON main.py --data_dir --dtype --model_dir --log_dir --tensorboard_logging +``` + +Run training on 1 HPU with batch size 2, bfloat16 precision and fold 0: + +```bash +$PYTHON main.py --data_dir /dataset_preprocessed --dtype bf16 --model_dir /tmp/unet3d_1_hpu --log_dir /tmp/unet3d_1_hpu --tensorboard_logging +``` + +**Run training on 8 HPUs:** + +**NOTE:** mpirun map-by PE attribute value may vary on your setup. For the recommended calculation, refer to the instructions detailed in [mpirun Configuration](https://docs.habana.ai/en/latest/TensorFlow/Tensorflow_Scaling_Guide/Horovod_Scaling/index.html#mpirun-configuration). + +Run training on 8 HPUs via mpirun with batch size 2, bfloat16 precision and fold 0: + +```bash +mpirun --allow-run-as-root --bind-to core --map-by socket:PE=6 --np 8 \ +$PYTHON main.py --use_horovod --data_dir /dataset_preprocessed --dtype bf16 --model_dir /tmp/unet3d_8_hpus --log_dir /tmp/unet3d_8_hpus --tensorboard_logging --log_all_workers +``` +**Run 5-fold Cross-Validation and compute average dice score:** + +All the commands described above will train and evaluate the model on the dataset with fold 0. To perform 5-fold-cross-validation on the dataset and compute average dice score across 5 folds, the user can execute training script 5 times and calculate the average dice score manually or run bash script `5-cross-validation.sh`: + +```bash +bash 5-cross-validation.sh +``` + +Run training on 8 HPUs 5-fold-cross-validation with batch size 2 and bfloat16 precision: + +```bash +bash 5-cross-validation.sh /dataset_preprocessed /tmp/unet3d_8_hpus 2 bf16 +``` +## Advanced + +The following sections provide further details on the dataset, running training and inference, and the training results. + +### Scripts and Sample Code + +In the root directory, the most important files are: +* `main.py`: Serves as the entry point to the application. Encapsulates the training routine. +* `requirements.txt`: Set of extra requirements for running U-Net. + +The `dataset/` folder contains the necessary tools to train and perform inference using U-Net. Its main components are: +* `data_loader.py`: Implements the data loading and augmentation. +* `transforms.py`: Implements the data augmentation functions. +* `preprocess_data.py`: Implements the data conversion and pre-processing functionality. + +The `runtime/` folder contains scripts with training and inference logic. Its contents are: +* `arguments.py`: Implements the command-line arguments parsing. +* `hooks.py`: Collects different metrics to be used for benchmarking and testing. +* `parse_results.py`: Defines a set of functions used for parsing the partial results. +* `setup.py`: Defines a set of functions to set the environment up. + + The `model/` folder contains information about the building blocks of UNet3D and the way they are assembled. Its contents are: +* `layers.py`: Defines the different blocks that are used to assemble UNet3D. +* `losses.py`: Defines the different losses used during training and evaluation. +* `model_fn.py`: Defines the computational graph to optimize. +* `unet3d.py`: Defines the model architecture using the blocks from the `layers.py` file. + +Other folders included in the root directory are: +* `images/`: Contains the model diagram + +### Parameters + +The complete list of the available parameters for the `main.py` script contains the following: +* `--exec_mode`: Select the execution mode to run the model (default: `train_and_evaluate`). The available modes: + * `train` - Trains the model and stores checkpoints in the directory passed using `--model_dir` + * `evaluate` - Loads the checkpoint (if available) and performs evaluation on validation subset (requires `--fold` other than `None`). + * `train_and_evaluate` - Trains the model from scratch and performs validation at the end (requires `--fold` other than `None`). + * `predict` - Loads the checkpoint (if available) and runs inference on the test set. Stores the results in the `--model_dir` directory. + * `train_and_predict` - Trains the model from scratch and performs inference. +* `--model_dir`: Set the output directory for information related to the model. +* `--log_dir`: Set the output directory for logs (default: `/tmp/unet3d_logs`). +* `--data_dir`: Set the input directory containing the preprocessed dataset. +* `--batch_size`: Size of each minibatch per device (default: `2`). +* `--dtype`: Set precision to be used in model on HPU: fp32/bf16 (default: `bf16`). +* `--bf16_config_path`: Path to custom mixed precision config to be used (default: `./bf16_config/unet.json`). +* `--fold`: Selected fold for cross-validation (default: `0`). +* `--num_folds`: Number of folds in k-cross-validation of dataset (default: `5`). +* `--max_steps`: Maximum number of steps (batches) for training (default: `16000`). +* `--seed`: Set random seed for reproducibility (default: `None`). +* `--log_every`: Log performance every n steps (default: `100`). +* `--learning_rate`: Model’s learning rate (default: `0.0002`). +* `--loss`: Loss function to be used during training (default: `dice+ce`). +* `--normalization`: Normalization block to be applied in the model (default: `instancenorm`). +* `--include_background`: Include background both in preditions and labels (default: `False`). +* `--no-augment`: Disable data augmentation (enabled by default). +* `--benchmark`: Enable performance benchmarking (disabled by default). If the flag is set, the script runs in a benchmark mode - each iteration is timed and the performance result (in images per second) is printed at the end. Works for both `train` and `predict` execution modes. +* `--warmup_steps`: Used during benchmarking - the number of steps to skip (default: `40`). First iterations are usually much slower since the graph is being constructed. Skipping the initial iterations is required for a fair performance assessment. +* `--resume_training`: Whether to resume training from a checkpoint, if there is one (disabled by default). +* `--no_xla`: Disable accelerated linear algebra optimization (enabled by default). +* `--use_amp`: Enable automatic mixed precision for GPU (disabled by default). +* `--no_hpu`: Disable execution on HPU, train on CPU/GPU (default: `False`). +* `--dump_config`: Directory for dumping debug traces (default: `None`). +* `--synth_data`: Use deterministic and synthetic data (default: `False`). +* `--disable_ckpt_saving`: Disables saving checkpoints (default: `False`). +* `--use_horovod`: Enable horovod usage (default: `False`). +* `--tensorboard_logging`: Enable tensorboard logging (default: `False`). +* `--log_all_workers`: Enable logging data for every horovod worker in a separate directory named `worker_N` (default: `False`). + +### Command Line Options + +To see the full list of the available options and their descriptions, use the `-h` or `--help` command-line option, for example: + +```bash +$PYTHON main.py --help +``` + +### Dataset Description + +The UNet3D model was trained in the [Brain Tumor Segmentation 2019 dataset](https://www.med.upenn.edu/cbica/brats-2019/). Test images provided by the organization were used to produce the resulting masks for submission. Upon registration, the challenge's data is made available through the https//ipp.cbica.upenn.edu service. + +The dataset consists of 335 240x240x155 `nifti` volumes. Each volume is represented by 4 modalities and a corresponding segmentation mask. +The following lists the modalities: +* Native T1-weighted (T1), +* Post-contrast T1-weighted (T1Gd), +* Native T2-weighted (T2), +* T2 Fluid Attenuated Inversion Recovery (FLAIR). + +Each voxel in a segmentation mask belongs to one of four classes: +* 0 corresponds to healthy tissue or background, +* 1 indicates the presence of the necrotic and non-enhancing tumor core (TC), +* 2 indicates the presence of the peritumoral edema (ED), +* 4 indicates the presence of the GD-enhancing tumor (ET). + +The objective is to produce a set of masks that segment the data as accurately as possible. The results are expected to be submitted as a 12-bit `nifti` 3D image, with values corresponding to the underlying class. + +### Dataset Guidelines + +The training and test datasets are given as 3D `nifti` volumes that can be read using the Nibabel library and NumPy. + +Initially, all modalities are loaded, stacked and converted into 240x240x155x4 NumPy arrays using Nibabel. To decrease the size of the dataset, each volume is clipped to 85% of the maximal value, normalized to 255 for each modality separately, casted to 8-bit, grouped by 4 volumes, and saved as a `tfrecord` file. The process of converting from `nifti` to `tfrecord` can be found in the `preprocess_data.py` script. + +The `tfrecord` files are fed to the model through `tf.data.TFRecordDataset()` to achieve high performance. + +The foreground voxel intensities then z-score normalized, whereas labels are one-hot encoded for their later use in dice or pixel-wise cross-entropy loss, becoming 240x240x155x4 tensors. + +If the augmentation is enabled, the following set of augmentation techniques are applied: +* Random horizontal flipping +* Random 128x128x128x4 crop +* Random brightness shifting + +In addition, random vertical flip and random gamma correction augmentations were implemented, but are not used. The process of loading, normalizing and augmenting the data contained in the dataset can be found in the `data_loader.py` script. + +#### Multi-dataset + +This implementation is tuned for the Brain Tumor Segmentation 2019 dataset. Using other datasets is possible, but might require changes to the code (data loader) and tuning some hyperparameters (e.g. learning rate, number of iterations). + +In the current implementation, the data loader works with tfrecord files. It should work seamlessly with any dataset containing 3D data stored in tfrecord format, as long as features (with corresponding mean and standard deviation) and labels are stored as bytestream in the same file as `X`, `Y`, `mean`, and `stdev`. See the data pre-processing script for details. If your data is stored in a different format, you will have to modify the parsing function in the `dataset/data_loader.py` file. For a walk-through, check the [TensorFlow tf.data API guide](https://www.tensorflow.org/guide/data_performance) + +### Training Process + +The model trains for a total 16,000 (16,000 / number of devices) iterations for each fold, with the default UNet3D setup: +* Adam optimizer with learning rate of 0.0002. +* Training and evaluation batch size of 2. + +The default configuration minimizes a function _L = 1 - DICE + cross entropy_ during training and reports achieved convergence as dice score per class, mean dice score, and dice score for whole tumor vs background. The training with a combination of dice and cross entropy has been proven to achieve better convergence than a training using only dice. + +If the `--exec_mode train_and_evaluate` parameter was used, and if `--fold` parameter is set to an integer value of {0, 1, 2, 3, 4}, the evaluation of the validation set takes place after the training is completed. The results of the evaluation will be printed to the console. + +### Inference Process + +Inference can be launched with the same script used for training by passing the `--exec_mode predict` flag: + +```bash +$PYTHON main.py --exec_mode predict --data_dir --model_dir [other parameters] +``` + +The script will then perform the following: +* Load the checkpoint from the directory specified by the `` directory. +* Run inference on the test dataset. +* Save the resulting masks in the `numpy` format in the `--model_dir` directory. + +## Supported Configuration + +| Validated on | SynapseAI Version | TensorFlow Version(s) | Mode | +|:------:|:-----------------:|:-----:|:----------:| +| Gaudi | 1.14.0 | 2.15.0 | Training | +| Gaudi2 | 1.14.0 | 2.15.0 | Training | + +## Changelog + +### 1.7.0 + +* Added TimeToTrain callback for dumping evaluation times + +### 1.6.0 + +* Model enabled on Gaudi2, with the same config as first-gen Gaudi. + +### 1.5.0 + +* Stopped overriding model_dir path with additional `model_checkpoint` directory. + +### 1.4.0 + +* Enabled tf.data.experimental.prefetch_to_device for HPU device to improve the model performance. +* Changed `python` or `python3` to `$PYTHON` to execute correct version based on environment setup. +* Replaced references to custom demo script by community entry points in README and `5-cross-validation.sh`. +* Added support to import horovod-fork package directly instead of using Model-References' TensorFlow.common.horovod_helpers. + +### 1.3.0 +* Moved BF16 config json file from TensorFlow/common/ to model's directory. + + + diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/bf16_config/unet.json b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/bf16_config/unet.json new file mode 100644 index 0000000000000000000000000000000000000000..46e81b0acfe7f97ecb390e16a2817dec8137e25e --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/bf16_config/unet.json @@ -0,0 +1,85 @@ +{ + "allowlist": [ + "BatchMatMul", + "BatchMatMulV2", + "BiasAdd", + "BiasAddGrad", + "Conv2D", + "Conv2DBackpropFilter", + "Conv2DBackpropInput", + "Conv3D", + "Conv3DBackpropFilter", + "Conv3DBackpropFilterV2", + "Conv3DBackpropInput", + "Conv3DBackpropInputV2", + "HabanaConv2DWithPadding", + "HabanaConv2DWithPaddingBackpropFilter", + "HabanaConv2DWithPaddingBackpropInput", + "HabanaInstanceNorm", + "HabanaInstanceNormGrad", + "LeakyRelu", + "LeakyReluGrad", + "MatMul", + "MaxPool", + "MaxPoolV2", + "MaxPoolGrad", + "MaxPoolGradV2", + "Relu", + "ReluGrad" + ], + "conditional_list": [ + "Add", + "AddN", + "AddV2", + "CollectiveReduceV2", + "CollectiveReduceV3", + "Concat", + "ConcatV2", + "Equal", + "Exp", + "GreaterEqual", + "HabanaClampBwd", + "HabanaClampFwd", + "HabanaDropout", + "HabanaDropoutGrad", + "HorovodAllgather", + "HorovodAllreduce", + "HpuCollectiveGather", + "HpuCollectiveGatherV2", + "HpuCollectiveReduce", + "Identity", + "Log1p", + "L2Loss", + "Max", + "Mean", + "Mul", + "Neg", + "Pad", + "PadV2", + "Pow", + "RealDiv", + "Reciprocal", + "Reshape", + "ResizeNearestNeighbor", + "ResizeNearestNeighborGrad", + "Select", + "Shape", + "ShapeN", + "Slice", + "Square", + "Tile" + ], + "strict_conditional_list": [], + "non_convertible_exceptions": [ + [ + ".*KEEP_FP32_PRECISION.*", + "" + ] + ], + "convertible_exceptions": [ + [ + ".*FORCE_BF16_PRECISION.*", + "" + ] + ] +} \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/data_loader.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b46650a546571db2f749b5422d5f05238e5399 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/data_loader.py @@ -0,0 +1,234 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - script migration to Tensorflow 2.x version +# - main function and unused imports have been removed +# - updated synth_train_fn function for stable CPU and HPU results +# - enabled experimental.prefetch_to_device functionality to improve the performance + +import os + +import numpy as np +import tensorflow as tf + +from dataset.transforms import NormalizeImages, OneHotLabels, apply_transforms, PadXYZ, RandomCrop3D, \ + RandomHorizontalFlip, RandomBrightnessCorrection, CenterCrop, apply_test_transforms, Cast + +CLASSES = {0: "TumorCore", 1: "PeritumoralEdema", 2: "EnhancingTumor"} + + +def cross_validation(x: np.ndarray, fold_idx: int, n_folds: int): + if fold_idx < 0 or fold_idx >= n_folds: + raise ValueError('Fold index has to be [0, n_folds). Received index {} for {} folds'.format(fold_idx, n_folds)) + + _folders = np.array_split(x, n_folds) + + return np.concatenate(_folders[:fold_idx] + _folders[fold_idx + 1:]), _folders[fold_idx] + + +class Dataset: + def __init__(self, data_dir, batch_size=2, fold_idx=0, n_folds=5, seed=0, pipeline_factor=1, params=None): + self._folders = np.array([os.path.join(data_dir, path) for path in os.listdir(data_dir)]) + self._train, self._eval = cross_validation(self._folders, fold_idx=fold_idx, n_folds=n_folds) + self._pipeline_factor = pipeline_factor + self._data_dir = data_dir + self.params = params + + self._hpu_id = params.worker_id if params.worker_id else 0 + self._num_hpus = params.num_workers if params.num_workers else 1 + + self._batch_size = batch_size + self._seed = seed + + self._xshape = (240, 240, 155, 4) + self._yshape = (240, 240, 155) + + def parse(self, serialized): + features = { + 'X': tf.io.FixedLenFeature([], tf.string), + 'Y': tf.io.FixedLenFeature([], tf.string), + 'mean': tf.io.FixedLenFeature([4], tf.float32), + 'stdev': tf.io.FixedLenFeature([4], tf.float32) + } + + parsed_example = tf.io.parse_single_example(serialized=serialized, + features=features) + + x = tf.io.decode_raw(parsed_example['X'], tf.uint8) + x = tf.cast(tf.reshape(x, self._xshape), tf.uint8) + y = tf.io.decode_raw(parsed_example['Y'], tf.uint8) + y = tf.cast(tf.reshape(y, self._yshape), tf.uint8) + + mean = parsed_example['mean'] + stdev = parsed_example['stdev'] + + return x, y, mean, stdev + + def parse_x(self, serialized): + features = {'X': tf.io.FixedLenFeature([], tf.string), + 'Y': tf.io.FixedLenFeature([], tf.string), + 'mean': tf.io.FixedLenFeature([4], tf.float32), + 'stdev': tf.io.FixedLenFeature([4], tf.float32)} + + parsed_example = tf.io.parse_single_example(serialized=serialized, + features=features) + + x = tf.io.decode_raw(parsed_example['X'], tf.uint8) + x = tf.cast(tf.reshape(x, self._xshape), tf.uint8) + + mean = parsed_example['mean'] + stdev = parsed_example['stdev'] + + return x, mean, stdev + + def prefetch(self, dataset, buffer_size): + """Dataset prefetching function""" + if len(tf.config.list_logical_devices('HPU')) > 0: + device = tf.config.list_logical_devices('HPU')[0].name + with tf.device(device): + dataset = dataset.apply(tf.data.experimental.prefetch_to_device(device)) + else: + dataset = dataset.prefetch(buffer_size) + + return dataset + + def train_fn(self): + assert len(self._train) > 0, "Training data not found." + + ds = tf.data.TFRecordDataset(filenames=self._train) + + ds = ds.shard(self._num_hpus, self._hpu_id) + ds = ds.cache() + ds = ds.shuffle(buffer_size=self._batch_size * 8, seed=self._seed) + ds = ds.repeat() + + ds = ds.map(self.parse, num_parallel_calls=tf.data.experimental.AUTOTUNE) + + transforms = [ + RandomCrop3D((128, 128, 128)), + RandomHorizontalFlip() if self.params.augment else None, + Cast(dtype=tf.float32), + NormalizeImages(), + RandomBrightnessCorrection() if self.params.augment else None, + OneHotLabels(n_classes=4), + ] + + ds = ds.map(map_func=lambda x, y, mean, stdev: apply_transforms(x, y, mean, stdev, transforms=transforms), + num_parallel_calls=tf.data.experimental.AUTOTUNE) + + ds = ds.batch(batch_size=self._batch_size, + drop_remainder=True) + + ds = self.prefetch(ds, buffer_size=tf.data.experimental.AUTOTUNE) + + return ds + + def eval_fn(self): + ds = tf.data.TFRecordDataset(filenames=self._eval) + assert len(self._eval) > 0, "Evaluation data not found. Did you specify --fold flag?" + + ds = ds.cache() + ds = ds.map(self.parse, num_parallel_calls=tf.data.experimental.AUTOTUNE) + + transforms = [ + CenterCrop((224, 224, 155)), + Cast(dtype=tf.float32), + NormalizeImages(), + OneHotLabels(n_classes=4), + PadXYZ() + ] + + ds = ds.map(map_func=lambda x, y, mean, stdev: apply_transforms(x, y, mean, stdev, transforms=transforms), + num_parallel_calls=tf.data.experimental.AUTOTUNE) + ds = ds.batch(batch_size=self._batch_size, + drop_remainder=False) + ds = self.prefetch(ds, buffer_size=tf.data.experimental.AUTOTUNE) + + return ds + + def test_fn(self, count=1, drop_remainder=False): + ds = tf.data.TFRecordDataset(filenames=self._eval) + assert len(self._eval) > 0, "Evaluation data not found. Did you specify --fold flag?" + + ds = ds.repeat(count) + ds = ds.map(self.parse_x, num_parallel_calls=tf.data.experimental.AUTOTUNE) + + transforms = [ + CenterCrop((224, 224, 155)), + Cast(dtype=tf.float32), + NormalizeImages(), + PadXYZ((224, 224, 160)) + ] + + ds = ds.map(map_func=lambda x, mean, stdev: apply_test_transforms(x, mean, stdev, transforms=transforms), + num_parallel_calls=tf.data.experimental.AUTOTUNE) + ds = ds.batch(batch_size=self._batch_size, + drop_remainder=drop_remainder) + ds = self.prefetch(ds, buffer_size=tf.data.experimental.AUTOTUNE) + + return ds + + def synth_train_fn(self): + """Synthetic data function for testing""" + inputs = tf.random.uniform(self._xshape, dtype=tf.int32, minval=0, maxval=255, seed=self._seed, + name='synth_inputs') + masks = tf.random.uniform(self._yshape, dtype=tf.int32, minval=0, maxval=4, seed=self._seed, + name='synth_masks') + + ds = tf.data.Dataset.from_tensors((inputs, masks)) + ds = ds.repeat() + + transforms = [ + Cast(dtype=tf.uint8), + RandomCrop3D((128, 128, 128)), + RandomHorizontalFlip() if self.params.augment else None, + Cast(dtype=tf.float32), + NormalizeImages(), + RandomBrightnessCorrection() if self.params.augment else None, + OneHotLabels(n_classes=4), + ] + + ds = ds.map(map_func=lambda x, y: apply_transforms(x, y, mean=0.0, stdev=1.0, transforms=transforms), + num_parallel_calls=1) + ds = ds.batch(self._batch_size) + ds = self.prefetch(ds, buffer_size=self._batch_size) + + return ds + + def synth_predict_fn(self, count=1): + """Synthetic data function for testing""" + inputs = tf.random.truncated_normal((64, 64, 64, 4), dtype=tf.float32, mean=0.0, stddev=1.0, seed=self._seed, + name='synth_inputs') + + ds = tf.data.Dataset.from_tensors(inputs) + ds = ds.repeat(count) + ds = ds.batch(self._batch_size) + ds = self.prefetch(ds, buffer_size=tf.data.experimental.AUTOTUNE) + + return ds + + @property + def train_size(self): + return len(self._train) + + @property + def eval_size(self): + return len(self._eval) + + @property + def test_size(self): + return len(self._eval) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/preprocess_data.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/preprocess_data.py new file mode 100644 index 0000000000000000000000000000000000000000..465390a5134b5eb8d60d8eb06b581366b6287c29 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/preprocess_data.py @@ -0,0 +1,160 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import argparse +from random import shuffle + +import numpy as np +import nibabel as nib +import tensorflow as tf + + +PARSER = argparse.ArgumentParser() + +PARSER.add_argument('--input_dir', '-i', + type=str, help='path to the input directory with data') + +PARSER.add_argument('--output_dir', '-o', + type=str, help='path to the output directory where tfrecord files will be stored') + +PARSER.add_argument('--verbose', '-v', dest='verbose', action='store_true', default=False) + +PARSER.add_argument('--vol_per_file', default=4, dest='vol_per_file', + type=int, help='how many volumes to pack into a single tfrecord file') + +PARSER.add_argument('--single_data_dir', dest='single_data_dir', action='store_true', default=False) + + +def load_features(path): + data = np.zeros((240, 240, 155, 4), dtype=np.uint8) + name = os.path.basename(path) + for i, modality in enumerate(["_t1.nii.gz", "_t1ce.nii.gz", "_t2.nii.gz", "_flair.nii.gz"]): + vol = load_single_nifti(os.path.join(path, name+modality)).astype(np.float32) + vol[vol > 0.85 * vol.max()] = 0.85 * vol.max() + vol = 255 * vol / vol.max() + data[..., i] = vol.astype(np.uint8) + + return data + + +def load_segmentation(path): + path = os.path.join(path, os.path.basename(path)) + "_seg.nii.gz" + return load_single_nifti(path).astype(np.uint8) + + +def load_single_nifti(path): + data = nib.load(path).get_fdata().astype(np.int16) + return np.transpose(data, (1, 0, 2)) + + +def write_to_file(features_list, labels_list, foreground_mean_list, foreground_std_list, output_dir, count): + output_filename = os.path.join(output_dir, "volume-{}.tfrecord".format(count)) + filelist = list(zip(np.array(features_list), + np.array(labels_list), + np.array(foreground_mean_list), + np.array(foreground_std_list))) + np_to_tfrecords(filelist, output_filename) + + +def np_to_tfrecords(filelist, output_filename): + writer = tf.io.TFRecordWriter(output_filename) + + for idx in range(len(filelist)): + X = filelist[idx][0].flatten().tostring() + Y = filelist[idx][1].flatten().tostring() + mean = filelist[idx][2].astype(np.float32).flatten() + stdev = filelist[idx][3].astype(np.float32).flatten() + + d_feature = {} + d_feature['X'] = tf.train.Feature(bytes_list=tf.train.BytesList(value=[X])) + d_feature['Y'] = tf.train.Feature(bytes_list=tf.train.BytesList(value=[Y])) + d_feature['mean'] = tf.train.Feature(float_list=tf.train.FloatList(value=mean)) + d_feature['stdev'] = tf.train.Feature(float_list=tf.train.FloatList(value=stdev)) + + features = tf.train.Features(feature=d_feature) + example = tf.train.Example(features=features) + serialized = example.SerializeToString() + writer.write(serialized) + writer.close() + + +def main(): + # parse arguments + params = PARSER.parse_args() + input_dir = params.input_dir + output_dir = params.output_dir + os.makedirs(params.output_dir, exist_ok=True) + + patient_list = [] + if params.single_data_dir: + patient_list.extend([os.path.join(input_dir, folder) for folder in os.listdir(input_dir)]) + else: + assert "HGG" in os.listdir(input_dir) and "LGG" in os.listdir(input_dir),\ + "Data directory has to contain folders named HGG and LGG. " \ + "If you have a single folder with patient's data please set --single_data_dir flag" + path_hgg = os.path.join(input_dir, "HGG") + path_lgg = os.path.join(input_dir, "LGG") + patient_list.extend([os.path.join(path_hgg, folder) for folder in os.listdir(path_hgg)]) + patient_list.extend([os.path.join(path_lgg, folder) for folder in os.listdir(path_lgg)]) + shuffle(patient_list) + + features_list = [] + labels_list = [] + foreground_mean_list = [] + foreground_std_list = [] + count = 0 + + total_tfrecord_files = len(patient_list) // params.vol_per_file + (1 if len(patient_list) % params.vol_per_file + else 0) + for i, folder in enumerate(patient_list): + + # Calculate mean and stdev only for foreground voxels + features = load_features(folder) + foreground = features > 0 + fg_mean = np.array([(features[..., i][foreground[..., i]]).mean() for i in range(features.shape[-1])]) + fg_std = np.array([(features[..., i][foreground[..., i]]).std() for i in range(features.shape[-1])]) + + # BraTS labels are 0,1,2,4 -> switching to 0,1,2,3 + labels = load_segmentation(folder) + labels[labels == 4] = 3 + + features_list.append(features) + labels_list.append(labels) + foreground_mean_list.append(fg_mean) + foreground_std_list.append(fg_std) + + if (i+1) % params.vol_per_file == 0: + write_to_file(features_list, labels_list, foreground_mean_list, foreground_std_list, output_dir, count) + + # Clear lists + features_list = [] + labels_list = [] + foreground_mean_list = [] + foreground_std_list = [] + count += 1 + + if params.verbose: + print("{}/{} tfrecord files created".format(count, total_tfrecord_files)) + + # create one more file if there are any remaining unpacked volumes + if features_list: + write_to_file(features_list, labels_list, foreground_mean_list, foreground_std_list, output_dir, count) + count += 1 + if params.verbose: + print("{}/{} tfrecord files created".format(count, total_tfrecord_files)) + + +if __name__ == '__main__': + main() diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/transforms.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1dc8453cb5cbeae0a08369a7f4ee218ef2b87e --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/dataset/transforms.py @@ -0,0 +1,218 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - script migration to Tensorflow 2.x version +# - added seed setting possibility to random operations + +import tensorflow as tf + +from runtime.arguments import parse_args + +params = parse_args() + + +def apply_transforms(x, y, mean, stdev, transforms): + for _t in transforms: + if _t is not None: + x, y = _t(x, y, mean, stdev) + return x, y + + +def apply_test_transforms(x, mean, stdev, transforms): + for _t in transforms: + if _t is not None: + x = _t(x, y=None, mean=mean, stdev=stdev) + return x + + +class PadXYZ: + def __init__(self, shape=None): + self.shape = shape + + def __call__(self, x, y, mean, stdev): + paddings = tf.constant([[0, 0], [0, 0], [0, 5], [0, 0]]) + x = tf.pad(tensor=x, paddings=paddings, mode="CONSTANT") + if y is None: + return x + y = tf.pad(tensor=y, paddings=paddings, mode="CONSTANT") + return x, y + + +class CenterCrop: + def __init__(self, shape): + self.shape = shape + + def __call__(self, x, y, mean, stdev): + shape = x.get_shape() + delta = [(shape[i] - self.shape[i]) // 2 for i in range(len(self.shape))] + x = x[ + delta[0]:delta[0] + self.shape[0], + delta[1]:delta[1] + self.shape[1], + delta[2]:delta[2] + self.shape[2] + ] + if y is None: + return x + y = y[ + delta[0]:delta[0] + self.shape[0], + delta[1]:delta[1] + self.shape[1], + delta[2]:delta[2] + self.shape[2] + ] + return x, y + + +class RandomCrop3D: + def __init__(self, shape, margins=(0, 0, 0)): + self.shape = shape + self.margins = margins + + def __call__(self, x, y, mean, stdev): + shape = x.get_shape() + min = tf.constant(self.margins, dtype=tf.float32) + max = tf.constant([shape[0] - self.shape[0] - self.margins[0], + shape[1] - self.shape[1] - self.margins[1], + shape[2] - self.shape[2] - self.margins[2]], dtype=tf.float32) + center = tf.random.uniform((len(self.shape),), minval=min, maxval=max, seed=params.seed) + center = tf.cast(center, dtype=tf.int32) + x = x[center[0]:center[0] + self.shape[0], + center[1]:center[1] + self.shape[1], + center[2]:center[2] + self.shape[2]] + if y is None: + return x + y = y[center[0]:center[0] + self.shape[0], + center[1]:center[1] + self.shape[1], + center[2]:center[2] + self.shape[2]] + return x, y + + +class NormalizeImages: + def __init__(self): + pass + + def __call__(self, x, y, mean, stdev): + mask = tf.math.greater(x, 0) + x = tf.compat.v1.where(mask, (x - tf.cast(mean, x.dtype)) / (tf.cast(stdev + 1e-8, x.dtype)), x) + + if y is None: + return x + return x, y + + +class Cast: + def __init__(self, dtype=tf.float32): + self._dtype = dtype + + def __call__(self, x, y, mean, stdev): + if y is None: + return tf.cast(x, dtype=self._dtype) + return tf.cast(x, dtype=self._dtype), y + + +class RandomHorizontalFlip: + def __init__(self, threshold=0.5): + self._threshold = threshold + + def __call__(self, x, y, mean, stdev): + h_flip = tf.random.uniform([], seed=params.seed) > self._threshold + + x = tf.cond(pred=h_flip, true_fn=lambda: tf.reverse(x, axis=[1]), false_fn=lambda: x) + y = tf.cond(pred=h_flip, true_fn=lambda: tf.reverse(y, axis=[1]), false_fn=lambda: y) + + return x, y + + +class RandomVerticalFlip: + def __init__(self, threshold=0.5): + self._threshold = threshold + + def __call__(self, x, y, mean, stdev): + h_flip = tf.random.uniform([], seed=params.seed) > self._threshold + + x = tf.cond(pred=h_flip, true_fn=lambda: tf.reverse(x, axis=[0]), false_fn=lambda: x) + y = tf.cond(pred=h_flip, true_fn=lambda: tf.reverse(y, axis=[0]), false_fn=lambda: y) + + return x, y + + +class RandomGammaCorrection: + def __init__(self, gamma_range=(0.8, 1.5), keep_stats=False, threshold=0.5, epsilon=1e-8): + self._gamma_range = gamma_range + self._keep_stats = keep_stats + self._eps = epsilon + self._threshold = threshold + + def __call__(self, x, y, mean, stdev): + augment = tf.random.uniform([], seed=params.seed) > self._threshold + gamma = tf.random.uniform([], minval=self._gamma_range[0], maxval=self._gamma_range[1], seed=params.seed) + + x_min = tf.math.reduce_min(input_tensor=x) + x_range = tf.math.reduce_max(input_tensor=x) - x_min + + x = tf.cond(pred=augment, + true_fn=lambda: tf.math.pow(((x - x_min) / float(x_range + self._eps)), gamma) * x_range + x_min, + false_fn=lambda: x) + return x, y + + +class RandomBrightnessCorrection: + def __init__(self, alpha=0.1, threshold=0.5, per_channel=True): + self._alpha_range = [1.0 - alpha, 1.0 + alpha] + self._threshold = threshold + self._per_channel = per_channel + + def __call__(self, x, y, mean, stdev): + mask = tf.math.greater(x, 0) + size = x.get_shape()[-1] if self._per_channel else 1 + augment = tf.random.uniform([], seed=params.seed) > self._threshold + correction = tf.random.uniform([size], + minval=self._alpha_range[0], + maxval=self._alpha_range[1], + dtype=x.dtype, seed=params.seed) + + x = tf.cond(pred=augment, + true_fn=lambda: tf.compat.v1.where(mask, x + correction, x), + false_fn=lambda: x) + + return x, y + + +class OneHotLabels: + def __init__(self, n_classes=1): + self._n_classes = n_classes + + def __call__(self, x, y, mean, stdev): + return x, tf.one_hot(y, self._n_classes) + + +class PadXY: + def __init__(self, dst_size=None): + if not dst_size: + raise ValueError("Invalid padding size: {}".format(dst_size)) + + self._dst_size = dst_size + + def __call__(self, x, y, mean, stdev): + return tf.pad(tensor=x, paddings=self._build_padding(x)), \ + tf.pad(tensor=y, paddings=self._build_padding(y)) + + def _build_padding(self, _t): + padding = [] + for i in range(len(_t.shape)): + if i < len(self._dst_size): + padding.append((0, self._dst_size[i] - _t.shape[i])) + else: + padding.append((0, 0)) + return padding diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/main.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/main.py new file mode 100644 index 0000000000000000000000000000000000000000..fec7cdc4fb9a61f635e3f33d6f289e462c54917f --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/main.py @@ -0,0 +1,114 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - script migration to Tensorflow 2.x version +# - included HPU horovod setup +# - added tensorboard logging functionality +# - added TumorCore, PeritumoralEdema and EnhancingTumor metrics to evaluation results +# - debug_train and debug_predict options have been removed +# - added tensor dumping possibility for training with dump_callback function +# - added TimeToTrain estimator for dumping evaluation timestamps + +import os +import logging + +import numpy as np +import tensorflow as tf + +from dataset.data_loader import Dataset, CLASSES +from runtime.hooks import get_hooks +from runtime.arguments import parse_args +from runtime.setup import prepare_model_dir, build_estimator, setup_horovod, set_flags, get_logger +from TensorFlow.common.debug import dump_callback + + +def parse_evaluation_results(result): + data = {CLASSES[i]: result[CLASSES[i]] for i in range(len(CLASSES))} + data['MeanDice'] = str(sum([result[CLASSES[i]] for i in range(len(CLASSES))]) / len(CLASSES)) + data['WholeTumor'] = str(result['WholeTumor']) + data['TumorCore'] = str(data['TumorCore']) + data['PeritumoralEdema'] = str(data['PeritumoralEdema']) + data['EnhancingTumor'] = str(data['EnhancingTumor']) + return data + + +def main(): + params = parse_args() + tf.random.set_seed(params.seed) + tf.get_logger().setLevel(logging.ERROR) + + params = setup_horovod(params) + set_flags(params) + model_dir = prepare_model_dir(params) + logger = get_logger(params) + + dataset = Dataset(data_dir=params.data_dir, + batch_size=params.batch_size, + fold_idx=params.fold, + n_folds=params.num_folds, + params=params, + seed=params.seed) + + estimator = build_estimator(params, model_dir) + + if params.tensorboard_logging and (params.worker_id == 0 or params.log_all_workers): + from TensorFlow.common.tb_utils import write_hparams_v1 + write_hparams_v1(params.log_dir, vars(params)) + + if params.tensorboard_logging: + from TensorFlow.common.tb_utils import TimeToTrainEstimatorHook + ttt = TimeToTrainEstimatorHook(train_or_eval ='eval', output_dir=params.log_dir) + + if not params.benchmark: + params.max_steps = params.max_steps // params.num_workers + if 'train' in params.exec_mode: + with dump_callback(params.dump_config): + training_hooks = get_hooks(params, logger) + dataset_fn = dataset.synth_train_fn if params.synth_data else dataset.train_fn + + estimator.train( + input_fn=dataset_fn, + steps=params.max_steps, + hooks=training_hooks) + + if 'evaluate' in params.exec_mode: + if params.tensorboard_logging: + ttt.begin() + result = estimator.evaluate(input_fn=dataset.eval_fn, steps=dataset.eval_size) + if params.tensorboard_logging: + ttt.end(session=None) + data = parse_evaluation_results(result) + if params.worker_id == 0: + logger.log(step=(), data=data) + + if 'predict' == params.exec_mode: + inference_hooks = get_hooks(params, logger) + if params.worker_id == 0: + count = 1 if not params.benchmark else 2 * params.warmup_steps * params.batch_size // dataset.test_size + predictions = estimator.predict( + input_fn=lambda: dataset.test_fn(count=count, + drop_remainder=params.benchmark), hooks=inference_hooks) + + for idx, p in enumerate(predictions): + volume = p['predictions'] + if not params.benchmark: + np.save(os.path.join(params.model_dir, "vol_{}.npy".format(idx)), volume) + + +if __name__ == '__main__': + tf.compat.v1.disable_eager_execution() + main() diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/layers.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..fd5481e0af116083a154fe500f80ad0ad6a5fb54 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/layers.py @@ -0,0 +1,134 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021-2023 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - script migration to Tensorflow 2.x version +# - tf.contrib.layers.instance_norm, tf.contrib.layers.group_norm replaced with its tensorflow_addons counterparts +# - added support for HabanaInstanceNormalization +# - added seed setting possibility to glorot_uniform_initializer operations + +import tensorflow as tf +from keras.layers import GroupNormalization +from runtime.arguments import parse_args + + +params = parse_args() + + +def _normalization(inputs, name, mode): + training = mode == tf.estimator.ModeKeys.TRAIN + if name == 'instancenorm': + if not params.no_hpu: + from habana_frameworks.tensorflow.ops.instance_norm import HabanaInstanceNormalization + instance_norm_block = HabanaInstanceNormalization + else: + instance_norm_block = GroupNormalization(groups=-1) + + gamma_initializer = tf.compat.v1.constant_initializer(1.0) + return instance_norm_block(gamma_initializer=gamma_initializer, epsilon=1e-6)(inputs, training=training) + + if name == 'groupnorm': + return GroupNormalization(groups=16, axis=-1)(inputs, training=training) + + if name == 'batchnorm': + return tf.compat.v1.keras.layers.BatchNormalization(axis=-1, + trainable=True, + virtual_batch_size=None)(inputs, training=training) + elif name == 'none': + return inputs + else: + raise ValueError('Invalid normalization layer') + + +def _activation(x, activation): + if activation == 'relu': + return tf.nn.relu(x) + elif activation == 'leaky_relu': + return tf.nn.leaky_relu(x, alpha=0.01) + elif activation == 'sigmoid': + return tf.nn.sigmoid(x) + elif activation == 'softmax': + return tf.nn.softmax(x) + elif activation == 'none': + return x + else: + raise ValueError("Unknown activation {}".format(activation)) + + +def convolution(x, + out_channels, + kernel_size=3, + stride=1, + mode=tf.estimator.ModeKeys.TRAIN, + normalization='batchnorm', + activation='leaky_relu', + transpose=False): + + conv = tf.keras.layers.Conv3DTranspose if transpose else tf.keras.layers.Conv3D + regularizer = None + + x = conv(filters=out_channels, + kernel_size=kernel_size, + strides=stride, + activation=None, + padding='same', + data_format='channels_last', + kernel_initializer=tf.compat.v1.glorot_uniform_initializer(seed=params.seed), + kernel_regularizer=regularizer, + bias_initializer=tf.compat.v1.zeros_initializer(), + bias_regularizer=regularizer)(x) + + x = _normalization(x, normalization, mode) + + return _activation(x, activation) + + +def upsample_block(x, skip_connection, out_channels, normalization, mode): + x = convolution(x, kernel_size=2, out_channels=out_channels, stride=2, + normalization='none', activation='none', transpose=True) + x = tf.keras.layers.Concatenate(axis=-1)([x, skip_connection]) + + x = convolution(x, out_channels=out_channels, normalization=normalization, mode=mode) + x = convolution(x, out_channels=out_channels, normalization=normalization, mode=mode) + return x + + +def input_block(x, out_channels, normalization, mode): + x = convolution(x, out_channels=out_channels, normalization=normalization, mode=mode) + x = convolution(x, out_channels=out_channels, normalization=normalization, mode=mode) + return x + + +def downsample_block(x, out_channels, normalization, mode): + x = convolution(x, out_channels=out_channels, normalization=normalization, mode=mode, stride=2) + return convolution(x, out_channels=out_channels, normalization=normalization, mode=mode) + + +def linear_block(x, out_channels, mode, activation='leaky_relu', normalization='none'): + x = convolution(x, out_channels=out_channels, normalization=normalization, mode=mode) + return convolution(x, out_channels=out_channels, activation=activation, mode=mode, normalization=normalization) + + +def output_layer(x, out_channels, activation): + x = tf.keras.layers.Conv3D(out_channels, + kernel_size=3, + activation=None, + padding='same', + kernel_regularizer=None, + kernel_initializer=tf.compat.v1.glorot_uniform_initializer(seed=params.seed), + bias_initializer=tf.compat.v1.zeros_initializer(), + bias_regularizer=None)(x) + return _activation(x, activation) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/losses.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..09fb0fc0acc6ccce96b063324c04ce56ba0b1b22 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/losses.py @@ -0,0 +1,89 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - script migration to Tensorflow 2.x version + +import tensorflow as tf + + +def make_loss(params, y_true, y_pred): + if params.loss == 'dice': + return _dice(y_true, y_pred) + if params.loss == 'ce': + return _ce(y_true, y_pred) + if params.loss == 'dice+ce': + return tf.add(_ce(y_true, y_pred), _dice(y_true, y_pred), name="total_loss_ref") + + raise ValueError('Unknown loss: {}'.format(params.loss)) + + +def _ce(y_true, y_pred): + return tf.reduce_sum( + input_tensor=tf.reduce_mean(input_tensor=tf.keras.backend.binary_crossentropy( + tf.cast(y_true, tf.float32), y_pred), axis=[0, 1, 2, 3]), + name='crossentropy_loss_ref') + + +def _dice(y_true, y_pred): + return tf.reduce_sum(input_tensor=dice_loss(predictions=y_pred, targets=y_true), name='dice_loss_ref') + + +def eval_dice(y_true, y_pred): + return 1 - dice_loss(predictions=y_pred, targets=y_true) + + +def dice_loss(predictions, + targets, + squared_pred=False, + smooth=1e-5, + top_smooth=0.0): + is_channels_first = False + + n_len = len(predictions.get_shape()) + reduce_axis = list(range(2, n_len)) if is_channels_first else list(range(1, n_len - 1)) + intersection = tf.reduce_sum(input_tensor=targets * predictions, axis=reduce_axis) + + if squared_pred: + targets = tf.square(targets) + predictions = tf.square(predictions) + + y_true_o = tf.reduce_sum(input_tensor=targets, axis=reduce_axis) + y_pred_o = tf.reduce_sum(input_tensor=predictions, axis=reduce_axis) + + denominator = y_true_o + y_pred_o + + f = (2.0 * intersection + top_smooth) / (denominator + smooth) + + return 1 - tf.reduce_mean(input_tensor=f, axis=0) + + +def total_dice(predictions, + targets, + smooth=1e-5, + top_smooth=0.0): + n_len = len(predictions.get_shape()) + reduce_axis = list(range(1, n_len-1)) + targets = tf.reduce_sum(input_tensor=targets, axis=-1) + predictions = tf.reduce_sum(input_tensor=predictions, axis=-1) + intersection = tf.reduce_sum(input_tensor=targets * predictions, axis=reduce_axis) + + y_true_o = tf.reduce_sum(input_tensor=targets, axis=reduce_axis) + y_pred_o = tf.reduce_sum(input_tensor=predictions, axis=reduce_axis) + + denominator = y_true_o + y_pred_o + + return tf.reduce_mean(input_tensor=(2.0 * intersection + top_smooth) / (denominator + smooth)) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/model_fn.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/model_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..fbfcf790cc907a412818230bb1e64fd80d7b103d --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/model_fn.py @@ -0,0 +1,89 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - script migration to Tensorflow 2.x version +# - added 'accuracy' metrics for consistency +# - added tensorboard loss logging +# - moved horovod import under use_horovod condition so that the user is not required to install this +# library when the model is being run on a single card + +import os + +import tensorflow as tf + +from model.unet3d import Builder +from model.losses import make_loss, eval_dice, total_dice +from dataset.data_loader import CLASSES + + +def unet_3d(features, labels, mode, params): + + logits = Builder(n_classes=4, normalization=params.normalization, mode=mode)(features) + + if mode == tf.estimator.ModeKeys.PREDICT: + prediction = tf.argmax(input=logits, axis=-1, output_type=tf.dtypes.int32) + return tf.estimator.EstimatorSpec(mode=mode, + predictions={'predictions': tf.cast(prediction, tf.int8)}) + + labels = tf.cast(labels, tf.float32) + if not params.include_background: + labels = labels[..., 1:] + logits = logits[..., 1:] + + if mode == tf.estimator.ModeKeys.EVAL: + eval_acc = eval_dice(y_true=labels, y_pred=tf.round(logits)) + total_eval_acc = total_dice(tf.round(logits), labels) + metrics = {CLASSES[i]: tf.compat.v1.metrics.mean(eval_acc[i]) for i in range(eval_acc.shape[-1])} + metrics['WholeTumor'] = tf.compat.v1.metrics.mean(total_eval_acc) + metrics['accuracy'] = metrics['WholeTumor'] # for consistency + return tf.estimator.EstimatorSpec(mode=mode, loss=tf.reduce_mean(input_tensor=eval_acc), + eval_metric_ops=metrics) + + loss = make_loss(params, y_pred=logits, y_true=labels) + loss = tf.identity(loss, name="total_loss_ref") + + global_step = tf.compat.v1.train.get_or_create_global_step() + + optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=params.learning_rate) + if params.use_horovod: + import horovod.tensorflow as hvd + optimizer = hvd.DistributedOptimizer(optimizer) + + # NGC has TF_ENABLE_AUTO_MIXED_PRECISION enabled by default. We cannot use + # both graph_rewrite and envar, so if we're not in NGC we do graph_rewrite + try: + amp_envar = int(os.environ['TF_ENABLE_AUTO_MIXED_PRECISION']) == 1 + except KeyError: + amp_envar = False + + if params.use_amp and not amp_envar: + optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite( + optimizer, + loss_scale='dynamic' + ) + + with tf.control_dependencies(tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS)): + train_op = optimizer.minimize(loss, global_step=global_step) + + training_hooks = [] + if params.tensorboard_logging and (params.worker_id == 0 or params.log_all_workers): + tf.compat.v1.summary.scalar("loss", loss) + training_hooks += [tf.estimator.SummarySaverHook(params.log_every, + output_dir=params.log_dir, summary_op=tf.compat.v1.summary.merge_all())] + + return tf.estimator.EstimatorSpec( + mode=mode, loss=loss, train_op=train_op, training_hooks=training_hooks) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/unet3d.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/unet3d.py new file mode 100644 index 0000000000000000000000000000000000000000..fc27361ff89b443a338d42b9860c4f8ffb2118c1 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/model/unet3d.py @@ -0,0 +1,82 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from model.layers import downsample_block, upsample_block, output_layer, input_block + + +class Builder: + def __init__(self, n_classes, mode, normalization='none'): + self._n_classes = n_classes + self._mode = mode + self._normalization = normalization + + def __call__(self, features): + skip_128 = input_block(x=features, + out_channels=32, + normalization=self._normalization, + mode=self._mode) + + skip_64 = downsample_block(x=skip_128, + out_channels=64, + normalization=self._normalization, + mode=self._mode) + + skip_32 = downsample_block(x=skip_64, + out_channels=128, + normalization=self._normalization, + mode=self._mode) + + skip_16 = downsample_block(x=skip_32, + out_channels=256, + normalization=self._normalization, + mode=self._mode) + + skip_8 = downsample_block(x=skip_16, + out_channels=320, + normalization=self._normalization, + mode=self._mode) + + x = downsample_block(x=skip_8, + out_channels=320, + normalization=self._normalization, + mode=self._mode) + + x = upsample_block(x, skip_8, + out_channels=320, + normalization=self._normalization, + mode=self._mode) + + x = upsample_block(x, skip_16, + out_channels=256, + normalization=self._normalization, + mode=self._mode) + + x = upsample_block(x, skip_32, + out_channels=128, + normalization=self._normalization, + mode=self._mode) + + x = upsample_block(x, skip_64, + out_channels=64, + normalization=self._normalization, + mode=self._mode) + + x = upsample_block(x, skip_128, + out_channels=32, + normalization=self._normalization, + mode=self._mode) + + return output_layer(x=x, + out_channels=self._n_classes, + activation='softmax') diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/requirements.txt b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..c9acd4348bba7d69456d6646866d54c696094695 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/requirements.txt @@ -0,0 +1,4 @@ +git+https://github.com/nvidia/dllogger@26a0f8f1958de2c0c460925ff6102a4d2486d6cc#egg=dllogger +munch==2.5.0 +nibabel==3.2.1 +PyYAML==6.0.0 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/arguments.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..ab75ef52747451dcddc997482c90cd509ad69c71 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/arguments.py @@ -0,0 +1,166 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - default values for exec_mode, max_steps, log_dir, augment, use_xla, batch_size +# - added dtype, num_workers_per_hls, kubernetes_run, use_horovod, no-augment, no_xla, +# seed, no_hpu, tensorboard_logging, log_all_workers, tf_verbosity, bf16_config_path options, +# dump_config, synth_data, disable_ckpt_saving +# - included missing help for all available flags +# - parser has been wraper with Munch dict for more elegant parameter access + + +import os +import argparse +from pathlib import Path + +from munch import Munch + + +def get_parser(description, distributed_launcher): + + parser = argparse.ArgumentParser(description=description) + + # Estimator flags + parser.add_argument('--model_dir', required=True, type=str, + help="""Output directory for information related to the model""") + parser.add_argument('--exec_mode', default="train_and_evaluate", + choices=['train', 'evaluate', 'train_and_evaluate', 'predict'], type=str, + help="""Execution mode of running the model""") + + # Training flags + parser.add_argument('--benchmark', dest='benchmark', action='store_true', default=False, + help="""Collect performance metrics during training""") + parser.add_argument('--max_steps', default=16000, type=int, + help="""Maximum number of steps used for training""") + parser.add_argument('--learning_rate', default=0.0002, type=float, + help="""Learning rate coefficient for AdamOptimizer""") + parser.add_argument('--log_every', default=100, type=int, + help="""Log data every n steps""") + parser.add_argument('--log_dir', default="/tmp/unet3d_logs", type=str, + help="""Output directory for logs""") + parser.add_argument('--loss', choices=['dice', 'ce', 'dice+ce'], default='dice+ce', type=str, + help="""Loss function to be used during training""") + parser.add_argument('--warmup_steps', default=40, type=int, + help="""Number of warmup steps""") + parser.add_argument('--normalization', choices=['instancenorm', 'batchnorm', 'groupnorm'], + default='instancenorm', type=str, + help="""Normalization block to be applied in the model""") + parser.add_argument('--include_background', dest='include_background', action='store_true', default=False, + help="""Include background both in preditions and labels""") + parser.add_argument('--resume_training', dest='resume_training', action='store_true', default=False, + help="""Resume training from a checkpoint""") + parser.add_argument('--num_workers_per_hls', dest='num_workers_per_hls', type=int, default=1, + help="""Number of workers for single HLS""" if distributed_launcher else argparse.SUPPRESS) # ignored by main.py + parser.add_argument("--hls_type", default="HLS1", type=str, + help="Type of HLS" if distributed_launcher else argparse.SUPPRESS) # ignored by main.py + parser.add_argument("--kubernetes_run", default=False, type=bool, + help="Kubernetes run" if distributed_launcher else argparse.SUPPRESS) # ignored by main.py + parser.add_argument('--use_horovod', dest='use_horovod', action='store_true', + help="""Enable horovod usage""") + + # Augmentations + parser.add_argument('--augment', dest='augment', action='store_true', + help="""Perform data augmentation during training""") + parser.add_argument('--no-augment', dest='augment', action='store_false') + parser.set_defaults(augment=True) + + # Dataset flags + parser.add_argument('--data_dir', required=True, type=str, + help="""Input directory containing the dataset for training the model""") + parser.add_argument('--batch_size', default=2, type=int, + help="""Size of each minibatch per device""") + parser.add_argument('--fold', default=0, type=int, + help="""Chosen fold for cross-validation""") + parser.add_argument('--num_folds', default=5, type=int, + help="""Number of folds in k-cross-validation of dataset""") + + # Tensorflow configuration flags + parser.add_argument('--dtype', '-d', type=str, choices=['fp32', 'bf16'], default='bf16', + help='Data type for HPU: fp32 or bf16') + parser.add_argument('--use_amp', '--amp', dest='use_amp', action='store_true', default=False, + help="""Train using TF-AMP for GPU/CPU""") + parser.add_argument('--use_xla', '--xla', dest='use_xla', action='store_true', + help="""Train using XLA""") + parser.add_argument('--no_xla', dest='use_xla', action='store_false') + parser.set_defaults(use_xla=True) + + parser.add_argument('--seed', default=None, type=int, + help="""Random seed""") + parser.add_argument('--dump_config', type=str, default=None, + help="""Directory for dumping debug traces""") + parser.add_argument('--synth_data', dest='synth_data', action='store_true', + help="""Use deterministic and synthetic data""") + parser.add_argument('--disable_ckpt_saving', dest='disable_ckpt_saving', action='store_true', + help="""Disables saving checkpoints""") + parser.add_argument('--no_hpu', dest='no_hpu', action='store_true', + help="""Do not load Habana modules. Train the model on CPU/GPU""") + parser.add_argument('--tensorboard_logging', dest='tensorboard_logging', action='store_true', + help="""Enable tensorboard logging""") + parser.add_argument('--log_all_workers', dest='log_all_workers', action='store_true', + help="""Enable logging data for every worker in a separate directory named `worker_N`""") + parser.add_argument('--tf_verbosity', dest='tf_verbosity', type=int, choices=[0, 1, 2, 3], + help="""Logging level from Tensorflow. + 0 = all messages are logged (default behavior) + 1 = INFO messages are not printed + 2 = INFO and WARNING messages are not printed + 3 = INFO, WARNING, and ERROR messages are not printed""") + DEFAULT_BF16_CONFIG_PATH = os.fspath(Path(os.path.realpath( + __file__)).parents[1].joinpath("bf16_config/unet.json")) + parser.add_argument('--bf16_config_path', metavar='', required=False, type=str, default=DEFAULT_BF16_CONFIG_PATH, + help=f'Path to custom mixed precision config to use given in JSON format. Defaults to {DEFAULT_BF16_CONFIG_PATH}') + + return parser + + +def parse_args(description="UNet-3D", distributed_launcher=False): + flags = get_parser(description, distributed_launcher).parse_args() + return Munch({ + 'model_dir': flags.model_dir, + 'exec_mode': flags.exec_mode, + 'benchmark': flags.benchmark, + 'max_steps': flags.max_steps, + 'learning_rate': flags.learning_rate, + 'log_every': flags.log_every, + 'log_dir': flags.log_dir, + 'loss': flags.loss, + 'warmup_steps': flags.warmup_steps, + 'normalization': flags.normalization, + 'include_background': flags.include_background, + 'resume_training': flags.resume_training, + 'augment': flags.augment, + 'data_dir': flags.data_dir, + 'batch_size': flags.batch_size, + 'fold': flags.fold, + 'num_folds': flags.num_folds, + 'use_amp': flags.use_amp, + 'use_xla': flags.use_xla, + 'dtype': flags.dtype, + 'precision': flags.dtype, + 'num_workers_per_hls': flags.num_workers_per_hls, + 'hls_type': flags.hls_type, + 'kubernetes_run': flags.kubernetes_run, + 'use_horovod': flags.use_horovod, + 'seed': flags.seed, + 'no_hpu': flags.no_hpu, + 'tensorboard_logging': flags.tensorboard_logging, + 'log_all_workers': flags.log_all_workers, + 'tf_verbosity': flags.tf_verbosity, + 'bf16_config_path': flags.bf16_config_path, + 'dump_config': flags.dump_config, + 'synth_data': flags.synth_data, + 'disable_ckpt_saving': flags.disable_ckpt_saving, + }) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/hooks.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..1e41b63b1c2fb575eb9000b3141e2b312425ecae --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/hooks.py @@ -0,0 +1,138 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - added tensorboard logging possibility +# - added performance parameters logging during training +# - added possibility to log data from every horovod worker +# - moved horovod import under use_horovod condition so that the user is not required to install this +# library when the model is being run on a single card + +import time + +import numpy as np +import tensorflow as tf + + +def get_hooks(params, logger): + if 'train' in params.exec_mode: + hooks = [] + if params.use_horovod: + import horovod.tensorflow as hvd + hooks += [hvd.BroadcastGlobalVariablesHook(0)] + if params.worker_id == 0 or params.log_all_workers: + if params.benchmark: + hooks += [ProfilingHook(warmup_steps=params.warmup_steps, + global_batch_size=params.num_workers * params.batch_size, + logger=logger, + mode='train')] + else: + hooks += [TrainingHook(params, + logger=logger, + tensor_names=['total_loss_ref:0'])] + if params.tensorboard_logging: + from TensorFlow.common.tb_utils import ExamplesPerSecondEstimatorHook + hooks += [ExamplesPerSecondEstimatorHook(params.batch_size, + params.log_every, + output_dir=params.log_dir)] + return hooks + + elif 'predict' == params.exec_mode: + hooks = [] + if params.worker_id == 0: + if params.benchmark: + hooks += [ProfilingHook(warmup_steps=params.warmup_steps, + global_batch_size=params.batch_size, + logger=logger, + mode='test')] + return hooks + + +class ProfilingHook(tf.estimator.SessionRunHook): + def __init__(self, warmup_steps, global_batch_size, logger, mode): + self._warmup_steps = warmup_steps + self._global_batch_size = global_batch_size + self._step = 0 + self._timestamps = [] + self._logger = logger + self._mode = mode + + def before_run(self, run_context): + self._step += 1 + if self._step >= self._warmup_steps: + self._timestamps.append(time.time()) + + def end(self, session): + deltas = np.array([self._timestamps[i + 1] - self._timestamps[i] + for i in range(len(self._timestamps) - 1)]) + stats = process_performance_stats(np.array(deltas), + self._global_batch_size, + self._mode) + + self._logger.log(step=(), data={metric: float( + value) for (metric, value) in stats}) + self._logger.flush() + + +class TrainingHook(tf.estimator.SessionRunHook): + def __init__(self, params, logger, tensor_names): + self._params = params + self._step = 0 + self._timestamp = time.time() + self._logger = logger + self._tensor_names = tensor_names + + def before_run(self, run_context): + run_args = tf.estimator.SessionRunArgs( + fetches=self._tensor_names + ) + + return run_args + + def after_run(self, + run_context, + run_values): + if self._step % self._params.log_every == 0: + duration = float(time.time() - self._timestamp) / \ + self._params.log_every + self._timestamp = time.time() + data = {} + for i in range(len(self._tensor_names)): + data[self._tensor_names[i]] = str(run_values.results[i]) + data["iter duration [ms]"] = 1000 * duration + data["examples/sec"] = self._params.batch_size / duration + self._logger.log( + step=(self._step, self._params.max_steps), data=data) + self._step += 1 + + def end(self, session): + self._logger.flush() + + +def process_performance_stats(timestamps, batch_size, mode): + timestamps_ms = 1000 * timestamps + latency_ms = timestamps_ms.mean() + std = timestamps_ms.std() + n = np.sqrt(len(timestamps_ms)) + throughput_imgps = (1000.0 * batch_size / timestamps_ms).mean() + + stats = [("throughput_{}".format(mode), str(throughput_imgps)), + ('latency_{}:'.format(mode), str(latency_ms))] + for ci, lvl in zip(["90%:", "95%:", "99%:"], + [1.645, 1.960, 2.576]): + stats.append(("Latency_{} ".format(mode) + ci, + str(latency_ms + lvl * std / n))) + return stats diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/parse_results.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/parse_results.py new file mode 100644 index 0000000000000000000000000000000000000000..815f7a171d764328198de9266555c797c00bd5a6 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/parse_results.py @@ -0,0 +1,66 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import argparse + + +def parse_convergence_results(path, environment): + whole_tumor = [] + tumor_core = [] + peritumoral_edema = [] + enhancing_tumor = [] + mean_dice = [] + logfiles = [f for f in os.listdir(path) if "log" in f and environment in f] + if not logfiles: + raise FileNotFoundError("No logfile found at {}".format(path)) + for logfile in logfiles: + with open(os.path.join(path, logfile), "r") as f: + content = f.readlines() + if "TumorCore" not in content[-1]: + print("Evaluation score not found. The file", logfile, "might be corrupted.") + continue + content = content[-1].split("()")[1] + whole_tumor.append(float([val for val in content.split(" ") + if "WholeTumor" in val][0].split()[-1])) + tumor_core.append(float([val for val in content.split(" ") + if "TumorCore" in val][0].split()[-1])) + peritumoral_edema.append(float([val for val in content.split(" ") + if "PeritumoralEdema" in val][0].split()[-1])) + enhancing_tumor.append(float([val for val in content.split(" ") + if "EnhancingTumor" in val][0].split()[-1])) + mean_dice.append(float([val for val in content.split(" ") + if "MeanDice" in val][0].split()[-1])) + + if whole_tumor: + print("Evaluation average dice score:", sum(mean_dice) / len(mean_dice)) + print("Evaluation whole tumor dice score:", sum(whole_tumor) / len(whole_tumor)) + print("Evaluation tumor core dice score:", sum(tumor_core) / len(tumor_core)) + print("Evaluation peritumoral edema dice score:", sum(peritumoral_edema) / len(peritumoral_edema)) + print("Evaluation enhancing tumor dice score:", sum(enhancing_tumor) / len(enhancing_tumor)) + else: + print("All logfiles were corrupted, no loss was obtained.") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--model_dir', + type=str, + required=True) + parser.add_argument('--env', + type=str, + required=True) + + args = parser.parse_args() + parse_convergence_results(path=args.model_dir, environment=args.env) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/setup.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e52dac3d54d9536c7fce08f73a31e6843a46b65d --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/UNet3D/runtime/setup.py @@ -0,0 +1,126 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - script migration to Tensorflow 2.x version +# - added HPU custom setup functions +# - added possibility to handle non-HPU runs +# - added possibility to log data from every horovod worker +# - added possibility to disable checkpoint saving +# - moved horovod import under use_horovod condition so that the user is not required to install this +# library when the model is being run on a single card +# - stopped overriding model_dir path with additional `model_checkpoint` directory + +import os + +import dllogger as logger +import tensorflow as tf +from dllogger import StdOutBackend, Verbosity, JSONStreamBackend + +from model.model_fn import unet_3d + + +def setup_horovod(params): + params.worker_id = 0 + params.num_workers = 1 + if params.use_horovod: + import horovod.tensorflow as hvd + if hvd is None: + raise RuntimeError( + "Problem encountered during Horovod import. Please make sure that habana-horovod package is installed.") + hvd.init() + if params.no_hpu: + # Horovod on GPU + os.environ['CUDA_VISIBLE_DEVICES'] = str(hvd.local_rank()) + params.worker_id = hvd.rank() + params.num_workers = hvd.size() + if params.log_all_workers: + params.log_dir = os.path.join(params.log_dir, f'worker_{params.worker_id}') + params.model_dir = os.path.join(params.model_dir, f'worker_{params.worker_id}') + + return params + + +def set_flags(params): + if params.tf_verbosity: + os.environ['TF_CPP_MIN_LOG_LEVEL'] = params.tf_verbosity + + if params.no_hpu: + os.environ['CUDA_CACHE_DISABLE'] = '1' + os.environ['HOROVOD_GPU_ALLREDUCE'] = 'NCCL' + os.environ['TF_GPU_THREAD_MODE'] = 'gpu_private' + os.environ['TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT'] = '0' + os.environ['TF_ADJUST_HUE_FUSED'] = '1' + os.environ['TF_ADJUST_SATURATION_FUSED'] = '1' + os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1' + os.environ['TF_SYNC_ON_FINISH'] = '0' + else: + from habana_frameworks.tensorflow import load_habana_module + load_habana_module() + if params.dtype == 'bf16': + os.environ['TF_BF16_CONVERSION'] = params.bf16_config_path + + +def prepare_model_dir(params): + model_dir = params.model_dir + model_dir = model_dir if ((params.worker_id == 0 or params.log_all_workers) and not params.benchmark) else None + if model_dir is not None: + os.makedirs(model_dir, exist_ok=True) + if ('train' in params.exec_mode) and (not params.resume_training): + os.system('rm -rf {}/*'.format(model_dir)) + + return model_dir + + +def build_estimator(params, model_dir): + config = tf.compat.v1.ConfigProto(gpu_options=tf.compat.v1.GPUOptions(), allow_soft_placement=True) + + if params.use_xla: + config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 + + config.gpu_options.allow_growth = True + config.gpu_options.visible_device_list = os.getenv('CUDA_VISIBLE_DEVICES', '0') + + if params.use_amp: + config.graph_options.rewrite_options.auto_mixed_precision = 1 + + checkpoint_steps = (params.max_steps // params.num_workers) if params.worker_id == 0 else None + checkpoint_steps = checkpoint_steps if not (params.benchmark or params.disable_ckpt_saving) else None + + run_config = tf.estimator.RunConfig( + save_summary_steps=params.max_steps, + session_config=config, + save_checkpoints_steps=checkpoint_steps, + save_checkpoints_secs=None, + keep_checkpoint_max=1) + + return tf.estimator.Estimator( + model_fn=unet_3d, + model_dir=model_dir, + config=run_config, + params=params) + + +def get_logger(params): + backends = [] + if params.worker_id == 0 or params.log_all_workers: + backends += [StdOutBackend(Verbosity.VERBOSE)] + if params.log_dir: + os.makedirs(params.log_dir, exist_ok=True) + log_file = f"{params.log_dir}/log.json" + backends += [JSONStreamBackend(Verbosity.VERBOSE, log_file)] + logger.init(backends=backends) + return logger diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/.gitignore b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..13aa18b20a3cb69eefbd9f2870cbeb98dfe13bae --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/.gitignore @@ -0,0 +1,2 @@ +data/* +logs/* diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/LICENSE b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..78aafbf820598ae1d596af2a403b642f81f05814 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2021 Habana Labs, Ltd. an Intel Company + +BSD 3-Clause License + +Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/NOTICE b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..60eda329d63bd88524ff6e59eceedfadd3ef992a --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/NOTICE @@ -0,0 +1,17 @@ +Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Ths repository includes software from: +* TensorFlow, (https://github.com/tensorflow/tensorflow) licensed + under the Apache License, Version 2.0 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/README.md b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/README.md new file mode 100644 index 0000000000000000000000000000000000000000..677612a0b060cc38dd2b8f5f71f5721385e758db --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/README.md @@ -0,0 +1,300 @@ +# UNet2D for TensorFlow 2 + +This directory provides a script and recipe to train a UNet2D Medical model to achieve state of the art accuracy, and is tested and maintained by Habana. +For further information on performance, refer to [Habana Model Performance Data page](https://developer.habana.ai/resources/habana-training-models/#performance). + +For further information on training deep learning models using Gaudi, refer to [developer.habana.ai](https://developer.habana.ai/resources/). + +## Table of Contents + +* [Model-References](../../../README.md) +* [Model overview](#model-overview) +* [Setup](#setup) +* [Training and Examples](#training-and-examples) +* [Advanced](#Advanced) +* [Supported Configuration](#supported-configuration) +* [Changelog](#changelog) + +## Model Overview + +This directory describes how to train UNet Medical model for 2D Segmentation on Intel® Gaudi® AI Accelerator (HPU). The UNet Medical model is a modified version of the original model located in [NVIDIA UNet Medical Image Segmentation for TensorFlow 2.x](https://github.com/NVIDIA/DeepLearningExamples/tree/master/TensorFlow2/Segmentation/UNet_Medical). The implementation provided covers UNet model as described in the original [UNet: Convolutional Networks for Biomedical Image Segmentation](https://arxiv.org/abs/1505.04597) paper. + +### Model Architecture + +The UNet model allows seamless segmentation of 2D images with high accuracy and performance, and can be adapted to solve many different segmentation issues. + +The following figure shows the construction of the UNet model and its components. A UNet is composed of a contractive and an expanding path, that aims at building a bottleneck in its centermost part through a combination of convolution and pooling operations. After this bottleneck, the image is reconstructed through a combination of convolutions and upsampling. Skip connections are added with the goal of helping the backward flow of gradients in order to improve the training. + +![UNet](images/unet.png) +Figure 1. The architecture of a UNet model from [UNet: Convolutional Networks for Biomedical Image Segmentation paper](https://arxiv.org/abs/1505.04597). + +### Model Changes + +The below lists the major changes applied to the model: + +* Removed GPU specific configurations. +* Changed some scripts to run the model on Gaudi. This includes loading Habana TensorFlow modules and using multiple Gaudi cards helpers. +* Added support for using bfloat16 precision instead of float16. +* Replaced tf.keras.activations.softmax with tf.nn.softmax due to performance issues described in https://github.com/tensorflow/tensorflow/pull/47572; +* Added further TensorBoard and performance logging options. +* Removed GPU specific files (examples/*, Dockerfile etc.) and some unused codes. +* Enabled the tf.data.experimental.prefetch_to_device for HPU device to improve performance. + +### Default Configuration + +- Execution mode: train and evaluate +- Batch size: 8 +- Data type: bfloat16 +- Maximum number of steps: 6400 +- Weight decay: 0.0005 +- Learning rate: 0.0001 +- Number of Horovod workers (HPUs): 1 +- Data augmentation: True +- Cross-validation: disabled +- Using XLA: False +- Logging losses and performance every N steps: 100 + +## Setup + +Please follow the instructions provided in the [Gaudi Installation Guide](https://docs.habana.ai/en/latest/Installation_Guide/GAUDI_Installation_Guide.html) to set up the environment including the `$PYTHON` environment variable. To achieve the best performance, please follow the methods outlined in the [Optimizing Training Platform guide](https://docs.habana.ai/en/latest/TensorFlow/Model_Optimization_TensorFlow/Optimization_Training_Platform.html). +The guides will walk you through the process of setting up your system to run the model on Gaudi. + + +### Clone Habana Model-References + +In the docker container, clone this repository and switch to the branch that matches your SynapseAI version. You can run the [`hl-smi`](https://docs.habana.ai/en/latest/Management_and_Monitoring/System_Management_Tools_Guide/System_Management_Tools.html#hl-smi-utility-options) utility to determine the SynapseAI version. + +```bash +git clone -b [SynapseAI version] https://github.com/HabanaAI/Model-References /root/Model-References +``` + +**Note:** If Model-References repository path is not in the PYTHONPATH, make sure you update it: +```bash +export PYTHONPATH=$PYTHONPATH:/root/to/Model-References +``` + +### Install Model Requirements + +1. In the docker container, go to the UNet2D directory: + +```bash +cd /root/Model-References/TensorFlow/computer_vision/Unet2D +``` +2. Install the required packages using pip: + +```bash +$PYTHON -m pip install -r requirements.txt +``` + +### Download the Dataset + +Download the [EM segmentation challenge dataset](http://brainiac2.mit.edu/isbi_challenge/home)*: + +```bash + $PYTHON download_dataset.py +``` + +By default, it will download the dataset to `./data` path. Use `--data_dir ` to change it. + +**NOTE:** If the original location is unavailable, the dataset is also mirrored on [Kaggle](https://www.kaggle.com/soumikrakshit/isbi-challenge-dataset). Registration is required. + +## Training and Examples + +### Single Card and Multi-Card Training Examples + +**Run training on 1 HPU:** + +```bash +$PYTHON unet2d.py --data_dir --batch_size \ +--dtype --model_dir --fold +``` + +- 1 HPU training with batch size 8, bfloat16 precision and fold 0: + + ```bash + $PYTHON unet2d.py --data_dir /data/tensorflow/unet2d --batch_size 8 --dtype bf16 --model_dir /tmp/unet2d_1_hpu --fold 0 --tensorboard_logging + ``` + +- 1 HPU training with batch size 8, float32 precision and fold 0: + + ```bash + $PYTHON unet2d.py --data_dir /data/tensorflow/unet2d --batch_size 8 --dtype fp32 --model_dir /tmp/unet2d_1_hpu --fold 0 --tensorboard_logging + ``` + +**Run training on 8 HPUs:** + +Running the script via mpirun requires`--use_horovod` argument, and the mpirun prefix with several parameters. + +**NOTE:** mpirun map-by PE attribute value may vary on your setup. For the recommended calculation, refer to the instructions detailed in [mpirun Configuration](https://docs.habana.ai/en/latest/TensorFlow/Tensorflow_Scaling_Guide/Horovod_Scaling/index.html#mpirun-configuration). + +```bash +mpirun --allow-run-as-root --bind-to core --map-by socket:PE=6 -np 8 \ + $PYTHON unet2d.py --data_dir --batch_size \ + --dtype --model_dir --fold --use_horovod +``` +- 8 HPUs training with batch size 8, bfloat16 precision and fold 0: + + ```bash + mpirun --allow-run-as-root --tag-output --merge-stderr-to-stdout --bind-to core --map-by socket:PE=6 -np 8 \ + $PYTHON unet2d.py --data_dir /data/tensorflow/unet2d/ --batch_size 8 \ + --dtype bf16 --model_dir /tmp/unet2d_8_hpus --fold 0 --tensorboard_logging --log_all_workers --use_horovod + ``` +- 8 HPUs training with batch size 8, float32 precision and fold 0: + + ```bash + mpirun --allow-run-as-root --tag-output --merge-stderr-to-stdout --bind-to core --map-by socket:PE=6 -np 8 \ + $PYTHON unet2d.py --data_dir /data/tensorflow/unet2d/ --batch_size 8 \ + --dtype fp32 --model_dir /tmp/unet2d_8_hpus --fold 0 --tensorboard_logging --log_all_workers --use_horovod + ``` + +**Run 5-fold Cross-Validation and compute average dice score:** + +All the commands described above train and evaluate the model on the dataset with fold 0. To perform 5-fold-cross-validation on the dataset and compute average dice score across 5 folds, you can execute training the script 5 times and calculate the average dice score manually or run bash script `train_and_evaluate.sh`: + +```bash +bash train_and_evaluate.sh +``` + +- 1 HPU 5-fold-cross-validation training with batch size 8 and bfloat16 precision: + + ```bash + bash train_and_evaluate.sh /data/tensorflow/unet2d/ /tmp/unet2d_1_hpu 8 bf16 1 + ``` + +- 1 HPU 5-fold-cross-validation training with batch size 8 and float32 precision: + + ```bash + bash train_and_evaluate.sh /data/tensorflow/unet2d/ /tmp/unet2d_1_hpu 8 fp32 1 + ``` + +- 8 HPUs 5-fold-cross-validation training with batch size 8 and bfloat16 precision: + + ```bash + bash train_and_evaluate.sh /data/tensorflow/unet2d/ /tmp/unet2d_8_hpus 8 bf16 8 + ``` + +- 8 HPUs 5-fold-cross-validation training with batch size 8 and float32 precision: + + ```bash + bash train_and_evaluate.sh /data/tensorflow/unet2d/ /tmp/unet2d_8_hpus 8 fp32 8 + ``` + +## Advanced + +The following sections provide further details on the scripts in the directory, available parameters and command-line options. + +### Scripts Definitions + +* `unet2d.py`: The training script of the UNet2D model, entry point to the application. +* `download_dataset.py`: Script for downloading dataset. +* `data_loading/data_loader.py`: Implements the data loading and augmentation. +* `model/layers.py`: Defines the different blocks that are used to assemble UNet. +* `model/unet.py`: Defines the model architecture using the blocks from the `layers.py` script. +* `runtime/arguments.py`: Implements the command-line arguments parsing. +* `runtime/losses.py`: Implements the losses used during training and evaluation. +* `runtime/run.py`: Implements the logic for training, evaluation, and inference. +* `runtime/parse_results.py`: Implements the intermediate results parsing. +* `runtime/setup.py`: Implements helper setup functions. +* `train_and_evaluate.sh`: Runs the topology training and evaluates the model for 5 cross-validation. + +Other folders included in the root directory are: +* `images/`: Contains a model diagram. + +### Parameters + +The complete list of the available parameters for the `unet2d.py` script contains: +* `--exec_mode`: Select the execution mode to run the model (default: `train_and_evaluate`). Modes available: + * `train` - trains model from scratch. + * `evaluate` - loads checkpoint from `--model_dir` (if available) and performs evaluation on validation subset (requires `--fold` other than `None`). + * `train_and_evaluate` - trains model from scratch and performs validation at the end (requires `--fold` other than `None`). + * `predict` - loads checkpoint from `--model_dir` (if available) and runs inference on the test set. Stores the results in `--model_dir` directory. + * `train_and_predict` - trains model from scratch and performs inference. +* `--model_dir`: Set the output directory for information related to the model (default: `/tmp/unet2d`). +* `--data_dir`: Set the input directory containing the dataset (default: `None`). +* `--log_dir`: Set the output directory for logs (default: `/tmp/unet2d`). +* `--batch_size`: Size of each minibatch per HPU (default: `8`). +* `--dtype`: Set precision to be used in model: fp32/bf16 (default: `bf16`). +* `--fold`: Selected fold for cross-validation (default: `None`). +* `--max_steps`: Maximum number of steps (batches) for training (default: `6400`). +* `--log_every`: Log data every n steps (default: `100`). +* `--evaluate_every`: Evaluate every n steps (default: `0` - evaluate once at the end). +* `--warmup_steps`: Number of steps to skip (default: `200`). First iterations are usually much slower since the graph is being constructed. Skipping the initial iterations is required for a fair performance assessment. +* `--weight_decay`: Weight decay coefficient (default: `0.0005`). +* `--learning_rate`: Model’s learning rate (default: `0.0001`). +* `--seed`: Set random seed for reproducibility (default: `123`). +* `--dump_config`: Directory for dumping debug traces (default: `None`). +* `--augment`: Enable data augmentation (default: `True`). +* `--benchmark`: Enable performance benchmarking (default: `False`). If the flag is set, the script runs in a benchmark mode - each iteration is timed and the performance result (in images per second) is printed at the end. Works for both `train` and `predict` execution modes. +* `--xla`: Enable accelerated linear algebra optimization (default: `False`). +* `--resume_training`: Resume training from a checkpoint (default: `False`). +* `--no_hpu`: Disable execution on HPU, train on CPU (default: `False`). +* `--synth_data`: Use deterministic and synthetic data (default: `False`). +* `--disable_ckpt_saving`: Disables saving checkpoints (default: `False`). +* `--use_horovod`: Enable horovod usage (default: `False`). +* `--tensorboard_logging`: Enable tensorboard logging (default: `False`). +* `--log_all_workers`: Enable logging data for every horovod worker in a separate directory named `worker_N` (default: False). +* `--bf16_config_path`: Path to custom mixed precision config to use given in JSON format. +* `--tf_verbosity`: If set changes logging level from Tensorflow: + * `0` - all messages are logged (default behavior); + * `1` - INFO messages are not printed; + * `2` - INFO and WARNING messages are not printed; + * `3` - INFO, WARNING, and ERROR messages are not printed. + +### Command-line Options + +To see the full list of the available options and their descriptions, use the `-h` or `--help` command-line option, for example: + +```bash +$PYTHON unet2d.py --help +``` + +## Supported Configuration + +| Validated on | SynapseAI Version | TensorFlow Version(s) | Mode | +|:------:|:-----------------:|:-----:|:----------:| +| Gaudi | 1.14.0 | 2.15.0 | Training | +| Gaudi2 | 1.13.0 | 2.13.1 | Training | + +## Changelog +### 1.14.0 +- Added time to train and throughput logs at the end of the training +- Changed benchmark mode to run the same amout of steps as non-benchmark mode + +### 1.12.0 +- Removed limited number of nodes inserted into a single HPU graph. + +### 1.11.0 + +- Limited number of nodes inserted into a single HPU graph to improve model performance. + +### 1.10.0 + +- Changed default seed value for higher accuracy. + +### 1.7.0 + +- Added TimeToTrain callback for dumping evaluation timestamps + +### 1.6.0 + +- Model enabled on Gaudi2 with the same config as first-gen Gaudi. +- Added num_parallel_calls for data loader to improve performance on Gaudi2. + +### 1.4.0 + +- Enabled tf.data.experimental.prefetch_to_device for HPU device for better performance. +- Changed `python` or `python3` to `$PYTHON` to execute correct version based on environment setup. +- Added support to import horovod-fork package directly instead of using Model-References' TensorFlow.common.horovod_helpers. Wrapped horovod import with a try-catch block so that installing the library is not required when the model is running on a single card. +- Replaced references to custom demo script by community entry points in the README and +`train_and_evaluate.sh`. + +### 1.3.0 + +- Moved BF16 config json file from TensorFlow/common/ to model's directory. +- Updated the requirements.txt + +### 1.2.0 + +- Removed the setting number of parallel calls in dataloader mapping to improve performance for different TensorFlow versions. +- Updated requirements.txt + diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/bf16_config/unet.json b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/bf16_config/unet.json new file mode 100644 index 0000000000000000000000000000000000000000..46e81b0acfe7f97ecb390e16a2817dec8137e25e --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/bf16_config/unet.json @@ -0,0 +1,85 @@ +{ + "allowlist": [ + "BatchMatMul", + "BatchMatMulV2", + "BiasAdd", + "BiasAddGrad", + "Conv2D", + "Conv2DBackpropFilter", + "Conv2DBackpropInput", + "Conv3D", + "Conv3DBackpropFilter", + "Conv3DBackpropFilterV2", + "Conv3DBackpropInput", + "Conv3DBackpropInputV2", + "HabanaConv2DWithPadding", + "HabanaConv2DWithPaddingBackpropFilter", + "HabanaConv2DWithPaddingBackpropInput", + "HabanaInstanceNorm", + "HabanaInstanceNormGrad", + "LeakyRelu", + "LeakyReluGrad", + "MatMul", + "MaxPool", + "MaxPoolV2", + "MaxPoolGrad", + "MaxPoolGradV2", + "Relu", + "ReluGrad" + ], + "conditional_list": [ + "Add", + "AddN", + "AddV2", + "CollectiveReduceV2", + "CollectiveReduceV3", + "Concat", + "ConcatV2", + "Equal", + "Exp", + "GreaterEqual", + "HabanaClampBwd", + "HabanaClampFwd", + "HabanaDropout", + "HabanaDropoutGrad", + "HorovodAllgather", + "HorovodAllreduce", + "HpuCollectiveGather", + "HpuCollectiveGatherV2", + "HpuCollectiveReduce", + "Identity", + "Log1p", + "L2Loss", + "Max", + "Mean", + "Mul", + "Neg", + "Pad", + "PadV2", + "Pow", + "RealDiv", + "Reciprocal", + "Reshape", + "ResizeNearestNeighbor", + "ResizeNearestNeighborGrad", + "Select", + "Shape", + "ShapeN", + "Slice", + "Square", + "Tile" + ], + "strict_conditional_list": [], + "non_convertible_exceptions": [ + [ + ".*KEEP_FP32_PRECISION.*", + "" + ] + ], + "convertible_exceptions": [ + [ + ".*FORCE_BF16_PRECISION.*", + "" + ] + ] +} \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/data_loading/data_loader.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/data_loading/data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..dd3993424d2554ee10fa2fb776172f6782dd52da --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/data_loading/data_loader.py @@ -0,0 +1,249 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2020-2022 Habana Labs, Ltd. an Intel Company +# +# Changes: +# - gpu_id, num_gpus replaced with hpu_id, num_hpus +# - removed setting number of parallel calls in dataloader mapping +# in order to improve performance for different TF versions +# - enable experimental.prefetch_to_device functionality to improve the performance +# - add num_parallel_calls to improve the performance on Gaudi2 + +""" Dataset class encapsulates the data loading""" +import os +from collections import deque + +import numpy as np +import tensorflow as tf +from PIL import Image, ImageSequence + + +class Dataset: + """Load, separate and prepare the data for training and prediction""" + + def __init__(self, data_dir, batch_size, fold, augment=False, hpu_id=0, num_hpus=1, seed=0, gaudi_type=None): + if not os.path.exists(data_dir): + raise FileNotFoundError('Cannot find data dir: {}'.format(data_dir)) + self._data_dir = data_dir + self._batch_size = batch_size + self._augment = augment + self._seed = seed + + images = self._load_multipage_tiff(os.path.join(self._data_dir, 'train-volume.tif')) + masks = self._load_multipage_tiff(os.path.join(self._data_dir, 'train-labels.tif')) + self._test_images = \ + self._load_multipage_tiff(os.path.join(self._data_dir, 'test-volume.tif')) + + train_indices, val_indices = self._get_val_train_indices(len(images), fold) + self._train_images = images[train_indices] + self._train_masks = masks[train_indices] + self._val_images = images[val_indices] + self._val_masks = masks[val_indices] + + self._num_hpus = num_hpus + self._hpu_id = hpu_id + + self._deterministic, self._num_parallel_calls = None, None + if gaudi_type is not None and 'GAUDI2' in gaudi_type: + self._deterministic = self._seed is not None + self._num_parallel_calls = tf.data.AUTOTUNE + + @property + def train_size(self): + return len(self._train_images) + + @property + def eval_size(self): + return len(self._val_images) + + @property + def test_size(self): + return len(self._test_images) + + def _load_multipage_tiff(self, path): + """Load tiff images containing many images in the channel dimension""" + return np.array([np.array(p) for p in ImageSequence.Iterator(Image.open(path))]) + + def _get_val_train_indices(self, length, fold, ratio=0.8): + assert 0 < ratio <= 1, "Train/total data ratio must be in range (0.0, 1.0]" + np.random.seed(self._seed) + indices = np.arange(0, length, 1, dtype=int) + np.random.shuffle(indices) + if fold is not None: + indices = deque(indices) + indices.rotate(fold * int((1.0 - ratio) * length)) + indices = np.array(indices) + train_indices = indices[:int(ratio * len(indices))] + val_indices = indices[int(ratio * len(indices)):] + else: + train_indices = indices + val_indices = [] + return train_indices, val_indices + + def _normalize_inputs(self, inputs): + """Normalize inputs""" + inputs = tf.expand_dims(tf.cast(inputs, tf.float32), -1) + + # Center around zero + inputs = tf.divide(inputs, 127.5) - 1 + # Resize to match output size + inputs = tf.image.resize(inputs, (388, 388)) + + return tf.image.resize_with_crop_or_pad(inputs, 572, 572) + + def _normalize_labels(self, labels): + """Normalize labels""" + labels = tf.expand_dims(tf.cast(labels, tf.float32), -1) + labels = tf.divide(labels, 255) + + # Resize to match output size + labels = tf.image.resize(labels, (388, 388)) + labels = tf.image.resize_with_crop_or_pad(labels, 572, 572) + + cond = tf.less(labels, 0.5 * tf.ones(tf.shape(input=labels))) + labels = tf.where(cond, tf.zeros(tf.shape(input=labels)), tf.ones(tf.shape(input=labels))) + + return tf.one_hot(tf.squeeze(tf.cast(labels, tf.int32)), 2) + + @tf.function + def _preproc_samples(self, inputs, labels, seed=None): + """Preprocess samples and perform random augmentations""" + inputs = self._normalize_inputs(inputs) + labels = self._normalize_labels(labels) + + if self._augment: + # Horizontal flip + h_flip = tf.random.uniform([], seed=seed) > 0.5 + inputs = tf.cond(pred=h_flip, true_fn=lambda: tf.image.flip_left_right(inputs), false_fn=lambda: inputs) + labels = tf.cond(pred=h_flip, true_fn=lambda: tf.image.flip_left_right(labels), false_fn=lambda: labels) + + # Vertical flip + v_flip = tf.random.uniform([], seed=seed) > 0.5 + inputs = tf.cond(pred=v_flip, true_fn=lambda: tf.image.flip_up_down(inputs), false_fn=lambda: inputs) + labels = tf.cond(pred=v_flip, true_fn=lambda: tf.image.flip_up_down(labels), false_fn=lambda: labels) + + # Prepare for batched transforms + inputs = tf.expand_dims(inputs, 0) + labels = tf.expand_dims(labels, 0) + + # Random crop and resize + left = tf.random.uniform([], seed=seed) * 0.3 + right = 1 - tf.random.uniform([], seed=seed) * 0.3 + top = tf.random.uniform([], seed=seed) * 0.3 + bottom = 1 - tf.random.uniform([], seed=seed) * 0.3 + + inputs = tf.image.crop_and_resize(inputs, [[top, left, bottom, right]], [0], (572, 572)) + labels = tf.image.crop_and_resize(labels, [[top, left, bottom, right]], [0], (572, 572)) + + # Gray value variations + + # Adjust brightness and keep values in range + inputs = tf.image.random_brightness(inputs, max_delta=0.2, seed=seed) + inputs = tf.clip_by_value(inputs, clip_value_min=-1, clip_value_max=1) + + inputs = tf.squeeze(inputs, 0) + labels = tf.squeeze(labels, 0) + + # Bring back labels to network's output size and remove interpolation artifacts + labels = tf.image.resize_with_crop_or_pad(labels, target_width=388, target_height=388) + cond = tf.less(labels, 0.5 * tf.ones(tf.shape(input=labels))) + labels = tf.where(cond, tf.zeros(tf.shape(input=labels)), tf.ones(tf.shape(input=labels))) + + return inputs, labels + + @tf.function + def _preproc_eval_samples(self, inputs, labels): + """Preprocess samples and perform random augmentations""" + inputs = self._normalize_inputs(inputs) + labels = self._normalize_labels(labels) + + # Bring back labels to network's output size and remove interpolation artifacts + labels = tf.image.resize_with_crop_or_pad(labels, target_width=388, target_height=388) + cond = tf.less(labels, 0.5 * tf.ones(tf.shape(input=labels))) + labels = tf.where(cond, tf.zeros(tf.shape(input=labels)), tf.ones(tf.shape(input=labels))) + + return (inputs, labels) + + def prefetch(self, dataset, buffer_size): + """Dataset prefetching function""" + if len(tf.config.list_logical_devices('HPU')) > 0: + device = tf.config.list_logical_devices('HPU')[0].name + with tf.device(device): + dataset = dataset.apply(tf.data.experimental.prefetch_to_device(device)) + else: + dataset = dataset.prefetch(buffer_size) + + return dataset + + def train_fn(self, drop_remainder=False): + """Input function for training""" + dataset = tf.data.Dataset.from_tensor_slices( + (self._train_images, self._train_masks)) + dataset = dataset.shard(self._num_hpus, self._hpu_id) + dataset = dataset.repeat() + dataset = dataset.shuffle(self._batch_size * 3) + + # Starting with Gaudi2 device, data augmentation is performed in parallel. + # To ensure determinism, the seed param must be passed to the preprocessing method. + # Sequential execution on first-gen Gaudi does not require this. + seed = self._seed if self._num_parallel_calls is not None else None + dataset = dataset.map(lambda images, labels: self._preproc_samples(images, labels, seed), + num_parallel_calls=self._num_parallel_calls, deterministic=self._deterministic) + dataset = dataset.batch(self._batch_size, drop_remainder=drop_remainder, + num_parallel_calls=self._num_parallel_calls, deterministic=self._deterministic) + dataset = self.prefetch(dataset, self._batch_size) + + return dataset + + def eval_fn(self, count, drop_remainder=False): + """Input function for validation""" + dataset = tf.data.Dataset.from_tensor_slices( + (self._val_images, self._val_masks)) + dataset = dataset.repeat(count=count) + dataset = dataset.map(self._preproc_eval_samples, + num_parallel_calls=self._num_parallel_calls, deterministic=self._deterministic) + dataset = dataset.batch(self._batch_size, drop_remainder=drop_remainder, + num_parallel_calls=self._num_parallel_calls, deterministic=self._deterministic) + dataset = self.prefetch(dataset, self._batch_size) + + return dataset + + def test_fn(self, count, drop_remainder=False): + """Input function for testing""" + dataset = tf.data.Dataset.from_tensor_slices( + self._test_images) + dataset = dataset.repeat(count=count) + dataset = dataset.map(self._normalize_inputs) + dataset = dataset.batch(self._batch_size, drop_remainder=drop_remainder) + dataset = self.prefetch(dataset, self._batch_size) + + return dataset + + def synth_fn(self): + """Synthetic data function for testing""" + inputs = tf.random.truncated_normal((572, 572, 1), dtype=tf.float32, mean=127.5, stddev=1, seed=self._seed, + name='synth_inputs') + masks = tf.random.truncated_normal((388, 388, 2), dtype=tf.float32, mean=0.01, stddev=0.1, seed=self._seed, + name='synth_masks') + + dataset = tf.data.Dataset.from_tensors((inputs, masks)) + + dataset = dataset.cache() + dataset = dataset.repeat() + dataset = dataset.batch(self._batch_size) + + dataset = self.prefetch(dataset, tf.data.experimental.AUTOTUNE) + + return dataset diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/download_dataset.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/download_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..1c1b7d70d827904af1b4a61ebfbb07c792d10a30 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/download_dataset.py @@ -0,0 +1,41 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import os + + +PARSER = argparse.ArgumentParser(description="U-Net medical") + +PARSER.add_argument('--data_dir', + type=str, + default='./data', + help="""Directory where to download the dataset""") + + +def main(): + FLAGS = PARSER.parse_args() + + if not os.path.exists(FLAGS.data_dir): + os.makedirs(FLAGS.data_dir) + + os.system('wget http://brainiac2.mit.edu/isbi_challenge/sites/default/files/train-volume.tif -P {}'.format(FLAGS.data_dir)) + os.system('wget http://brainiac2.mit.edu/isbi_challenge/sites/default/files/train-labels.tif -P {}'.format(FLAGS.data_dir)) + os.system('wget http://brainiac2.mit.edu/isbi_challenge/sites/default/files/test-volume.tif -P {}'.format(FLAGS.data_dir)) + + print("Finished downloading files for U-Net medical to {}".format(FLAGS.data_dir)) + + +if __name__ == '__main__': + main() diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/model/layers.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/model/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..2f59adac31503f7f48168bceeada016cb09a9aa9 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/model/layers.py @@ -0,0 +1,206 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# -*- coding: utf-8 -*- +""" Contains a set of utilities that allow building the UNet model""" + +import tensorflow as tf + + +def _crop_and_concat(inputs, residual_input): + """ Perform a central crop of ``residual_input`` and concatenate to ``inputs`` + + Args: + inputs (tf.Tensor): Tensor with input + residual_input (tf.Tensor): Residual input + + Return: + Concatenated tf.Tensor with the size of ``inputs`` + + """ + factor = inputs.shape[1] / residual_input.shape[1] + return tf.concat([inputs, tf.image.central_crop(residual_input, factor)], axis=-1) + + +class InputBlock(tf.keras.Model): + def __init__(self, filters, seed=None): + """ UNet input block + + Perform two unpadded convolutions with a specified number of filters and downsample + through max-pooling. First convolution + + Args: + filters (int): Number of filters in convolution + """ + super().__init__(self) + self.initializer = tf.keras.initializers.GlorotUniform(seed=seed) + with tf.name_scope('input_block'): + self.conv1 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.conv2 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.maxpool = tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=2) + + def call(self, inputs): + out = self.conv1(inputs) + out = self.conv2(out) + mp = self.maxpool(out) + return mp, out + + +class DownsampleBlock(tf.keras.Model): + def __init__(self, filters, idx, seed=None): + """ UNet downsample block + + Perform two unpadded convolutions with a specified number of filters and downsample + through max-pooling + + Args: + filters (int): Number of filters in convolution + idx (int): Index of block + + Return: + Tuple of convolved ``inputs`` after and before downsampling + + """ + super().__init__(self) + self.initializer = tf.keras.initializers.GlorotUniform(seed=seed) + with tf.name_scope('downsample_block_{}'.format(idx)): + self.conv1 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.conv2 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.maxpool = tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=2) + + def call(self, inputs): + out = self.conv1(inputs) + out = self.conv2(out) + mp = self.maxpool(out) + return mp, out + + +class BottleneckBlock(tf.keras.Model): + def __init__(self, filters, seed=None): + """ UNet central block + + Perform two unpadded convolutions with a specified number of filters and upsample + including dropout before upsampling for training + + Args: + filters (int): Number of filters in convolution + """ + super().__init__(self) + self.initializer = tf.keras.initializers.GlorotUniform(seed=seed) + with tf.name_scope('bottleneck_block'): + self.conv1 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.conv2 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.dropout = tf.keras.layers.Dropout(rate=0.5) + self.conv_transpose = tf.keras.layers.Conv2DTranspose(filters=filters // 2, + kernel_size=(3, 3), + strides=(2, 2), + padding='same', + activation=tf.nn.relu, + kernel_initializer=self.initializer) + + def call(self, inputs, training): + out = self.conv1(inputs) + out = self.conv2(out) + out = self.dropout(out, training=training) + out = self.conv_transpose(out) + return out + + +class UpsampleBlock(tf.keras.Model): + def __init__(self, filters, idx, seed=None): + """ UNet upsample block + + Perform two unpadded convolutions with a specified number of filters and upsample + + Args: + filters (int): Number of filters in convolution + idx (int): Index of block + """ + super().__init__(self) + self.initializer = tf.keras.initializers.GlorotUniform(seed=seed) + with tf.name_scope('upsample_block_{}'.format(idx)): + self.conv1 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.conv2 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.conv_transpose = tf.keras.layers.Conv2DTranspose(filters=filters // 2, + kernel_size=(3, 3), + strides=(2, 2), + padding='same', + activation=tf.nn.relu, + kernel_initializer=self.initializer) + + def call(self, inputs, residual_input): + out = _crop_and_concat(inputs, residual_input) + out = self.conv1(out) + out = self.conv2(out) + out = self.conv_transpose(out) + return out + + +class OutputBlock(tf.keras.Model): + def __init__(self, filters, n_classes, seed=None): + """ UNet output block + + Perform three unpadded convolutions, the last one with the same number + of channels as classes we want to classify + + Args: + filters (int): Number of filters in convolution + n_classes (int): Number of output classes + """ + super().__init__(self) + self.initializer = tf.keras.initializers.GlorotUniform(seed=seed) + with tf.name_scope('output_block'): + self.conv1 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.conv2 = tf.keras.layers.Conv2D(filters=filters, + kernel_size=(3, 3), + activation=tf.nn.relu, + kernel_initializer=self.initializer) + self.conv3 = tf.keras.layers.Conv2D(filters=n_classes, + kernel_size=(1, 1), + activation=None, + kernel_initializer=self.initializer) + + def call(self, inputs, residual_input): + out = _crop_and_concat(inputs, residual_input) + out = self.conv1(out) + out = self.conv2(out) + out = self.conv3(out) + return out diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/model/unet.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/model/unet.py new file mode 100644 index 0000000000000000000000000000000000000000..db4d22761b491698b7783dbbd4920f2f7a3b970c --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/model/unet.py @@ -0,0 +1,61 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" Model construction utils + +This module provides a convenient way to create different topologies +based around UNet. + +""" + +import tensorflow as tf + +from model.layers import InputBlock, DownsampleBlock, BottleneckBlock, UpsampleBlock, OutputBlock + + +class Unet(tf.keras.Model): + """ U-Net: Convolutional Networks for Biomedical Image Segmentation + + Source: + https://arxiv.org/pdf/1505.04597 + + """ + def __init__(self, seed=None): + super().__init__(self) + self.input_block = InputBlock(filters=64, seed=seed) + self.bottleneck = BottleneckBlock(filters=1024, seed=seed) + self.output_block = OutputBlock(filters=64, n_classes=2, seed=seed) + + self.down_blocks = [DownsampleBlock(filters, idx, seed=seed) + for idx, filters in enumerate([128, 256, 512])] + + self.up_blocks = [UpsampleBlock(filters, idx, seed=seed) + for idx, filters in enumerate([512, 256, 128])] + + def call(self, x, training=True): + skip_connections = [] + out, residual = self.input_block(x) + skip_connections.append(residual) + + for down_block in self.down_blocks: + out, residual = down_block(out) + skip_connections.append(residual) + + out = self.bottleneck(out, training) + + for up_block in self.up_blocks: + out = up_block(out, skip_connections.pop()) + + out = self.output_block(out, skip_connections.pop()) + return out diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/requirements.txt b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a40c7e5ffab66f1b3d5e9e3c6854289da45d5f2 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/requirements.txt @@ -0,0 +1,5 @@ +git+https://github.com/nvidia/dllogger@26a0f8f1958de2c0c460925ff6102a4d2486d6cc#egg=dllogger +munch==2.5.0 +pillow==10.2.0 +PyYAML==6.0.0 +numpy==1.24.0 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/arguments.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..d249fb486581c9f36c0d9db13239640ae913764e --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/arguments.py @@ -0,0 +1,214 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2020-2023 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - default values for model_dir, log_dir, batch_size, max_steps, augment +# - removed use_amp, use_trt flags +# - added dtype, hvd_workers, dump_config, no_hpu, synth_data, disable_ckpt_saving, +# use_horovod, tensorboard_logging, bf16_config_path, tf_verbosity, +# kubernetes_run options +# - SmartFormatter for textwrapping help message +# - added gaudi_type param +# - changed seed default value + +"""Command line argument parsing""" + +import os +import argparse +from pathlib import Path + +from munch import Munch + + +class SmartFormatter(argparse.ArgumentDefaultsHelpFormatter): + ''' + Custom Help Formatter used to split help text when '\n' was + inserted in it. + ''' + def _fill_text(self, text, width, indent): + return ''.join(line for line in text.splitlines(keepends=True)) + + def _split_lines(self, text, width): + return [argparse.HelpFormatter._split_lines(self, t, width)[0] for t in text.splitlines()] + + +def get_parser(description, distributed_launcher): + parser = argparse.ArgumentParser(description=description, formatter_class=SmartFormatter) + + parser.add_argument('--exec_mode', + type=str, + choices=['train', 'train_and_predict', 'predict', 'evaluate', 'train_and_evaluate'], + default='train_and_evaluate', + help="""Execution mode of running the model""") + + parser.add_argument('--model_dir', + type=str, + default='/tmp/unet2d', + help="""Output directory for information related to the model""") + + parser.add_argument('--data_dir', + type=str, + required=True, + help="""Input directory containing the dataset for training the model""") + + parser.add_argument('--log_dir', + type=str, + default="/tmp/unet2d", + help="""Output directory for training logs""") + + parser.add_argument('-b', '--batch_size', + type=int, + default=8, + help="""Size of each minibatch per HPU""") + + parser.add_argument('-d', '--dtype', + type=str, + default='bf16', + metavar='bf16/fp32', + choices=['fp32', 'bf16'], + help='Data type: fp32 or bf16') + + parser.add_argument('--fold', + type=int, + default=None, + help="""Chosen fold for cross-validation. Use None to disable cross-validation""") + + parser.add_argument('--max_steps', + type=int, + default=6400, + help="""Maximum number of steps (batches) used for training""") + + parser.add_argument('--log_every', + type=int, + default=100, + help="""Log data every n steps""") + + parser.add_argument('--evaluate_every', + type=int, + default=0, + help="""Evaluate every n steps""") + + parser.add_argument('--warmup_steps', + type=int, + default=200, + help="""Number of warmup steps""") + + parser.add_argument('--weight_decay', + type=float, + default=0.0005, + help="""Weight decay coefficient""") + + parser.add_argument('--learning_rate', + type=float, + default=0.0001, + help="""Learning rate coefficient for AdamOptimizer""") + + parser.add_argument('--seed', + type=int, + default=123, + help="""Random seed""") + + parser.add_argument('--dump_config', + type=str, + default=None, + help="""Directory for dumping debug traces""") + + parser.add_argument('--augment', dest='augment', action='store_true', + help="""Perform data augmentation during training""") + parser.add_argument('--no-augment', dest='augment', action='store_false') + parser.set_defaults(augment=True) + + parser.add_argument('--benchmark', dest='benchmark', action='store_true', + help="""Collect performance metrics during training""") + parser.add_argument('--no-benchmark', dest='benchmark', action='store_false') + + parser.add_argument('--use_xla', '--xla', dest='use_xla', action='store_true', + help="""Train using XLA""") + + parser.add_argument('--resume_training', dest='resume_training', action='store_true', + help="""Resume training from a checkpoint""") + + parser.add_argument('--no_hpu', dest='no_hpu', action='store_true', + help="""Disables execution on HPU, train on CPU""") + + parser.add_argument('--synth_data', dest='synth_data', action='store_true', + help="""Use deterministic and synthetic data""") + + parser.add_argument('--disable_ckpt_saving', dest='disable_ckpt_saving', action='store_true', + help="""Disables saving checkpoints""") + + parser.add_argument('--hvd_workers', dest='hvd_workers', type=int, default=1, + help="""Number of Horovod workers for single HLS""" if distributed_launcher else argparse.SUPPRESS) # ignored by unet2d.py + + parser.add_argument("--kubernetes_run", default=False, type=bool, + help="Kubernetes run" if distributed_launcher else argparse.SUPPRESS) # ignored by unet2d.py + + parser.add_argument('--use_horovod', dest='use_horovod', action='store_true', + help="""Enable horovod usage""") + + parser.add_argument('--tensorboard_logging', dest='tensorboard_logging', action='store_true', + help="""Enable tensorboard logging""") + + parser.add_argument('--log_all_workers', dest='log_all_workers', action='store_true', + help="""Enable logging data for every horovod worker in a separate directory named `worker_N`""") + + DEFAULT_BF16_CONFIG_PATH = os.fspath(Path(os.path.realpath(__file__)).parents[1].joinpath("bf16_config/unet.json")) + parser.add_argument('--bf16_config_path', metavar='', required=False, type=str, default=DEFAULT_BF16_CONFIG_PATH, + help="""Path to custom mixed precision config to use given in JSON format.""") + + parser.add_argument('--tf_verbosity', dest='tf_verbosity', type=int, choices=[0, 1, 2, 3], + help="""If set changes logging level from Tensorflow: + 0 - all messages are logged (default behavior); + 1 - INFO messages are not printed; + 2 - INFO and WARNING messages are not printed; + 3 - INFO, WARNING, and ERROR messages are not printed.""") + return parser + + +def parse_args(description="UNet-medical", distributed_launcher=False): + flags = get_parser(description, distributed_launcher).parse_args() + return Munch({ + 'exec_mode': flags.exec_mode, + 'model_dir': flags.model_dir, + 'data_dir': flags.data_dir, + 'log_dir': flags.log_dir, + 'batch_size': flags.batch_size, + 'dtype': flags.dtype, + 'fold': flags.fold, + 'max_steps': flags.max_steps, + 'log_every': flags.log_every, + 'evaluate_every': flags.evaluate_every, + 'warmup_steps': flags.warmup_steps, + 'weight_decay': flags.weight_decay, + 'learning_rate': flags.learning_rate, + 'seed': flags.seed, + 'dump_config': flags.dump_config, + 'augment': flags.augment, + 'benchmark': flags.benchmark, + 'use_xla': flags.use_xla, + 'resume_training': flags.resume_training, + 'no_hpu': flags.no_hpu, + 'synth_data': flags.synth_data, + 'disable_ckpt_saving': flags.disable_ckpt_saving, + 'hvd_workers': flags.hvd_workers, + 'kubernetes_run': flags.kubernetes_run, + 'use_horovod': flags.use_horovod, + 'tensorboard_logging': flags.tensorboard_logging, + 'log_all_workers': flags.log_all_workers, + 'bf16_config_path': flags.bf16_config_path, + 'tf_verbosity': flags.tf_verbosity, + 'gaudi_type': None + }) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/losses.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..f38249276e12520a83d0b5528d225f72fd52c989 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/losses.py @@ -0,0 +1,49 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - replace tf.keras.activations.softmax with tf.nn.softmax due to +# https://github.com/tensorflow/tensorflow/pull/47572 +# - replace tf.keras.backend.binary_crossentropy with tf.nn.sigmoid_cross_entropy_with_logits + +"""Training and evaluation losses""" + +import tensorflow as tf + + +# Class Dice coefficient averaged over batch +def dice_coef(predict, target, axis=1, eps=1e-6): + intersection = tf.reduce_sum(input_tensor=predict * target, axis=axis) + union = tf.reduce_sum(input_tensor=predict * predict + target * target, axis=axis) + dice = (2. * intersection + eps) / (union + eps) + return tf.reduce_mean(input_tensor=dice, axis=0) # average over batch + + +def partial_losses(predict, target): + n_classes = predict.shape[-1] + + flat_logits = tf.reshape(tf.cast(predict, tf.float32), + [tf.shape(input=predict)[0], -1, n_classes]) + flat_labels = tf.reshape(target, + [tf.shape(input=predict)[0], -1, n_classes]) + + crossentropy_loss = tf.reduce_mean(input_tensor=tf.nn.sigmoid_cross_entropy_with_logits(logits=flat_logits, + labels=flat_labels), + name='cross_loss_ref') + + dice_loss = tf.reduce_mean(input_tensor=1 - dice_coef(tf.nn.softmax(flat_logits, axis=-1), + flat_labels), name='dice_loss_ref') + return crossentropy_loss, dice_loss diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/parse_results.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/parse_results.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc30c5dbb8b8475a6fe8094ae70bb3d10caefd5 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/parse_results.py @@ -0,0 +1,82 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2020-2023 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - removed exec_mode from argparser +# - replaced gpu specific env choices to hpu + +import os +import argparse + +import numpy as np + + +def process_performance_stats(timestamps, batch_size, mode): + """ Get confidence intervals + + :param timestamps: Collection of timestamps + :param batch_size: Number of samples per batch + :param mode: Estimator's execution mode + :return: Stats + """ + timestamps_ms = 1000 * timestamps + throughput_imgps = 1000.0 * batch_size / timestamps_ms.mean() + stats = {f"throughput_{mode}": throughput_imgps, + f"latency_{mode}_mean": timestamps_ms.mean()} + for level in [90, 95, 99]: + stats.update({f"latency_{mode}_{level}": np.percentile(timestamps_ms, level)}) + + return stats + + +def parse_convergence_results(path, environment): + dice_scores = [] + ce_scores = [] + logfiles = [f for f in os.listdir(path) if "log" in f and environment in f] + if not logfiles: + raise FileNotFoundError("No logfile found at {}".format(path)) + for logfile in logfiles: + with open(os.path.join(path, logfile), "r") as f: + content = f.readlines()[-1] + if "eval_dice_score" not in content: + print("Evaluation score not found. The file", logfile, "might be corrupted.") + continue + dice_scores.append(float([val for val in content.split(" ") + if "eval_dice_score" in val][0].split()[-1])) + ce_scores.append(float([val for val in content.split(" ") + if "eval_ce_loss" in val][0].split()[-1])) + if dice_scores: + print("Evaluation dice score:", sum(dice_scores) / len(dice_scores)) + print("Evaluation cross-entropy loss:", sum(ce_scores) / len(ce_scores)) + else: + print("All logfiles were corrupted, no loss was obtained.") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description="UNet-medical-utils") + + parser.add_argument('--model_dir', + type=str, + required=True) + + parser.add_argument('--env', + choices=['fp32_1hpu', 'fp32_8hpu', 'bf16_1hpu', 'bf16_8hpu'], + type=str, + required=True) + + args = parser.parse_args() + parse_convergence_results(path=args.model_dir, environment=args.env) + print() diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/run.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/run.py new file mode 100644 index 0000000000000000000000000000000000000000..5a72f56d7ce6fc12460d681aca0ced9620359514 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/run.py @@ -0,0 +1,241 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2020-2023 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - wrapped horovod import in a try-catch block so that the user is not required to install this library +# when the model is being run on a single card +# - removed GPU specific mixed_precision handling +# - added synthetic data option for deterministic training +# - added tensorboard logging and performance measurements logs +# - in a training mode return loss from train_step as a numpy object to transfer the data to host +# - added TimeToTrain callback for dumping evaluation timestamps + +import os +from time import time + +import numpy as np +from PIL import Image +import tensorflow as tf + +from runtime.losses import partial_losses +from runtime.parse_results import process_performance_stats +from TensorFlow.common.tb_utils import write_hparams_v2 + + +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None + + +def train(params, model, dataset, logger, tb_logger=None, ttt_callback=None): + np.random.seed(params.seed) + tf.random.set_seed(params.seed) + + num_workers = hvd.size() if hvd is not None and hvd.is_initialized() else 1 + worker_id = hvd.rank() if hvd is not None and hvd.is_initialized() else 0 + max_steps = params.max_steps // num_workers + + optimizer = tf.keras.optimizers.legacy.Adam(learning_rate=params.learning_rate) + + ce_loss = tf.keras.metrics.Mean(name='ce_loss') + f1_loss = tf.keras.metrics.Mean(name='dice_loss') + checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) + if params.resume_training and params.model_dir: + checkpoint.restore(tf.train.latest_checkpoint(params.model_dir)) + + if tb_logger is not None: + write_hparams_v2(tb_logger.train_writer, vars(params)) + + @tf.function + def train_step(features, labels, warmup_batch=False): + with tf.GradientTape() as tape: + output_map = model(features) + crossentropy_loss, dice_loss = partial_losses(output_map, labels) + added_losses = tf.add(crossentropy_loss, dice_loss, name="total_loss_ref") + loss = added_losses + params.weight_decay * tf.add_n( + [tf.nn.l2_loss(v) for v in model.trainable_variables + if 'batch_normalization' not in v.name]) + + if hvd is not None and hvd.is_initialized(): + tape = hvd.DistributedGradientTape(tape) + gradients = tape.gradient(loss, model.trainable_variables) + optimizer.apply_gradients(zip(gradients, model.trainable_variables)) + + # Note: broadcast should be done after the first gradient step to ensure optimizer + # initialization. + if hvd is not None and hvd.is_initialized() and warmup_batch: + hvd.broadcast_variables(model.variables, root_rank=0) + hvd.broadcast_variables(optimizer.variables(), root_rank=0) + + ce_loss(crossentropy_loss) + f1_loss(dice_loss) + return loss + + timestamps = [] + if params.benchmark: + assert max_steps > params.warmup_steps, \ + "max_steps value has to be greater than warmup_steps" + for iteration, (images, labels) in enumerate(dataset.train_fn(drop_remainder=True)): + loss = train_step(images, labels, warmup_batch=iteration == 0).numpy() + if iteration > params.warmup_steps: + timestamps.append(time()) + + if iteration >= max_steps: + break + + if worker_id == 0: + deltas = np.array([timestamps[i + 1] - timestamps[i] for i in range(len(timestamps) - 1)]) + stats = process_performance_stats(deltas, num_workers * params.batch_size, mode="train") + logger.log(step=(), data=stats) + else: + timestamp = time() + start_time = timestamp + dataset_fn = dataset.synth_fn if params.synth_data else dataset.train_fn + for iteration, (images, labels) in enumerate(dataset_fn()): + # assign returned loss as a numpy object to transfer the data to host + loss = train_step(images, labels, warmup_batch=iteration == 0).numpy() + if iteration > params.warmup_steps: + timestamps.append(time()) + if worker_id == 0 or params.log_all_workers: + if iteration % params.log_every == 0: + duration = float(time() - timestamp) / params.log_every + timestamp = time() + data = { + "train_ce_loss": float(ce_loss.result()), + "train_dice_loss": float(f1_loss.result()), + "train_total_loss": float(f1_loss.result() + ce_loss.result()), + "iter duration [ms]": 1000 * duration, + "IPS": params.batch_size / duration + } + logger.log(step=(iteration, max_steps), data=data) + + if tb_logger is not None: + with tb_logger.train_writer.as_default(): + for name, value in data.items(): + tf.summary.scalar(name, value, step=iteration) + # for consistency + tf.summary.scalar("loss", data["train_total_loss"], step=iteration) + tf.summary.scalar("examples/sec", data["IPS"], step=iteration) + tf.summary.scalar("global_step/sec", 1. / duration, step=iteration) + + if (params.evaluate_every > 0) and (iteration % params.evaluate_every == 0): + evaluate(params, model, dataset, logger, tb_logger, ttt_callback, restore_checkpoint=False) + + f1_loss.reset_states() + ce_loss.reset_states() + + if iteration >= max_steps: + break + + if worker_id == 0: + if max_steps > params.warmup_steps: + deltas = np.array([timestamps[i + 1] - timestamps[i] for i in range(len(timestamps) - 1)]) + stats = process_performance_stats(deltas, num_workers * params.batch_size, mode="train") + logger.log(step=(), data=stats) + else: + print(f"max_steps value has to be greater than warmup_steps, skipping throughput calculation...") + logger.log(step=(), data={"train_time [sec]": (time() - start_time)}) + + if not params.disable_ckpt_saving and worker_id == 0: + checkpoint.save(file_prefix=os.path.join(params.model_dir, "checkpoint")) + + logger.flush() + + +def evaluate(params, model, dataset, logger, tb_logger=None, ttt_callback=None, restore_checkpoint=True): + if ttt_callback is not None: + ttt_callback.on_test_begin() + if params.fold is None: + print("No fold specified for evaluation. Please use --fold [int] to select a fold.") + ce_loss = tf.keras.metrics.Mean(name='ce_loss') + f1_loss = tf.keras.metrics.Mean(name='dice_loss') + checkpoint = tf.train.Checkpoint(model=model) + if params.model_dir and restore_checkpoint: + checkpoint.restore(tf.train.latest_checkpoint(params.model_dir)).expect_partial() + + def validation_step(features, labels): + output_map = model(features, training=False) + crossentropy_loss, dice_loss = partial_losses(output_map, labels) + ce_loss(crossentropy_loss) + f1_loss(dice_loss) + + for iteration, (images, labels) in enumerate(dataset.eval_fn(count=1)): + validation_step(images, labels) + if iteration >= dataset.eval_size // params.batch_size: + break + + data = {} + if dataset.eval_size > 0: + data = { + "eval_ce_loss": float(ce_loss.result()), + "eval_dice_loss": float(f1_loss.result()), + "eval_total_loss": float(f1_loss.result() + ce_loss.result()), + "eval_dice_score": 1.0 - float(f1_loss.result()), + "loss": float(f1_loss.result() + ce_loss.result()), + "accuracy": 1.0 - float(f1_loss.result()), # for consistency + } + logger.log(step=(), data=data) + if tb_logger is not None: + with tb_logger.eval_writer.as_default(): + for name, value in data.items(): + tf.summary.scalar(name, value, step=iteration) + + logger.flush() + if ttt_callback is not None: + ttt_callback.on_test_end() + + +def predict(params, model, dataset, logger): + checkpoint = tf.train.Checkpoint(model=model) + if params.model_dir: + checkpoint.restore(tf.train.latest_checkpoint(params.model_dir)).expect_partial() + + @tf.function + def prediction_step(features): + return tf.nn.softmax(model(features, training=False), axis=-1) + + if params.benchmark: + assert params.max_steps > params.warmup_steps, \ + "max_steps value has to be greater than warmup_steps" + timestamps = [] + for iteration, images in enumerate(dataset.test_fn(count=None, drop_remainder=True)): + prediction_step(images) + if iteration > params.warmup_steps: + timestamps.append(time()) + if iteration >= params.max_steps: + break + + deltas = np.array([timestamps[i + 1] - timestamps[i] for i in range(len(timestamps) - 1)]) + stats = process_performance_stats(deltas, params.batch_size, mode="test") + logger.log(step=(), data=stats) + else: + predictions = np.concatenate([prediction_step(images).numpy() + for images in dataset.test_fn(count=1)], axis=0) + binary_masks = [np.argmax(p, axis=-1).astype(np.uint8) * 255 for p in predictions] + multipage_tif = [Image.fromarray(mask).resize(size=(512, 512), resample=Image.BILINEAR) + for mask in binary_masks] + + output_dir = os.path.join(params.model_dir, 'predictions') + if not os.path.exists(output_dir): + os.makedirs(output_dir) + multipage_tif[0].save(os.path.join(output_dir, 'test-masks.tif'), + compression="tiff_deflate", + save_all=True, + append_images=multipage_tif[1:]) + + print("Predictions saved at {}".format(output_dir)) + logger.flush() diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/setup.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..66a5622c478e31e15d6ac2b27716467e4501a776 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/runtime/setup.py @@ -0,0 +1,94 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2020-2023 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - wrapped horovod import in a try-catch block so that the user is not required to install this library +# when the model is being run on a single card +# - removed GPU specific flags +# - set TF_BF16_CONVERSION flag to default unet2d config for bfloat16 precision +# - changed GPU specific logic for configuration with HPU +# - fixed JSON logger output directory +# - read type of Gaudi device if available + +import os +import multiprocessing + +import numpy as np +import tensorflow as tf +import dllogger as logger +from dllogger import StdOutBackend, Verbosity, JSONStreamBackend + +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None + + +def set_flags(params): + if params.tf_verbosity: + os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(params.tf_verbosity) + + if not params.no_hpu: + from habana_frameworks.tensorflow import load_habana_module + load_habana_module() + + from habana_frameworks.tensorflow.habana_device import get_type + params.gaudi_type = get_type() + + if params.dtype == 'bf16': + os.environ['TF_BF16_CONVERSION'] = params.bf16_config_path + + np.random.seed(params.seed) + tf.random.set_seed(params.seed) + + if params.use_xla: + tf.config.optimizer.set_jit(True) + + per_hpu_thread_count = 1 + num_hpus = hvd.size() if hvd is not None and hvd.is_initialized() else 1 + cpu_count = multiprocessing.cpu_count() + total_hpu_thread_count = per_hpu_thread_count * num_hpus + + tf.config.threading.set_intra_op_parallelism_threads(0) + tf.config.threading.set_inter_op_parallelism_threads(cpu_count - total_hpu_thread_count) + + +def prepare_model_dir(params): + worker_id = hvd.rank() if hvd is not None and hvd.is_initialized() else 0 + if params.benchmark or (not params.log_all_workers and worker_id != 0): + return None + + model_dir = os.path.join(params.model_dir, "model_checkpoint") + if params.log_all_workers and hvd is not None and hvd.is_initialized(): + model_dir = os.path.join(model_dir, f'worker_{worker_id}') + + os.makedirs(model_dir, exist_ok=True) + if ('train' in params.exec_mode) and (not params.resume_training): + os.system('rm -rf {}/*'.format(model_dir)) + return model_dir + + +def get_logger(params): + backends = [] + worker_id = hvd.rank() if hvd is not None and hvd.is_initialized() else 0 + if worker_id == 0: + backends += [StdOutBackend(Verbosity.VERBOSE)] + if params.log_dir: + os.makedirs(params.log_dir, exist_ok=True) + log_file = f"{params.log_dir}/log.json" + backends += [JSONStreamBackend(Verbosity.VERBOSE, log_file)] + logger.init(backends=backends) + return logger diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/train_and_evaluate.sh b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/train_and_evaluate.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b4df7f445d9dd56df38a43573682d03cd0e3d2a --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/train_and_evaluate.sh @@ -0,0 +1,38 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# +# This script runs 5-fold cross-validation of UNet2D topology for 6400 iterations +# Usage: +# bash train_and_evaluate.sh + +if [ ! -d $2 ] # If the results path doesn't exist, create +then + mkdir $2 +fi + +if [ $5 == 1 ] # Single card training +then + $PYTHON unet2d.py --data_dir $1 --model_dir $2 --log_dir $2/fold_0 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate --fold 0 --tensorboard_logging > $2/${4}_${5}hpu_fold0.log + $PYTHON unet2d.py --data_dir $1 --model_dir $2 --log_dir $2/fold_1 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate --fold 1 --tensorboard_logging > $2/${4}_${5}hpu_fold1.log + $PYTHON unet2d.py --data_dir $1 --model_dir $2 --log_dir $2/fold_2 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate --fold 2 --tensorboard_logging > $2/${4}_${5}hpu_fold2.log + $PYTHON unet2d.py --data_dir $1 --model_dir $2 --log_dir $2/fold_3 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate --fold 3 --tensorboard_logging > $2/${4}_${5}hpu_fold3.log + $PYTHON unet2d.py --data_dir $1 --model_dir $2 --log_dir $2/fold_4 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate --fold 4 --tensorboard_logging > $2/${4}_${5}hpu_fold4.log +else # Multi card training + mpirun --allow-run-as-root --tag-output --merge-stderr-to-stdout --bind-to core --map-by socket:PE=6 -np $5 $PYTHON unet2d.py \ + --data_dir $1 --model_dir $2 --log_dir $2/fold_0 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate \ + --fold 0 --tensorboard_logging --log_all_workers --use_horovod > $2/${4}_${5}hpu_fold0.log + mpirun --allow-run-as-root --tag-output --merge-stderr-to-stdout --bind-to core --map-by socket:PE=6 -np $5 $PYTHON unet2d.py \ + --data_dir $1 --model_dir $2 --log_dir $2/fold_1 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate \ + --fold 1 --tensorboard_logging --log_all_workers --use_horovod > $2/${4}_${5}hpu_fold1.log + mpirun --allow-run-as-root --tag-output --merge-stderr-to-stdout --bind-to core --map-by socket:PE=6 -np $5 $PYTHON unet2d.py \ + --data_dir $1 --model_dir $2 --log_dir $2/fold_2 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate \ + --fold 2 --tensorboard_logging --log_all_workers --use_horovod > $2/${4}_${5}hpu_fold2.log + mpirun --allow-run-as-root --tag-output --merge-stderr-to-stdout --bind-to core --map-by socket:PE=6 -np $5 $PYTHON unet2d.py \ + --data_dir $1 --model_dir $2 --log_dir $2/fold_3 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate \ + --fold 3 --tensorboard_logging --log_all_workers --use_horovod > $2/${4}_${5}hpu_fold3.log + mpirun --allow-run-as-root --tag-output --merge-stderr-to-stdout --bind-to core --map-by socket:PE=6 -np $5 $PYTHON unet2d.py \ + --data_dir $1 --model_dir $2 --log_dir $2/fold_4 --max_steps 6400 --batch_size $3 --dtype $4 --exec_mode train_and_evaluate \ + --fold 4 --tensorboard_logging --log_all_workers --use_horovod > $2/${4}_${5}hpu_fold4.log +fi +$PYTHON runtime/parse_results.py --model_dir $2 --env ${4}_${5}hpu diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/unet2d.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/unet2d.py new file mode 100644 index 0000000000000000000000000000000000000000..029c051d4867ec541ed3047a055bd6b3885eaaeb --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/Unet2D/unet2d.py @@ -0,0 +1,93 @@ +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +############################################################################### +# Copyright (C) 2020-2022 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - renamed script from main.py to unet2d.py +# - wrapped horovod import in a try-catch block so that the user is not required to install this library +# when the model is being run on a single card +# - added tensorboard logging functionality +# - added TimeToTrain callback for dumping evaluation timestamps + +import os +from collections import namedtuple + +import tensorflow as tf + +from model.unet import Unet +from runtime.run import train, evaluate, predict +from runtime.setup import get_logger, set_flags, prepare_model_dir +from runtime.arguments import parse_args +from data_loading.data_loader import Dataset +from TensorFlow.common.debug import dump_callback +from TensorFlow.common.tb_utils import TimeToTrainKerasHook + +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None + + +def main(): + """ + Starting point of the application + """ + params = parse_args(description="UNet-medical") + if params.use_horovod: + if hvd is None: + raise RuntimeError( + "Problem encountered during Horovod import. Please make sure that habana-horovod package is installed.") + hvd.init() + set_flags(params) + + model_dir = prepare_model_dir(params) + params.model_dir = model_dir + logger = get_logger(params) + + tb_logger = None + ttt_callback = None + if params.tensorboard_logging: + log_dir = params.log_dir + if hvd is not None and hvd.is_initialized() and params.log_all_workers: + log_dir = os.path.join(log_dir, f'worker_{hvd.rank()}') + tb_logger = namedtuple('TBSummaryWriters', 'train_writer eval_writer')( + tf.summary.create_file_writer(log_dir), + tf.summary.create_file_writer(os.path.join(log_dir, 'eval'))) + ttt_callback = TimeToTrainKerasHook(os.path.join(log_dir, 'eval')) + + model = Unet(seed=params.seed) + + dataset = Dataset(data_dir=params.data_dir, + batch_size=params.batch_size, + fold=params.fold, + augment=params.augment, + hpu_id=hvd.rank() if hvd is not None and hvd.is_initialized() else 0, + num_hpus=hvd.size() if hvd is not None and hvd.is_initialized() else 1, + seed=params.seed, + gaudi_type=params.gaudi_type) + + if 'train' in params.exec_mode: + with dump_callback(params.dump_config): + train(params, model, dataset, logger, tb_logger, ttt_callback) + + if 'evaluate' in params.exec_mode: + evaluate(params, model, dataset, logger, tb_logger, ttt_callback) + + if 'predict' in params.exec_mode: + predict(params, model, dataset, logger) + + +if __name__ == '__main__': + main() diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/LICENSE b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..be5b99bff92d0edfc0cb92c145670a8f4c487d57 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/LICENSE @@ -0,0 +1,192 @@ +Copyright (c) 2022 Habana Labs, Ltd. an Intel Company + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2020 Fausto Morales + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/README.md b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c8e37a8aa91d1e8db642d35549496be96af049aa --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/README.md @@ -0,0 +1,184 @@ +# Vision Transformer for TensorFlow + +This directory provides a script and recipe to train a Vision Transformer model to achieve state of the art accuracy, and is tested and maintained by Habana. +For further information on performance, refer to [Habana Model Performance Data page](https://developer.habana.ai/resources/habana-training-models/#performance). + +For further information on training deep learning models using Gaudi, refer to [developer.habana.ai](https://developer.habana.ai/resources/). + +## Table of Contents + +* [Model-References](../../../README.md) +* [Model overview](#model-overview) +* [Setup](#setup) +* [Training and Examples](#training-the-model) +* [Profiling Example](#profiling-example) +* [Supported Configuration](#supported-configuration) +* [Changelog](#changelog) +* [Known Issues](#known-issues) + +## Model Overview + +Original model was taken from [vit-keras](https://github.com/faustomorales/vit-keras/) repository. +This is a Keras implementation of the models described in [An Image is Worth 16x16 Words: Transformes For Image Recognition at Scale](https://arxiv.org/pdf/2010.11929.pdf). +It is based on an earlier implementation from [tuvovan](https://github.com/tuvovan/Vision_Transformer_Keras), modified to match the Flax implementation in the [official repository](https://github.com/google-research/vision_transformer). + +The weights here are ported over from the weights provided in the official repository. For more details on implementation, refer to `utils.load_weights_numpy`. + +## Setup + +Please follow the instructions provided in the [Gaudi Installation Guide](https://docs.habana.ai/en/latest/Installation_Guide/GAUDI_Installation_Guide.html) to set up the environment including the `$PYTHON` environment variable. To achieve the best performance, please follow the methods outlined in the [Optimizing Training Platform guide](https://docs.habana.ai/en/latest/TensorFlow/Model_Optimization_TensorFlow/Optimization_Training_Platform.html). +The guides will walk you through the process of setting up your system to run the model on Gaudi. + +### Clone Habana Model-References + +In the docker container, clone this repository and switch to the branch that matches your SynapseAI version. You can run the [`hl-smi`](https://docs.habana.ai/en/latest/Management_and_Monitoring/System_Management_Tools_Guide/System_Management_Tools.html#hl-smi-utility-options) utility to determine the SynapseAI version. + +```bash +git clone -b [SynapseAI version] https://github.com/HabanaAI/Model-References /root/Model-References +``` + +**Note:** If Model-References repository path is not in the PYTHONPATH, make sure you update it: +```bash +export PYTHONPATH=$PYTHONPATH:/root/Model-References +``` + +### Install Model Requirements + +1. In the docker container, go to the Vision Transformer directory: + +```bash +cd /root/Model-References/TensorFlow/computer_vision/VisionTransformer +``` + +2. Install the required packages using pip: + +```bash +$PYTHON -m pip install -r requirements.txt +``` + +### Training Data + +The Vision Transformer script operates on ImageNet 1k, a widely popular image classification dataset from the ILSVRC challenge. +Post downloading the dataset, the pre-processing script will be located in ResNet folder: [preprocess_imagenet.py](../Resnets/preprocess_imagenet.py) +To obtain the dataset, perform the following steps: +1. Sign up with http://image-net.org/download-images and acquire the rights to download original images. +2. Follow the link to the 2012 ILSVRC and download `ILSVRC2012_img_val.tar` and `ILSVRC2012_img_train.tar`. +3. Use the below commands to prepare the dataset under `/data/tensorflow_datasets/imagenet/tf_records`. This is the default data directory for the training script. + +``` +export IMAGENET_HOME=/data/tensorflow +mkdir -p $IMAGENET_HOME/validation +mkdir -p $IMAGENET_HOME/train +tar xf ILSVRC2012_img_val.tar -C $IMAGENET_HOME/validation +tar xf ILSVRC2012_img_train.tar -C $IMAGENET_HOME/train +cd $IMAGENET_HOME/train +for f in *.tar; do + d=`basename $f .tar` + mkdir $d + tar xf $f -C $d +done +cd $IMAGENET_HOME +rm $IMAGENET_HOME/train/*.tar # optional +wget -O synset_labels.txt https://raw.githubusercontent.com/tensorflow/models/master/research/slim/datasets/imagenet_2012_validation_synset_labels.txt +cd /root/Model-References/TensorFlow/computer_vision/Resnets +$PYTHON preprocess_imagenet.py \ + --raw_data_dir=$IMAGENET_HOME \ + --local_scratch_dir=$IMAGENET_HOME/imagenet/tf_records +``` + +## Training and Examples + +### Single Card and Multi-Card Training Examples + +**Run training on 1 HPU:** + +Run training on 1 HPU with BF16 precision, batch size 32 and gradient accumulation every 8 steps: + +```bash +$PYTHON train.py --dtype=bf16 --batch_size=32 --grad_accum_steps=8 +``` + +**Run training on 8 HPUs:** + +**NOTE:** mpirun map-by PE attribute value may vary on your setup. For the recommended calculation, refer to the instructions detailed in [mpirun Configuration](https://docs.habana.ai/en/latest/TensorFlow/Tensorflow_Scaling_Guide/Horovod_Scaling/index.html#mpirun-configuration). + +Vision Transformer relies on mpi4py and tf.distribute to enable distributed training. +Since `batch_size` parameter is global, it must be scaled (BS of a single card times number of cards). +`distributed` flag must be used to ensure proper strategy is in use. + +Run training on 8 HPUs with BF16 precision, batch size 256, 1000 warmup steps and gradient accumulation every 8 steps: + +```bash +mpirun -np 8 $PYTHON train.py -d=bf16 --batch_size=256 --warmup_steps=1000 --grad_accum_steps=8 --distributed +``` + +## Profiling Example + +### Single Card Profiling Training Example + +**Run training on 1 HPU:** + +Run training on 1 HPU with batch size 32, 1 epochs, 20 steps and 12-15 iterations: + +```bash +$PYTHON train.py --epochs 1 --steps_per_epoch 20 --profile 12,15 +``` + +### Parameters + +You can modify the training behavior through various flags in `train.py` script. + +- `dataset`, `dataset_dir`: Dataset directory. +- `optimizer`: Optimizer. +- `dtype`, `d`: Data type (FP32 or BF16). +- `batch_size`: Global batch size. +- `lr_sched`: Learning rate scheduler (linear, exp, steps, constant, WarmupCosine). +- `initial_lr`: Initial learning rate. +- `final_lr`: Final learning rate. +- `warmup_steps`: Warmup steps. +- `epochs`: Total number of epochs for training. +- `steps_per_epoch`: Number of steps for training per epoch, overrides default value. +- `validation_steps`: Number of steps for validation, overrides default value. +- `model`: Model (ViT-B_16, ViT-L_16, ViT-B_32, ViT-L_32). +- `train_subset`: Pattern to detect train subset in dataset directory. +- `val_subset`: Pattern to detect validation subset in dataset directory. +- `grad_accum_steps`: Gradient accumulation steps. +- `resume_from_checkpoint_path`: Path to checkpoint to start from. +- `resume_from_epoch`: Initial epoch index. +- `evaluate_checkpoint_path`: Checkpoint path for evaluating the model on --val_subset. +- `weights_path`: Path to weights cache directory. ~/.keras is used if not set. +- `deterministic`: Enable deterministic behavior, this will also disable data augmentation. --seed must be set. +- `seed`: Seed to be used by random functions. +- `device`: Device type (CPU or HPU). +- `distributed`: Enable distributed training. +- `base_tf_server_port`: Rank 0 port used by tf.distribute. +- `save_summary_steps`: Steps between saving summaries to TensorBoard. +- `recipe_cache`: Path to recipe cache directory. Set to empty to disable recipe cache. Externally set 'TF_RECIPE_CACHE_PATH' will override this setting. +- `dump_config`: Side-by-side config file. Internal, do not use. + +## Supported Configuration + +| Validated on | SynapseAI Version | TensorFlow Version(s) | Mode | +|:------:|:-----------------:|:-----:|:----------:| +| Gaudi | 1.10.0 | 2.12.0 | Training | + + +## Changelog + +### 1.4.0 + +- Updated dataset paths. +- Added '--profile' parameter. +- implementation override clean-up. + +### 1.3.0 + +- Updated 'tensorflow_addons' and 'mpi4py' in requirements.txt. +- Added implementation override of Gelu. +- Improved robustness in multi-card scenarios. + +## Known Issues + +### Profiling in Multi-card Scenario + +To profile in multi-card scenario, habanalabs driver must be loaded with increased `timeout_locked` parameter (eg. `timeout_locked=300`). \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/config.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/config.py new file mode 100644 index 0000000000000000000000000000000000000000..feef43f31a0744dc0eb5d8e6595bc891bb23b38e --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/config.py @@ -0,0 +1,30 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### + +from types import SimpleNamespace +config = SimpleNamespace() + +# Subdirectory name for saving trained weights and models. +config.SAVE_DIR = 'saves' + +# Subdirectory name for saving TensorBoard log files. +config.LOG_DIR = 'logs' + +# Default path to the ImageNet TFRecords dataset files. +config.DEFAULT_DATASET_DIR = '/data/tensorflow/imagenet/tf_records' + +# Path to weights cache directory. ~/.keras is used if None. +config.WEIGHTS_DIR = None + +# Number of parallel workers for generating training/validation data. +config.NUM_DATA_WORKERS = 128 + +# Do image data augmentation or not. +config.DATA_AUGMENTATION = True + +# Enable deterministic behavior. +config.DETERMINISTIC = False + +# Seed to be used by random functions. +config.SEED = None diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/models/__init__.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/models/models.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/models/models.py new file mode 100644 index 0000000000000000000000000000000000000000..0606361eaabd68d8f2de9e80e9ed41054aaa81a4 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/models/models.py @@ -0,0 +1,381 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### + +import math + +import tensorflow as tf +from tensorflow.keras import backend +from typeguard import typechecked +from typing import Union + + +class GradientAccumulator(tf.keras.optimizers.legacy.Optimizer): + """Optimizer wrapper for gradient accumulation.""" + + @typechecked + def __init__( + self, + optimizer: Union[tf.keras.optimizers.legacy.Optimizer, str], + accum_steps: tf.types.experimental.TensorLike = 4, + name: str = "GradientAccumulator", + **kwargs, + ): + r"""Construct a new GradientAccumulator optimizer. + Args: + optimizer: str or `tf.keras.optimizers.Optimizer` that will be + used to compute and apply gradients. + accum_steps: int > 0. Update gradient in every accumulation steps. + name: Optional name for the operations created when applying + gradients. Defaults to "GradientAccumulator". + **kwargs: keyword arguments. Allowed to be {`clipnorm`, + `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients by + norm; `clipvalue` is clip gradients by value, `decay` is + included for backward compatibility to allow time inverse + decay of learning rate. `lr` is included for backward + compatibility, recommended to use `learning_rate` instead. + """ + super().__init__(name, **kwargs) + self._optimizer = tf.keras.optimizers.get(optimizer) + self._gradients = [] + self._accum_steps = accum_steps + + def _create_slots(self, var_list): + self._optimizer._create_slots(var_list=var_list) + for var in var_list: + self.add_slot(var, "ga") + + self._gradients = [self.get_slot(var, "ga") for var in var_list] + + @property + def gradients(self): + """The accumulated gradients on the current replica.""" + if not self._gradients: + raise ValueError( + "The accumulator should be called first to initialize the gradients" + ) + return list( + gradient.read_value() if gradient is not None else gradient + for gradient in self._gradients + ) + + def apply_gradients(self, grads_and_vars, name=None, **kwargs): + self._optimizer._iterations = self.iterations + return super().apply_gradients(grads_and_vars, name, **kwargs) + + def _resource_apply_dense(self, grad, var, apply_state=None): + accum_gradient = self.get_slot(var, "ga") + if accum_gradient is not None and grad is not None: + accum_gradient.assign_add( + grad / self._accum_steps, use_locking=self._use_locking, read_value=False + ) + + def _apply(): + if "apply_state" in self._optimizer._dense_apply_args: + train_op = self._optimizer._resource_apply_dense( + accum_gradient.read_value(), var, apply_state=apply_state + ) + else: + train_op = self._optimizer._resource_apply_dense( + accum_gradient.read_value(), var + ) + reset_op = accum_gradient.assign( + tf.zeros_like(accum_gradient), + use_locking=self._use_locking, + read_value=False, + ) + return tf.group(train_op, reset_op) + + apply_op = tf.cond( + (self.iterations + 1) % self._accum_steps == 0, _apply, lambda: tf.no_op() + ) + return apply_op + + def _resource_apply_sparse(self, grad: tf.types.experimental.TensorLike, var, indices, apply_state): + accum_gradient = self.get_slot(var, "ga") + if accum_gradient is not None and grad is not None: + self._resource_scatter_add(accum_gradient, indices, grad) + + def _apply(): + if "apply_state" in self._optimizer._sparse_apply_args: + train_op = self._optimizer._resource_apply_sparse( + accum_gradient.sparse_read(indices), + var, + indices, + apply_state=apply_state, + ) + else: + train_op = self._optimizer._resource_apply_sparse( + accum_gradient.sparse_read(indices), var, indices + ) + reset_op = accum_gradient.assign( + tf.zeros_like(accum_gradient), + use_locking=self._use_locking, + read_value=False, + ) + return tf.group(train_op, reset_op) + + apply_op = tf.cond( + (self.iterations + 1) % self._accum_steps == 0, _apply, lambda: tf.no_op() + ) + return apply_op + + def reset(self): + """Resets the accumulated gradients on the current replica.""" + assign_ops = [] + if not self._gradients: + return assign_ops + + for gradient in self._gradients: + if gradient is not None: + assign_ops.append( + gradient.assign( + tf.zeros_like(gradient), + use_locking=self._use_locking, + read_value=False, + ) + ) + + return tf.group(assign_ops) + + @property + def lr(self): + return self._optimizer._get_hyper("learning_rate") + + @lr.setter + def lr(self, lr): + self._optimizer._set_hyper("learning_rate", lr) # + + @property + def learning_rate(self): + return self._optimizer._get_hyper("learning_rate") + + @learning_rate.setter + def learning_rate(self, learning_rate): + self._optimizer._set_hyper("learning_rate", learning_rate) + + def get_config(self): + config = { + "accum_steps": self._accum_steps, + "optimizer": tf.keras.optimizers.serialize(self._optimizer), + } + base_config = super().get_config() + return {**base_config, **config} + + @classmethod + def from_config(cls, config, custom_objects=None): + optimizer = tf.keras.optimizers.deserialize( + config.pop("optimizer"), custom_objects=custom_objects + ) + return cls(optimizer, **config) + + +IN_SHAPE = (224, 224, 3) # shape of input image tensor +NUM_CLASSES = 1000 # number of output classes (1000 for ImageNet) + + +def _set_l2(model, weight_decay): + """Add L2 regularization into layers with weights + Reference: https://jricheimer.github.io/keras/2019/02/06/keras-hack-1/ + """ + for layer in model.layers: + if isinstance(layer, tf.keras.layers.DepthwiseConv2D): + layer.add_loss(lambda: tf.keras.regularizers.l2( + weight_decay)(layer.kernel)) + print('added wd to layer %s' % layer.name) + elif isinstance(layer, tf.keras.layers.Conv2D): + #layer.add_loss(lambda: keras.regularizers.l2(weight_decay)(layer.kernel)) + print('added wd to layer %s' % layer.name) + elif isinstance(layer, tf.keras.layers.Dense): + layer.add_loss(lambda: tf.keras.regularizers.l2( + weight_decay)(layer.kernel)) + print('added wd to layer %s' % layer.name) + elif isinstance(layer, tf.keras.layers.BatchNormalization): + layer.add_loss(lambda: tf.keras.regularizers.l2( + weight_decay)(layer.kernel)) + print('added wd to layer %s' % layer.name) + + +def get_batch_size(model_name, value): + """get_batch_size + + These default batch_size values were chosen based on available + GPU RAM (11GB) on GeForce GTX-2080Ti. + """ + if value > 0: + return value + elif 'densenet121' in model_name: + return 16 + else: + raise ValueError + + +def get_iter_size(model_name, value): + """get_iter_size + + These default iter_size values were chosen to make 'effective' + batch_size to be 256. + """ + if value > 0: + return value + elif 'densenet121' in model_name: + return 16 + else: + raise ValueError + + +def get_initial_lr(model_name, value): + return value if value > 0. else 3e-4 + + +def get_final_lr(model_name, value): + return value if value > 0. else 3e-4 + + +class CosineLearningRateScheduleWithWarmup(tf.keras.callbacks.Callback): + def __init__(self, schedule, initial_lr, warmup_steps, resume_step, total_steps, cycles=0.5, verbose=0): + super(CosineLearningRateScheduleWithWarmup, self).__init__() + + self.schedule = schedule + self.verbose = verbose + self.warmup_steps = warmup_steps + self.initial_lr = initial_lr + self.resume_step = resume_step + self.total_steps = total_steps + self.cycles = cycles + + def on_train_begin(self, logs=None): + self.iter = 0 + self.resume_step + + def on_train_batch_end(self, batch, logs=None): + self.iter += 1 + if self.iter < self.warmup_steps: + warmup_multiplier = float(self.iter) / float(self.warmup_steps) + lr = self.initial_lr * warmup_multiplier + backend.set_value(self.model.optimizer.lr, lr) + else: + progress = float(self.iter - self.warmup_steps) / \ + float(max(1, self.total_steps - self.warmup_steps)) + lr = max(0.0, 0.5 * (1. + tf.math.cos(math.pi * + float(self.cycles) * 2.0 * progress)))*self.initial_lr + backend.set_value(self.model.optimizer.lr, lr) + + def on_epoch_begin(self, epoch, logs=None): + if not hasattr(self.model.optimizer, 'learning_rate'): + raise ValueError('Optimizer must have a "lr" attribute.') + try: # new API + lr = float(backend.get_value(self.model.optimizer.learning_rate)) + except TypeError: # Support for old API for backward compatibility + print("An exception occurred") + + backend.set_value(self.model.optimizer.learning_rate, + backend.get_value(lr)) + if self.verbose > 0: + print('\nEpoch %05d: LearningRateScheduler reducing learning ' + 'rate to %s.' % (epoch + 1, lr)) + + def on_epoch_end(self, epoch, logs=None): + logs = logs or {} + logs['lr'] = backend.get_value(self.model.optimizer.learning_rate) + + +def get_lr_func(total_epochs, lr_sched='linear', + initial_lr=6e-2, final_lr=1e-5, warmup_steps=0, resume_step=0, total_steps=5004): + """Returns a learning decay function for training. + + 5 types of lr_sched are supported: 'linear' or 'exp', 'steps' , 'constant' , 'WarmupCosine' (exponential). + """ + def linear_decay(epoch): + """Decay LR linearly for each epoch.""" + if total_epochs == 1: + return initial_lr + else: + ratio = max((total_epochs - epoch - 1.) / (total_epochs - 1.), 0.) + lr = final_lr + (initial_lr - final_lr) * ratio + print('Epoch %d, lr = %f' % (epoch+1, lr)) + return lr + + def exp_decay(epoch): + """Decay LR exponentially for each epoch.""" + if total_epochs == 1: + return initial_lr + else: + lr_decay = (final_lr / initial_lr) ** (1. / (total_epochs - 1)) + lr = initial_lr * (lr_decay ** epoch) + print('Epoch %d, lr = %f' % (epoch+1, lr)) + return lr + + def steps_decay(epoch): + if total_epochs == 1: + # learning rate is reduced by x10 at the end of epochs: 30,60,80,110,140,... + return initial_lr + else: + if (epoch < 80): + lr_decay = pow(0.1, epoch // 30) + else: + lr_decay = pow(0.1, (epoch+10) // 30) + print(epoch) + print(lr_decay) + + lr = initial_lr * lr_decay + print('Epoch %d, lr = %f' % (epoch+1, lr)) + return lr + + def constant(epoch): + """Decay LR exponentially for each epoch.""" + if total_epochs == 1: + return initial_lr + else: + lr = initial_lr + print('Epoch %d, lr = %f' % (epoch+1, lr)) + return lr + + if total_epochs < 1: + raise ValueError('bad total_epochs (%d)' % total_epochs) + if lr_sched == 'linear': + return tf.keras.callbacks.LearningRateScheduler(linear_decay) + elif lr_sched == 'exp': + return tf.keras.callbacks.LearningRateScheduler(exp_decay) + elif lr_sched == 'steps': + return tf.keras.callbacks.LearningRateScheduler(steps_decay) + elif lr_sched == 'constant': + return tf.keras.callbacks.LearningRateScheduler(constant) + elif lr_sched == 'WarmupCosine': + return CosineLearningRateScheduleWithWarmup(constant, initial_lr, warmup_steps, resume_step, total_steps) + + else: + raise ValueError('bad lr_sched') + + +def get_weight_decay(model_name, value): + return value if value >= 0. else 1e-5 + + +def get_optimizer(optim_name, initial_lr, accumulation_steps=1, epsilon=1e-2): + """get_optimizer + + Note: + 1. Learning rate decay is implemented as a callback in model.fit(), + so I do not specify 'decay' in the optimizers here. + 2. Refer to the following for information about 'epsilon' in Adam: + https://github.com/tensorflow/tensorflow/blob/v1.14.0/tensorflow/python/keras/optimizer_v2/adam.py#L93 + """ + from functools import partial + if optim_name == 'sgd': + optimizer = partial(tf.keras.optimizers.legacy.SGD, + momentum=0.9, nesterov=False, global_clipnorm=1.0) + elif optim_name == 'adam': + optimizer = partial(tf.keras.optimizers.legacy.Adam, epsilon=epsilon) + elif optim_name == 'rmsprop': + optimizer = partial(tf.keras.optimizers.legacy.RMSprop, + rho=0.9, epsilon=epsilon) + else: + # implementation of 'AdamW' is removed temporarily + raise ValueError + + optimizer = optimizer(learning_rate=initial_lr) + if accumulation_steps > 1: + optimizer = GradientAccumulator( + optimizer, accum_steps=accumulation_steps) + + return optimizer diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/requirements.txt b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..bff669be57cc26011221c73aac086d3e32a0ab68 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/requirements.txt @@ -0,0 +1,3 @@ +vit-keras==0.1.0 +opencv-python==4.7.0.68 +mpi4py==3.1.3 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/train.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/train.py new file mode 100644 index 0000000000000000000000000000000000000000..0c7e82a2802de69d3df29332f03267d762ddc66f --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/train.py @@ -0,0 +1,297 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### + +import argparse +import os +import random + +import numpy as np +import tensorflow as tf +from TensorFlow.common.debug import dump_callback +from TensorFlow.common.tb_utils import (ExamplesPerSecondKerasHookV2, TensorBoardWithHParamsV2, + TimeToTrainKerasHook) +from config import config +from models.models import get_lr_func, get_optimizer +from utils.distribution_utils import configure_cluster, comm_size, comm_rank +from utils.dataset import get_dataset +from vit_keras import vit + + +def tf_distribute_config(base_tf_server_port: int): + """ + Generates a TensorFlow cluster information and sets it to TF_CONFIG environment variable. + TF_CONFIG won't be altered if it was externally set. + """ + hls_addresses = str(os.environ.get( + 'MULTI_HLS_IPS', '127.0.0.1')).split(',') + rank = comm_rank() + size = comm_size() + + worker_hosts = ",".join([",".join([address + ':' + str(base_tf_server_port + r) + for r in range(size//len(hls_addresses))]) + for address in hls_addresses]) + + configure_cluster(worker_hosts, rank) + print(os.environ['TF_CONFIG']) + + +DESCRIPTION = 'VisionTransformer training script.' + + +def main(): + parser = argparse.ArgumentParser(description=DESCRIPTION) + parser.add_argument('--dataset', '--dataset_dir', metavar='PATH', + default=config.DEFAULT_DATASET_DIR, help='Dataset directory.') + parser.add_argument('--optimizer', default='sgd', + choices=['sgd', 'adam', 'rmsprop'], help='Optimizer.') + parser.add_argument('-d', '--dtype', default='fp32', + choices=['fp32', 'bf16'], help='Data type.') + parser.add_argument('--batch_size', type=int, + default=32, help='Global batch size.') + parser.add_argument('--lr_sched', default='WarmupCosine', choices=[ + 'linear', 'exp', 'steps', 'constant', 'WarmupCosine'], help='Learning rate scheduler.') + parser.add_argument('--initial_lr', type=float, + default=6e-2, help='Initial learning rate.') + parser.add_argument('--final_lr', type=float, + default=1e-5, help='Final learning rate.') + parser.add_argument('--warmup_steps', type=int, + default=4000, help='Warmup steps.') + parser.add_argument('--epochs', type=int, default=10, + help='Total number of epochs for training.') + parser.add_argument('--steps_per_epoch', type=int, + help='Number of steps for training per epoch, overrides default value.') + parser.add_argument('--validation_steps', type=int, + help='Number of steps for validation, overrides default value.') + parser.add_argument('--profile', type=str, default='0', + help='Profile the batch(es) to sample compute characteristics.' + 'Must be an integer or a pair of comma-separated integers. For example: --profile 4,6') + parser.add_argument('--model', default='ViT-B_16', + choices=['ViT-B_16', 'ViT-L_16', 'ViT-B_32', 'ViT-L_32'], help='Model.') + parser.add_argument('--train_subset', default='train/train', + help='Pattern to detect train subset in dataset directory.') + parser.add_argument('--val_subset', default='validation/validation', + help='Pattern to detect validation subset in dataset directory.') + parser.add_argument('--grad_accum_steps', type=int, + default=8, help='Gradient accumulation steps.') + parser.add_argument('--resume_from_checkpoint_path', + metavar='PATH', help='Path to checkpoint to start from.') + parser.add_argument('--resume_from_epoch', metavar='EPOCH_INDEX', + type=int, default=0, help='Initial epoch index.') + parser.add_argument('--evaluate_checkpoint_path', metavar='PATH', + help='Checkpoint path for evaluating the model on --val_subset') + parser.add_argument('--weights_path', metavar='PATH', + help='Path to weights cache directory. ~/.keras is used if not set.') + parser.add_argument('--deterministic', action='store_true', default=False, + help='Enable deterministic behavior, this will also disable data augmentation. --seed must be set.') + parser.add_argument('--seed', type=int, + help='Seed to be used by random functions.') + parser.add_argument('--device', default='HPU', + choices=['CPU', 'HPU'], help='Device type.') + parser.add_argument('--distributed', action='store_true', + default=False, help='Enable distributed training.') + parser.add_argument('--base_tf_server_port', type=int, + default=7850, help='Rank 0 port used by tf.distribute.') + parser.add_argument('--save_summary_steps', type=int, default=0, + help='Steps between saving summaries to TensorBoard.') + parser.add_argument('--recipe_cache', default='/tmp/vit_recipe_cache', + help='Path to recipe cache directory. Set to empty to disable recipe cache. Externally set \'TF_RECIPE_CACHE_PATH\' will override this setting.') + parser.add_argument( + '--dump_config', help='Side-by-side config file. Internal, do not use.') + args = parser.parse_args() + + if args.weights_path is not None: + config.WEIGHTS_DIR = args.weights_path + + if args.dtype == 'bf16': + tf.keras.mixed_precision.set_global_policy('mixed_bfloat16') + + if args.device == 'HPU': + if args.distributed: + os.environ['TF_HCCL_MEMORY_ALLOWANCE_MB'] = '1000' + from habana_frameworks.tensorflow import load_habana_module + load_habana_module() + + # Handle recipe caching. + recipe_cache = args.recipe_cache + if 'TF_RECIPE_CACHE_PATH' not in os.environ.keys() and recipe_cache: + os.environ['TF_RECIPE_CACHE_PATH'] = recipe_cache + + # Clear previous recipe cache. + if not args.distributed or comm_rank() == 0: + if os.path.exists(recipe_cache) and os.path.isdir(recipe_cache): + import shutil + shutil.rmtree(recipe_cache) + # Wait for rank 0 to remove cache. + if args.distributed: + from mpi4py import MPI + MPI.COMM_WORLD.Barrier() + + # Create separate log dir directory. + if args.distributed: + config.LOG_DIR = os.path.join( + config.LOG_DIR, f'worker_{comm_rank()}') + + # Handle determinism. + config.DETERMINISTIC = args.deterministic + config.SEED = args.seed + if args.deterministic: + assert args.seed is not None, "Deterministic behavior require seed to be set." + tf.config.threading.set_inter_op_parallelism_threads(1) + tf.config.threading.set_intra_op_parallelism_threads(1) + os.environ['TF_DETERMINISTIC_OPS'] = '1' + config.DATA_AUGMENTATION = False + if args.seed is not None: + random.seed(args.seed) + np.random.seed(args.seed) + tf.random.set_seed(args.seed) + + # Handle distribution strategy. + if args.distributed: + tf_distribute_config(args.base_tf_server_port) + if args.device == 'HPU': + from habana_frameworks.tensorflow.distribute import HPUStrategy + strategy = HPUStrategy() + else: + strategy = tf.distribute.MultiWorkerMirroredStrategy() + else: + strategy = tf.distribute.OneDeviceStrategy(f'device:{args.device}:0') + + if not args.distributed or comm_rank() == 0: + print('Number of devices: {}'.format(strategy.num_replicas_in_sync)) + + num_classes = 1000 + batch_size = args.batch_size + nb_epoch = args.epochs + dataset = args.dataset + resume_from_checkpoint_path = args.resume_from_checkpoint_path + resume_from_epoch = args.resume_from_epoch + optim_name = args.optimizer + initial_lr = args.initial_lr + final_lr = args.final_lr + lr_sched = args.lr_sched + warmup_steps = args.warmup_steps + model_name = args.model + grad_accum_steps = args.grad_accum_steps + + ds_train = get_dataset(dataset, args.train_subset, batch_size, + is_training=True, distributed=args.distributed) + ds_valid = get_dataset(dataset, args.val_subset, + batch_size, False, distributed=args.distributed) + + if args.dump_config is not None: + vit.CONFIG_B['dropout'] = 0.0 + vit.CONFIG_L['dropout'] = 0.0 + + # Load our model + with strategy.scope(): + image_size = 384 + if model_name == 'ViT-B_16': + model = vit.vit_b16( + image_size=image_size, + activation='softmax', + pretrained=True, + include_top=True, + pretrained_top=False, + classes=num_classes, + weights="imagenet21k") + elif model_name == 'ViT-L_16': + model = vit.vit_l16( + image_size=image_size, + activation='softmax', + pretrained=True, + include_top=True, + pretrained_top=False, + classes=num_classes, + weights="imagenet21k") + elif model_name == 'ViT-B_32': + model = vit.vit_b32( + image_size=image_size, + activation='softmax', + pretrained=True, + include_top=True, + pretrained_top=False, + classes=num_classes, + weights="imagenet21k") + elif model_name == 'ViT-L_32': + model = vit.vit_l32( + image_size=image_size, + activation='softmax', + pretrained=True, + include_top=True, + pretrained_top=False, + classes=num_classes, + weights="imagenet21k") + else: + print( + "Model is not supported, please use either ViT-B_16 or ViT-L_16 or ViT-B_32 or ViT-L_32") + exit(0) + + optimizer = get_optimizer( + optim_name, initial_lr, accumulation_steps=grad_accum_steps, epsilon=1e-2) + model.compile(optimizer=optimizer, loss='categorical_crossentropy', + metrics=['accuracy'], run_eagerly=False) + + # Start training + + steps_per_epoch = 1281167 // batch_size + if args.steps_per_epoch is not None: + steps_per_epoch = args.steps_per_epoch + validation_steps = 50000 // batch_size + if args.validation_steps is not None: + validation_steps = args.validation_steps + + total_steps = nb_epoch * steps_per_epoch + resume_step = resume_from_epoch * steps_per_epoch + + lrate = get_lr_func(nb_epoch, lr_sched, initial_lr, + final_lr, warmup_steps, resume_step, total_steps) + + save_name = model_name if not model_name.endswith('.h5') else \ + os.path.split(model_name)[-1].split('.')[0].split('-')[0] + model_ckpt = tf.keras.callbacks.ModelCheckpoint( + os.path.join(config.SAVE_DIR, save_name) + '-ckpt-{epoch:03d}.h5', + monitor='train_loss') + + callbacks = [lrate, model_ckpt] + + profile_batch = 0 + if not args.distributed or comm_rank() == 0: + profile_batch = tuple(int(i) for i in args.profile.split(',')) + if len(profile_batch) == 1: + profile_batch = profile_batch[0] + callbacks += [TensorBoardWithHParamsV2( + vars(args), log_dir=config.LOG_DIR, update_freq=args.save_summary_steps, profile_batch=profile_batch)] + callbacks += [TimeToTrainKerasHook(output_dir=config.LOG_DIR)] + + if args.save_summary_steps > 0: + callbacks += [ExamplesPerSecondKerasHookV2( + output_dir=config.LOG_DIR, every_n_steps=args.save_summary_steps, batch_size=args.batch_size)] + + if (args.evaluate_checkpoint_path is not None): + model.load_weights(args.evaluate_checkpoint_path) + results = model.evaluate(x=ds_valid, steps=validation_steps) + print("Test loss, Test acc:", results) + exit() + + if ((resume_from_epoch is not None) and (resume_from_checkpoint_path is not None)): + model.load_weights(resume_from_checkpoint_path) + + with dump_callback(args.dump_config): + model.fit(x=ds_train, y=None, + steps_per_epoch=steps_per_epoch, + callbacks=callbacks, + initial_epoch=resume_from_epoch, + epochs=nb_epoch, + shuffle=not args.deterministic, + verbose=1 if not args.distributed else comm_rank() == 0, + validation_data=(ds_valid, None), + validation_steps=validation_steps, + ) + + if not args.distributed or comm_rank() == 0: + model.save(f'{config.SAVE_DIR}/{save_name}-model-final.h5') + + +if __name__ == '__main__': + main() diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/__init__.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/dataset.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..47a01c0c0987d36b09c12cc0ce703ebcc56970d3 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/dataset.py @@ -0,0 +1,134 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +"""dataset.py + +This module implements functions for reading ImageNet (ILSVRC2012) +dataset in TFRecords format. +""" + +import os +from functools import partial + +import tensorflow as tf + +from config import config +from utils.image_processing import preprocess_image, resize_and_rescale_image + + +def decode_jpeg(image_buffer, scope=None): + """Decode a JPEG string into one 3-D float image Tensor. + + Args: + image_buffer: scalar string Tensor. + scope: Optional scope for name_scope. + Returns: + 3-D float Tensor with values ranging from [0, 1). + """ + with tf.compat.v1.name_scope(values=[image_buffer], name=scope, + default_name='decode_jpeg'): + # Decode the string as an RGB JPEG. + # Note that the resulting image contains an unknown height + # and width that is set dynamically by decode_jpeg. In other + # words, the height and width of image is unknown at compile-i + # time. + image = tf.image.decode_jpeg(image_buffer, channels=3) + + # After this point, all image pixels reside in [0,1) + # until the very end, when they're rescaled to (-1, 1). + # The various adjust_* ops all require this range for dtype + # float. + image = tf.image.convert_image_dtype(image, dtype=tf.float32) + return image + + +def _parse_fn(example_serialized, is_training): + """Helper function for parse_fn_train() and parse_fn_valid() + + Each Example proto (TFRecord) contains the following fields: + + image/height: 462 + image/width: 581 + image/colorspace: 'RGB' + image/channels: 3 + image/class/label: 615 + image/class/synset: 'n03623198' + image/class/text: 'knee pad' + image/format: 'JPEG' + image/filename: 'ILSVRC2012_val_00041207.JPEG' + image/encoded: + + Args: + example_serialized: scalar Tensor tf.string containing a + serialized Example protocol buffer. + is_training: training (True) or validation (False). + + Returns: + image_buffer: Tensor tf.string containing the contents of + a JPEG file. + label: Tensor tf.int32 containing the label. + text: Tensor tf.string containing the human-readable label. + """ + feature_map = { + 'image/encoded': tf.io.FixedLenFeature([], dtype=tf.string, + default_value=''), + 'image/class/label': tf.io.FixedLenFeature([], dtype=tf.int64, + default_value=-1), + 'image/class/text': tf.io.FixedLenFeature([], dtype=tf.string, + default_value=''), + } + parsed = tf.io.parse_single_example( + serialized=example_serialized, features=feature_map) + image = decode_jpeg(parsed['image/encoded']) + if config.DATA_AUGMENTATION: + image = preprocess_image(image, 384, 384, is_training=is_training) + else: + image = resize_and_rescale_image(image, 384, 384) + # The label in the tfrecords is 1~1000 (0 not used). + # So I think the minus 1 (of class label) is needed below. + label = tf.one_hot(parsed['image/class/label'] - 1, 1000, dtype=tf.float32) + return (image, label) + + +def get_dataset(tfrecords_dir, subset, batch_size, is_training, distributed): + """Read TFRecords files and turn them into a TFRecordDataset. + + Args: + tfrecords_dir: dataset directory + subset: pattern to detect subset in dataset directory + batch_size: Global batch size + is_training (bool): use True if dataset will be used for training + distributed (bool): use True if used in distributed environment + + Returns: + TFRecordDataset: Dataset. + """ + filenames = tf.io.matching_files( + os.path.join(tfrecords_dir, '%s-*' % subset)) + ds = tf.data.Dataset.from_tensor_slices(filenames) + + # Sharding should be used only for training and in distributed environments. + if distributed and is_training: + from utils.distribution_utils import comm_size, comm_rank + ds = ds.shard(comm_size(), comm_rank()) + + if is_training: + num_files = tf.cast(tf.shape(input=filenames)[0], tf.int64) + ds = ds.shuffle(buffer_size=num_files) + + ds = ds.interleave(tf.data.TFRecordDataset, cycle_length=10) + + if is_training: + ds = ds.shuffle(buffer_size=10000) + ds = ds.repeat() + + parser = partial(_parse_fn, is_training=is_training) + ds = ds.map(map_func=parser, + num_parallel_calls=config.NUM_DATA_WORKERS, deterministic=False) + ds = ds.batch(batch_size=batch_size, drop_remainder=True) + + # Sharding is already done, so disable autosharding. + options = tf.data.Options() + options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF + + return ds.with_options(options) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/distribution_utils.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/distribution_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..463b799c6dd969761b73adbe1e5cdd7327173b0a --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/distribution_utils.py @@ -0,0 +1,61 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +"""Helper functions for running models in a distributed setting.""" + + +import json +import os + + +def comm_size(): + return int(os.environ.get("OMPI_COMM_WORLD_SIZE", 1)) + + +def comm_rank(): + return int(os.environ.get("OMPI_COMM_WORLD_RANK", 0)) + + +def configure_cluster(worker_hosts=None, task_index=-1): + """Set multi-worker cluster spec in TF_CONFIG environment variable. + + Args: + worker_hosts: comma-separated list of worker ip:port pairs. + + Returns: + Number of workers in the cluster. + """ + tf_config = json.loads(os.environ.get('TF_CONFIG', '{}')) + if tf_config: + num_workers = (len(tf_config['cluster'].get('chief', [])) + + len(tf_config['cluster'].get('worker', []))) + elif worker_hosts: + workers = worker_hosts.split(',') + num_workers = len(workers) + if num_workers > 1 and task_index < 0: + raise ValueError( + 'Must specify task_index when number of workers > 1') + task_index = 0 if num_workers == 1 else task_index + os.environ['TF_CONFIG'] = json.dumps({ + 'cluster': { + 'worker': workers + }, + 'task': {'type': 'worker', 'index': task_index} + }) + else: + num_workers = 1 + return num_workers diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/image_processing.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/image_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..67e31ada0dfd4136b3b3477966ef81e9a51f2524 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/utils/image_processing.py @@ -0,0 +1,468 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +# The code was taken from: +# https://github.com/tensorflow/models/blob/master/research/slim/preprocessing/inception_preprocessing.py +# +# I've renamed the file and modify the code to suit my own need. +# JK Jung, +# +# Changed usage of tensorflow-addons rotate to use keras implementation instead + +"""Provides utilities to preprocess images for the Inception networks.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import random + +import tensorflow as tf + +from tensorflow.python.ops import control_flow_ops +from keras.layers import RandomRotation + +def _smallest_size_at_least(height, width, smallest_side): + """Computes new shape with the smallest side equal to `smallest_side`. + + Computes new shape with the smallest side equal to `smallest_side` while + preserving the original aspect ratio. + + Args: + height: an int32 scalar tensor indicating the current height. + width: an int32 scalar tensor indicating the current width. + smallest_side: A python integer or scalar `Tensor` indicating the size of + the smallest side after resize. + + Returns: + new_height: an int32 scalar tensor indicating the new height. + new_width: and int32 scalar tensor indicating the new width. + """ + smallest_side = tf.convert_to_tensor(value=smallest_side, dtype=tf.int32) + + height = tf.cast(height, dtype=tf.float32) + width = tf.cast(width, dtype=tf.float32) + smallest_side = tf.cast(smallest_side, dtype=tf.float32) + + scale = tf.cond(pred=tf.greater(height, width), + true_fn=lambda: smallest_side / width, + false_fn=lambda: smallest_side / height) + new_height = tf.cast(tf.math.rint(height * scale), dtype=tf.int32) + new_width = tf.cast(tf.math.rint(width * scale), dtype=tf.int32) + return new_height, new_width + + +def _aspect_preserving_resize(image, smallest_side): + """Resize images preserving the original aspect ratio. + + Args: + image: A 3-D image `Tensor`. + smallest_side: A python integer or scalar `Tensor` indicating the size of + the smallest side after resize. + + Returns: + resized_image: A 3-D tensor containing the resized image. + """ + smallest_side = tf.convert_to_tensor(value=smallest_side, dtype=tf.int32) + + shape = tf.shape(input=image) + height = shape[0] + width = shape[1] + new_height, new_width = _smallest_size_at_least(height, width, smallest_side) + image = tf.expand_dims(image, 0) + resized_image = tf.image.resize(image, [new_height, new_width], + method=tf.image.ResizeMethod.BILINEAR) + resized_image = tf.squeeze(resized_image) + resized_image.set_shape([None, None, 3]) + return resized_image + + +def _crop(image, offset_height, offset_width, crop_height, crop_width): + """Crops the given image using the provided offsets and sizes. + + Note that the method doesn't assume we know the input image size but it does + assume we know the input image rank. + + Args: + image: an image of shape [height, width, channels]. + offset_height: a scalar tensor indicating the height offset. + offset_width: a scalar tensor indicating the width offset. + crop_height: the height of the cropped image. + crop_width: the width of the cropped image. + + Returns: + the cropped (and resized) image. + + Raises: + InvalidArgumentError: if the rank is not 3 or if the image dimensions are + less than the crop size. + """ + original_shape = tf.shape(input=image) + + rank_assertion = tf.Assert( + tf.equal(tf.rank(image), 3), + ['Rank of image must be equal to 3.']) + with tf.control_dependencies([rank_assertion]): + cropped_shape = tf.stack([crop_height, crop_width, original_shape[2]]) + + size_assertion = tf.Assert( + tf.logical_and( + tf.greater_equal(original_shape[0], crop_height), + tf.greater_equal(original_shape[1], crop_width)), + ['Crop size greater than the image size.']) + + offsets = tf.cast(tf.stack([offset_height, offset_width, 0]), dtype=tf.int32) + + # Use tf.slice instead of crop_to_bounding box as it accepts tensors to + # define the crop size. + with tf.control_dependencies([size_assertion]): + image = tf.slice(image, offsets, cropped_shape) + return tf.reshape(image, cropped_shape) + + +def _central_crop(image_list, crop_height, crop_width): + """Performs central crops of the given image list. + + Args: + image_list: a list of image tensors of the same dimension but possibly + varying channel. + crop_height: the height of the image following the crop. + crop_width: the width of the image following the crop. + + Returns: + the list of cropped images. + """ + outputs = [] + for image in image_list: + image_height = tf.shape(input=image)[0] + image_width = tf.shape(input=image)[1] + + offset_height = (image_height - crop_height) / 2 + offset_width = (image_width - crop_width) / 2 + + outputs.append(_crop(image, offset_height, offset_width, + crop_height, crop_width)) + return outputs + + +def apply_with_random_selector(x, func, num_cases): + """Computes func(x, sel), with sel sampled from [0...num_cases-1]. + + Args: + x: input Tensor. + func: Python function to apply. + num_cases: Python int32, number of cases to sample sel from. + + Returns: + The result of func(x, sel), where func receives the value of the + selector as a python integer, but sel is sampled dynamically. + """ + sel = tf.random.uniform([], maxval=num_cases, dtype=tf.int32) + # Pass the real x only to one of the func calls. + return control_flow_ops.merge([ + func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case) + for case in range(num_cases)])[0] + + +def distort_color(image, color_ordering=0, fast_mode=True, scope=None): + """Distort the color of a Tensor image. + + Each color distortion is non-commutative and thus ordering of the color ops + matters. Ideally we would randomly permute the ordering of the color ops. + Rather then adding that level of complication, we select a distinct ordering + of color ops for each preprocessing thread. + + Args: + image: 3-D Tensor containing single image in [0, 1]. + color_ordering: Python int, a type of distortion (valid values: 0-3). + fast_mode: Avoids slower ops (random_hue and random_contrast) + scope: Optional scope for name_scope. + Returns: + 3-D Tensor color-distorted image on range [0, 1] + Raises: + ValueError: if color_ordering not in [0, 3] + """ + with tf.compat.v1.name_scope(scope, 'distort_color', [image]): + if fast_mode: + if color_ordering == 0: + image = tf.image.random_brightness(image, max_delta=32. / 255.) + image = tf.image.random_saturation(image, lower=0.5, upper=1.5) + else: + image = tf.image.random_saturation(image, lower=0.5, upper=1.5) + image = tf.image.random_brightness(image, max_delta=32. / 255.) + else: + if color_ordering == 0: + image = tf.image.random_brightness(image, max_delta=32. / 255.) + image = tf.image.random_saturation(image, lower=0.5, upper=1.5) + image = tf.image.random_hue(image, max_delta=0.2) + image = tf.image.random_contrast(image, lower=0.5, upper=1.5) + elif color_ordering == 1: + image = tf.image.random_saturation(image, lower=0.5, upper=1.5) + image = tf.image.random_brightness(image, max_delta=32. / 255.) + image = tf.image.random_contrast(image, lower=0.5, upper=1.5) + image = tf.image.random_hue(image, max_delta=0.2) + elif color_ordering == 2: + image = tf.image.random_contrast(image, lower=0.5, upper=1.5) + image = tf.image.random_hue(image, max_delta=0.2) + image = tf.image.random_brightness(image, max_delta=32. / 255.) + image = tf.image.random_saturation(image, lower=0.5, upper=1.5) + elif color_ordering == 3: + image = tf.image.random_hue(image, max_delta=0.2) + image = tf.image.random_saturation(image, lower=0.5, upper=1.5) + image = tf.image.random_contrast(image, lower=0.5, upper=1.5) + image = tf.image.random_brightness(image, max_delta=32. / 255.) + else: + raise ValueError('color_ordering must be in [0, 3]') + + # The random_* ops do not necessarily clamp. + return tf.clip_by_value(image, 0.0, 1.0) + + +def distorted_bounding_box_crop(image, + bbox, + min_object_covered=0.1, + aspect_ratio_range=(0.75, 1.33), + area_range=(0.05, 1.0), + max_attempts=100, + scope=None): + """Generates cropped_image using a one of the bboxes randomly distorted. + + See `tf.image.sample_distorted_bounding_box` for more documentation. + + Args: + image: 3-D Tensor of image (it will be converted to floats in [0, 1]). + bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] + where each coordinate is [0, 1) and the coordinates are arranged + as [ymin, xmin, ymax, xmax]. If num_boxes is 0 then it would use the whole + image. + min_object_covered: An optional `float`. Defaults to `0.1`. The cropped + area of the image must contain at least this fraction of any bounding box + supplied. + aspect_ratio_range: An optional list of `floats`. The cropped area of the + image must have an aspect ratio = width / height within this range. + area_range: An optional list of `floats`. The cropped area of the image + must contain a fraction of the supplied image within in this range. + max_attempts: An optional `int`. Number of attempts at generating a cropped + region of the image of the specified constraints. After `max_attempts` + failures, return the entire image. + scope: Optional scope for name_scope. + Returns: + A tuple, a 3-D Tensor cropped_image and the distorted bbox + """ + with tf.compat.v1.name_scope(scope, 'distorted_bounding_box_crop', [image, bbox]): + # Each bounding box has shape [1, num_boxes, box coords] and + # the coordinates are ordered [ymin, xmin, ymax, xmax]. + + # A large fraction of image datasets contain a human-annotated bounding + # box delineating the region of the image containing the object of interest. + # We choose to create a new bounding box for the object which is a randomly + # distorted version of the human-annotated bounding box that obeys an + # allowed range of aspect ratios, sizes and overlap with the human-annotated + # bounding box. If no box is supplied, then we assume the bounding box is + # the entire image. + sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box( + image_size=tf.shape(input=image), + bounding_boxes=bbox, + min_object_covered=min_object_covered, + aspect_ratio_range=aspect_ratio_range, + area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=True) + bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box + + # Crop the image to the specified bounding box. + cropped_image = tf.slice(image, bbox_begin, bbox_size) + return cropped_image, distort_bbox + + +def resize_and_rescale_image(image, height, width, + do_mean_subtraction=True, scope=None): + """Prepare one image for training/evaluation. + + Args: + image: 3-D float Tensor + height: integer + width: integer + scope: Optional scope for name_scope. + Returns: + 3-D float Tensor of prepared image. + """ + with tf.compat.v1.name_scope(values=[image, height, width], name=scope, + default_name='resize_image'): + image = tf.expand_dims(image, 0) + image = tf.image.resize(image, [height, width], + method=tf.image.ResizeMethod.BILINEAR) + image = tf.squeeze(image, [0]) + if do_mean_subtraction: + # rescale to [-1,1] + image = tf.subtract(image, 0.5) + image = tf.multiply(image, 2.0) + return image + +def rotate_image (image, angle): + return RandomRotation(factor=math.radians(angle))(image) + +def preprocess_for_train(image, + height, + width, + bbox, + max_angle=15., + fast_mode=True, + scope=None, + add_image_summaries=False): + """Distort one image for training a network. + + Distorting images provides a useful technique for augmenting the data + set during training in order to make the network invariant to aspects + of the image that do not effect the label. + + Additionally it would create image_summaries to display the different + transformations applied to the image. + + Args: + image: 3-D Tensor of image. If dtype is tf.float32 then the range should be + [0, 1], otherwise it would converted to tf.float32 assuming that the range + is [0, MAX], where MAX is largest positive representable number for + int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). + height: integer + width: integer + bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] + where each coordinate is [0, 1) and the coordinates are arranged + as [ymin, xmin, ymax, xmax]. + fast_mode: Optional boolean, if True avoids slower transformations (i.e. + bi-cubic resizing, random_hue or random_contrast). + scope: Optional scope for name_scope. + add_image_summaries: Enable image summaries. + Returns: + 3-D float Tensor of distorted image used for training with range [-1, 1]. + """ + with tf.compat.v1.name_scope(scope, 'distort_image', [image, height, width, bbox]): + assert image.dtype == tf.float32 + # random rotatation of image between -15 to 15 degrees with 0.75 prob + angle = random.uniform(-max_angle, max_angle) \ + if random.random() < 0.75 else 0. + + #original tf1.x code uses tf.contrib, replaced with tf2.x tfa.image + #rotated_image = tf.contrib.image.rotate(image, math.radians(angle), + # interpolation='BILINEAR') + rotated_image = tf.py_function(rotate_image, [image, angle], tf.float32) + + # random cropping + distorted_image, distorted_bbox = distorted_bounding_box_crop( + rotated_image, + bbox, + min_object_covered=0.6, + area_range=(0.6, 1.0)) + # Restore the shape since the dynamic slice based upon the bbox_size loses + # the third dimension. + distorted_image.set_shape([None, None, 3]) + + # This resizing operation may distort the images because the aspect + # ratio is not respected. We select a resize method in a round robin + # fashion based on the thread number. + # Note that ResizeMethod contains 4 enumerated resizing methods. + + # We select only 1 case for fast_mode bilinear. + + #in tf2.x only bilinear interpolation is supported + num_resize_cases = 1 if fast_mode else 4 + distorted_image = apply_with_random_selector( + distorted_image, + #lambda x, method: tf.image.resize(x, [height, width], method), + lambda x, method: tf.image.resize(x, [height, width], tf.image.ResizeMethod.BILINEAR), + num_cases=num_resize_cases) + + #if add_image_summaries: + # tf.summary.image('training_image', + # tf.expand_dims(distorted_image, 0)) + + # Randomly flip the image horizontally. + distorted_image = tf.image.random_flip_left_right(distorted_image) + + # Randomly distort the colors. There are 1 or 4 ways to do it. + num_distort_cases = 1 if fast_mode else 4 + distorted_image = apply_with_random_selector( + distorted_image, + lambda x, ordering: distort_color(x, ordering, fast_mode), + num_cases=num_distort_cases) + + #if add_image_summaries: + # tf.summary.image('final_distorted_image', + # tf.expand_dims(distorted_image, 0)) + + distorted_image = tf.subtract(distorted_image, 0.5) + distorted_image = tf.multiply(distorted_image, 2.0) + return distorted_image + + +def preprocess_for_eval(image, + height, + width, + scope=None, + add_image_summaries=False): + """Prepare one image for evaluation. + + Args: + image: 3-D Tensor of image. If dtype is tf.float32 then the range should be + [0, 1], otherwise it would converted to tf.float32 assuming that the range + is [0, MAX], where MAX is largest positive representable number for + int(8/16/32) data type (see `tf.image.convert_image_dtype` for details). + height: integer + width: integer + scope: Optional scope for name_scope. + Returns: + 3-D float Tensor of prepared image. + """ + with tf.compat.v1.name_scope(scope, 'eval_image', [image, height, width]): + assert image.dtype == tf.float32 + #image = resize_and_rescale_image(image, 256, 256, + # do_mean_subtraction=False) + image = _aspect_preserving_resize(image, max(height, width)) + image = _central_crop([image], height, width)[0] + image.set_shape([height, width, 3]) + + #if add_image_summaries: + # tf.summary.image('validation_image', tf.expand_dims(image, 0)) + + image = tf.subtract(image, 0.5) + image = tf.multiply(image, 2.0) + return image + + +def preprocess_image(image, + height, + width, + is_training=False): + """Pre-process one image for training or evaluation. + + Args: + image: 3-D Tensor [height, width, channels] with the image. + height: integer, image expected height. + width: integer, image expected width. + is_training: Boolean. If true it would transform an image for train, + otherwise it would transform it for evaluation. + fast_mode: Optional boolean, if True avoids slower transformations. + + Returns: + 3-D float Tensor containing an appropriately scaled image + """ + if is_training: + bbox = tf.constant([0.0, 0.0, 1.0, 1.0], + dtype=tf.float32, + shape=[1, 1, 4]) + return preprocess_for_train(image, height, width, bbox, fast_mode=True) + else: + return preprocess_for_eval(image, height, width) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/__init__.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6c8e6b979c5f58121ac7ee2d9e024749da3a8ce1 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/__init__.py @@ -0,0 +1 @@ +__version__ = "0.0.0" diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/layers.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..19441b4d39564d9f1d47b0f99999522488117523 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/layers.py @@ -0,0 +1,184 @@ +# pylint: disable=arguments-differ,missing-function-docstring,missing-class-docstring,unexpected-keyword-arg,no-value-for-parameter +import tensorflow as tf + + +@tf.keras.utils.register_keras_serializable() +class ClassToken(tf.keras.layers.Layer): + """Append a class token to an input layer.""" + + def build(self, input_shape): + cls_init = tf.zeros_initializer() + self.hidden_size = input_shape[-1] + self.cls = tf.Variable( + name="cls", + initial_value=cls_init(shape=(1, 1, self.hidden_size), dtype="float32"), + trainable=True, + ) + + def call(self, inputs): + batch_size = tf.shape(inputs)[0] + cls_broadcasted = tf.cast( + tf.broadcast_to(self.cls, [batch_size, 1, self.hidden_size]), + dtype=inputs.dtype, + ) + return tf.concat([cls_broadcasted, inputs], 1) + + def get_config(self): + config = super().get_config() + return config + + @classmethod + def from_config(cls, config): + return cls(**config) + + +@tf.keras.utils.register_keras_serializable() +class AddPositionEmbs(tf.keras.layers.Layer): + """Adds (optionally learned) positional embeddings to the inputs.""" + + def build(self, input_shape): + assert ( + len(input_shape) == 3 + ), f"Number of dimensions should be 3, got {len(input_shape)}" + self.pe = tf.Variable( + name="pos_embedding", + initial_value=tf.random_normal_initializer(stddev=0.06)( + shape=(1, input_shape[1], input_shape[2]) + ), + dtype="float32", + trainable=True, + ) + + def call(self, inputs): + return inputs + tf.cast(self.pe, dtype=inputs.dtype) + + def get_config(self): + config = super().get_config() + return config + + @classmethod + def from_config(cls, config): + return cls(**config) + + +@tf.keras.utils.register_keras_serializable() +class MultiHeadSelfAttention(tf.keras.layers.Layer): + def __init__(self, *args, num_heads, **kwargs): + super().__init__(*args, **kwargs) + self.num_heads = num_heads + + def build(self, input_shape): + hidden_size = input_shape[-1] + num_heads = self.num_heads + if hidden_size % num_heads != 0: + raise ValueError( + f"embedding dimension = {hidden_size} should be divisible by number of heads = {num_heads}" + ) + self.hidden_size = hidden_size + self.projection_dim = hidden_size // num_heads + self.query_dense = tf.keras.layers.Dense(hidden_size, name="query") + self.key_dense = tf.keras.layers.Dense(hidden_size, name="key") + self.value_dense = tf.keras.layers.Dense(hidden_size, name="value") + self.combine_heads = tf.keras.layers.Dense(hidden_size, name="out") + + # pylint: disable=no-self-use + def attention(self, query, key, value): + score = tf.matmul(query, key, transpose_b=True) + dim_key = tf.cast(tf.shape(key)[-1], score.dtype) + scaled_score = score / tf.math.sqrt(dim_key) + weights = tf.nn.softmax(scaled_score, axis=-1) + output = tf.matmul(weights, value) + return output, weights + + def separate_heads(self, x, batch_size): + x = tf.reshape(x, (batch_size, -1, self.num_heads, self.projection_dim)) + return tf.transpose(x, perm=[0, 2, 1, 3]) + + def call(self, inputs): + batch_size = tf.shape(inputs)[0] + query = self.query_dense(inputs) + key = self.key_dense(inputs) + value = self.value_dense(inputs) + query = self.separate_heads(query, batch_size) + key = self.separate_heads(key, batch_size) + value = self.separate_heads(value, batch_size) + + attention, weights = self.attention(query, key, value) + attention = tf.transpose(attention, perm=[0, 2, 1, 3]) + concat_attention = tf.reshape(attention, (batch_size, -1, self.hidden_size)) + output = self.combine_heads(concat_attention) + return output, weights + + def get_config(self): + config = super().get_config() + config.update({"num_heads": self.num_heads}) + return config + + @classmethod + def from_config(cls, config): + return cls(**config) + + +# pylint: disable=too-many-instance-attributes +@tf.keras.utils.register_keras_serializable() +class TransformerBlock(tf.keras.layers.Layer): + """Implements a Transformer block.""" + + def __init__(self, *args, num_heads, mlp_dim, dropout, **kwargs): + super().__init__(*args, **kwargs) + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.dropout = dropout + + def build(self, input_shape): + self.att = MultiHeadSelfAttention( + num_heads=self.num_heads, + name="MultiHeadDotProductAttention_1", + ) + self.mlpblock = tf.keras.Sequential( + [ + tf.keras.layers.Dense( + self.mlp_dim, + activation="linear", + name=f"{self.name}/Dense_0", + ), + tf.keras.layers.Lambda( + lambda x: tf.keras.activations.gelu(x, approximate=False) + ), + tf.keras.layers.Dropout(self.dropout), + tf.keras.layers.Dense(input_shape[-1], name=f"{self.name}/Dense_1"), + tf.keras.layers.Dropout(self.dropout), + ], + name="MlpBlock_3", + ) + self.layernorm1 = tf.keras.layers.LayerNormalization( + epsilon=1e-6, name="LayerNorm_0" + ) + self.layernorm2 = tf.keras.layers.LayerNormalization( + epsilon=1e-6, name="LayerNorm_2" + ) + self.dropout_layer = tf.keras.layers.Dropout(self.dropout) + + def call(self, inputs, training): + x = self.layernorm1(inputs) + x, weights = self.att(x) + x = self.dropout_layer(x, training=training) + x = x + inputs + y = self.layernorm2(x) + y = self.mlpblock(y) + return x + y, weights + + def get_config(self): + config = super().get_config() + config.update( + { + "num_heads": self.num_heads, + "mlp_dim": self.mlp_dim, + "dropout": self.dropout, + } + ) + return config + + @classmethod + def from_config(cls, config): + return cls(**config) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/utils.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..da3252d20fc3a351cb6484eaa32f3c61a45c0149 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/utils.py @@ -0,0 +1,207 @@ +import os +import typing +import warnings +from urllib import request +from http import client +import io +import pkg_resources +#import validators +import numpy as np +import scipy as sp +import cv2 + +try: + import PIL + import PIL.Image +except ImportError: # pragma: no cover + PIL = None + +ImageInputType = typing.Union[str, np.ndarray, "PIL.Image.Image", io.BytesIO] + + +def get_imagenet_classes() -> typing.List[str]: + """Get the list of ImageNet 2012 classes.""" + filepath = pkg_resources.resource_filename("vit_keras", "imagenet2012.txt") + with open(filepath) as f: + classes = [l.strip() for l in f.readlines()] + return classes + + +def read(filepath_or_buffer: ImageInputType, size, timeout=None): + """Read a file into an image object + Args: + filepath_or_buffer: The path to the file or any object + with a `read` method (such as `io.BytesIO`) + size: The size to resize the image to. + timeout: If filepath_or_buffer is a URL, the timeout to + use for making the HTTP request. + """ + if PIL is not None and isinstance(filepath_or_buffer, PIL.Image.Image): + return np.array(filepath_or_buffer.convert("RGB")) + if isinstance(filepath_or_buffer, (io.BytesIO, client.HTTPResponse)): + image = np.asarray(bytearray(filepath_or_buffer.read()), dtype=np.uint8) + image = cv2.imdecode(image, cv2.IMREAD_UNCHANGED) + elif isinstance(filepath_or_buffer, str) and validators.url(filepath_or_buffer): + return read(request.urlopen(filepath_or_buffer, timeout=timeout), size=size) + else: + if not os.path.isfile(filepath_or_buffer): + raise FileNotFoundError( + "Could not find image at path: " + filepath_or_buffer + ) + image = cv2.imread(filepath_or_buffer) + if image is None: + raise ValueError(f"An error occurred reading {filepath_or_buffer}.") + # We use cvtColor here instead of just ret[..., ::-1] + # in order to ensure that we provide a contiguous + # array for later processing. Some hashers use ctypes + # to pass the array and non-contiguous arrays can lead + # to erroneous results. + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + return cv2.resize(image, (size, size)) + + +def apply_embedding_weights(target_layer, source_weights): + """Apply embedding weights to a target layer. + + Args: + target_layer: The target layer to which weights will + be applied. + source_weights: The source weights, which will be + resized as necessary. + """ + expected_shape = target_layer.weights[0].shape + if expected_shape != source_weights.shape: + token, grid = source_weights[0, :1], source_weights[0, 1:] + sin = int(np.sqrt(grid.shape[0])) + sout = int(np.sqrt(expected_shape[1] - 1)) + warnings.warn( + "Resizing position embeddings from " f"{sin} to {sout}", + UserWarning, + ) + zoom = (sout / sin, sout / sin, 1) + grid = sp.ndimage.zoom(grid.reshape(sin, sin, -1), zoom, order=1).reshape( + sout * sout, -1 + ) + source_weights = np.concatenate([token, grid], axis=0)[np.newaxis] + target_layer.set_weights([source_weights]) + + +def load_weights_numpy(model, params_path, pretrained_top): + """Load weights saved using Flax as a numpy array. + + Args: + model: A Keras model to load the weights into. + params_path: Filepath to a numpy archive. + pretrained_top: Whether to load the top layer weights. + """ + params_dict = np.load( + params_path, allow_pickle=False + ) # pylint: disable=unexpected-keyword-arg + source_keys = list(params_dict.keys()) + pre_logits = any(l.name == "pre_logits" for l in model.layers) + source_keys_used = [] + n_transformers = len( + set( + "/".join(k.split("/")[:2]) + for k in source_keys + if k.startswith("Transformer/encoderblock_") + ) + ) + n_transformers_out = sum( + l.name.startswith("Transformer/encoderblock_") for l in model.layers + ) + assert n_transformers == n_transformers_out, ( + f"Wrong number of transformers (" + f"{n_transformers_out} in model vs. {n_transformers} in weights)." + ) + + matches = [] + for tidx in range(n_transformers): + encoder = model.get_layer(f"Transformer/encoderblock_{tidx}") + source_prefix = f"Transformer/encoderblock_{tidx}" + matches.extend( + [ + { + "layer": layer, + "keys": [ + f"{source_prefix}/{norm}/{name}" for name in ["scale", "bias"] + ], + } + for norm, layer in [ + ("LayerNorm_0", encoder.layernorm1), + ("LayerNorm_2", encoder.layernorm2), + ] + ] + + [ + { + "layer": encoder.mlpblock.get_layer( + f"{source_prefix}/Dense_{mlpdense}" + ), + "keys": [ + f"{source_prefix}/MlpBlock_3/Dense_{mlpdense}/{name}" + for name in ["kernel", "bias"] + ], + } + for mlpdense in [0, 1] + ] + + [ + { + "layer": layer, + "keys": [ + f"{source_prefix}/MultiHeadDotProductAttention_1/{attvar}/{name}" + for name in ["kernel", "bias"] + ], + "reshape": True, + } + for attvar, layer in [ + ("query", encoder.att.query_dense), + ("key", encoder.att.key_dense), + ("value", encoder.att.value_dense), + ("out", encoder.att.combine_heads), + ] + ] + ) + for layer_name in ["embedding", "head", "pre_logits"]: + if layer_name == "head" and not pretrained_top: + source_keys_used.extend(["head/kernel", "head/bias"]) + continue + if layer_name == "pre_logits" and not pre_logits: + continue + matches.append( + { + "layer": model.get_layer(layer_name), + "keys": [f"{layer_name}/{name}" for name in ["kernel", "bias"]], + } + ) + matches.append({"layer": model.get_layer("class_token"), "keys": ["cls"]}) + matches.append( + { + "layer": model.get_layer("Transformer/encoder_norm"), + "keys": [f"Transformer/encoder_norm/{name}" for name in ["scale", "bias"]], + } + ) + apply_embedding_weights( + target_layer=model.get_layer("Transformer/posembed_input"), + source_weights=params_dict["Transformer/posembed_input/pos_embedding"], + ) + source_keys_used.append("Transformer/posembed_input/pos_embedding") + for match in matches: + source_keys_used.extend(match["keys"]) + source_weights = [params_dict[k] for k in match["keys"]] + if match.get("reshape", False): + source_weights = [ + source.reshape(expected.shape) + for source, expected in zip( + source_weights, match["layer"].get_weights() + ) + ] + match["layer"].set_weights(source_weights) + unused = set(source_keys).difference(source_keys_used) + if unused: + warnings.warn(f"Did not use the following weights: {unused}", UserWarning) + target_keys_set = len(source_keys_used) + target_keys_all = len(model.weights) + if target_keys_set < target_keys_all: + warnings.warn( + f"Only set {target_keys_set} of {target_keys_all} weights.", UserWarning + ) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/vit.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..c398e4a674c9fa16cef79e477ca03090fa4a4284 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/VisionTransformer/vit_keras/vit.py @@ -0,0 +1,294 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# - Removed unused imports +# - Weights cache dir is no longer hardcoded +# - Only rank 0 download weights +# - Last layer must be fp32 - required for tf.keras.mixed_precision + +# type: ignore +import warnings +import tensorflow as tf +from . import layers, utils +from utils.distribution_utils import comm_size, comm_rank + +CONFIG_B = { + "dropout": 0.1, + "mlp_dim": 3072, + "num_heads": 12, + "num_layers": 12, + "hidden_size": 768, +} + +CONFIG_L = { + "dropout": 0.1, + "mlp_dim": 4096, + "num_heads": 16, + "num_layers": 24, + "hidden_size": 1024, +} + +BASE_URL = "https://github.com/faustomorales/vit-keras/releases/download/dl" +WEIGHTS = {"imagenet21k": 21_843, "imagenet21k+imagenet2012": 1_000} +SIZES = {"B_16", "B_32", "L_16", "L_32"} + + +def preprocess_inputs(X): + """Preprocess images""" + return tf.keras.applications.imagenet_utils.preprocess_input( + X, data_format=None, mode="tf" + ) + +def build_model( + image_size: int, + patch_size: int, + num_layers: int, + hidden_size: int, + num_heads: int, + name: str, + mlp_dim: int, + classes: int, + dropout=0.1, + activation="linear", + include_top=True, + representation_size=None, +): + """Build a ViT model. + + Args: + image_size: The size of input images. + patch_size: The size of each patch (must fit evenly in image_size) + classes: optional number of classes to classify images + into, only to be specified if `include_top` is True, and + if no `weights` argument is specified. + num_layers: The number of transformer layers to use. + hidden_size: The number of filters to use + num_heads: The number of transformer heads + mlp_dim: The number of dimensions for the MLP output in the transformers. + dropout_rate: fraction of the units to drop for dense layers. + activation: The activation to use for the final layer. + include_top: Whether to include the final classification layer. If not, + the output will have dimensions (batch_size, hidden_size). + representation_size: The size of the representation prior to the + classification layer. If None, no Dense layer is inserted. + """ + assert image_size % patch_size == 0, "image_size must be a multiple of patch_size" + x = tf.keras.layers.Input(shape=(image_size, image_size, 3)) + y = tf.keras.layers.Conv2D( + filters=hidden_size, + kernel_size=patch_size, + strides=patch_size, + padding="valid", + name="embedding", + )(x) + y = tf.keras.layers.Reshape((y.shape[1] * y.shape[2], hidden_size))(y) + y = layers.ClassToken(name="class_token")(y) + y = layers.AddPositionEmbs(name="Transformer/posembed_input")(y) + for n in range(num_layers): + y, _ = layers.TransformerBlock( + num_heads=num_heads, + mlp_dim=mlp_dim, + dropout=dropout, + name=f"Transformer/encoderblock_{n}", + )(y) + y = tf.keras.layers.LayerNormalization( + epsilon=1e-6, name="Transformer/encoder_norm" + )(y) + y = tf.keras.layers.Lambda(lambda v: v[:, 0], name="ExtractToken")(y) + if representation_size is not None: + y = tf.keras.layers.Dense( + representation_size, name="pre_logits", activation="tanh" + )(y) + if include_top: + y = tf.keras.layers.Dense(classes, name="head", activation=activation, dtype='float32')(y) + + return tf.keras.models.Model(inputs=x, outputs=y, name=name) + + + +def validate_pretrained_top( + include_top: bool, pretrained: bool, classes: int, weights: str +): + """Validate that the pretrained weight configuration makes sense.""" + assert weights in WEIGHTS, f"Unexpected weights: {weights}." + expected_classes = WEIGHTS[weights] + if classes != expected_classes: + warnings.warn( + f"Can only use pretrained_top with {weights} if classes = {expected_classes}. Setting manually.", + UserWarning, + ) + assert include_top, "Can only use pretrained_top with include_top." + assert pretrained, "Can only use pretrained_top with pretrained." + return expected_classes + + +def load_pretrained(size, weights, pretrained_top, model): + """Load model weights for a known configuration.""" + fname = f"ViT-{size}_{weights}.npz" + origin = f"{BASE_URL}/{fname}" + from config import config + # If more than 1 process exist - rank 0 download weights, other ranks use same file. + if comm_size() > 1: + from mpi4py import MPI + if comm_rank() == 0: + tf.keras.utils.get_file( + fname, origin, cache_subdir="weights", cache_dir=config.WEIGHTS_DIR) + MPI.COMM_WORLD.Barrier() + local_filepath = tf.keras.utils.get_file( + fname, origin, cache_subdir="weights", cache_dir=config.WEIGHTS_DIR) + + # 'tf.keras.utils.get_file' checks for write access even if such is not required. + # This can lead to another path being used. Warn if such behavior happens. + if config.WEIGHTS_DIR is not None: + import os + import sys + if not os.access(config.WEIGHTS_DIR, os.W_OK) and comm_rank() == 0: + warnings.warn( + f'No write access to {config.WEIGHTS_DIR}, path to weights currently used: {local_filepath}', + UserWarning, + ) + sys.stderr.flush() + + utils.load_weights_numpy(model, local_filepath, pretrained_top) + + # Wait until all ranks have their weights loaded. + if comm_size() > 1: + MPI.COMM_WORLD.Barrier() + + +def vit_b16( + image_size: int = 224, + classes=1000, + activation="linear", + include_top=True, + pretrained=True, + pretrained_top=True, + weights="imagenet21k+imagenet2012", +): + """Build ViT-B16. All arguments passed to build_model.""" + if pretrained_top: + classes = validate_pretrained_top( + include_top=include_top, + pretrained=pretrained, + classes=classes, + weights=weights, + ) + model = build_model( + **CONFIG_B, + name="vit-b16", + patch_size=16, + image_size=image_size, + classes=classes, + activation=activation, + include_top=include_top, + representation_size=768 if weights == "imagenet21k" else None, + ) + if pretrained: + load_pretrained( + size="B_16", weights=weights, model=model, pretrained_top=pretrained_top + ) + + return model + + +def vit_b32( + image_size: int = 224, + classes=1000, + activation="linear", + include_top=True, + pretrained=True, + pretrained_top=True, + weights="imagenet21k+imagenet2012", +): + """Build ViT-B32. All arguments passed to build_model.""" + if pretrained_top: + classes = validate_pretrained_top( + include_top=include_top, + pretrained=pretrained, + classes=classes, + weights=weights, + ) + model = build_model( + **CONFIG_B, + name="vit-b32", + patch_size=32, + image_size=image_size, + classes=classes, + activation=activation, + include_top=include_top, + representation_size=768 if weights == "imagenet21k" else None, + ) + if pretrained: + load_pretrained( + size="B_32", weights=weights, model=model, pretrained_top=pretrained_top + ) + return model + + +def vit_l16( + image_size: int = 384, + classes=1000, + activation="linear", + include_top=True, + pretrained=True, + pretrained_top=True, + weights="imagenet21k+imagenet2012", +): + """Build ViT-L16. All arguments passed to build_model.""" + if pretrained_top: + classes = validate_pretrained_top( + include_top=include_top, + pretrained=pretrained, + classes=classes, + weights=weights, + ) + model = build_model( + **CONFIG_L, + patch_size=16, + name="vit-l16", + image_size=image_size, + classes=classes, + activation=activation, + include_top=include_top, + representation_size=1024 if weights == "imagenet21k" else None, + ) + if pretrained: + load_pretrained( + size="L_16", weights=weights, model=model, pretrained_top=pretrained_top + ) + return model + + +def vit_l32( + image_size: int = 384, + classes=1000, + activation="linear", + include_top=True, + pretrained=True, + pretrained_top=True, + weights="imagenet21k+imagenet2012", +): + """Build ViT-L32. All arguments passed to build_model.""" + if pretrained_top: + classes = validate_pretrained_top( + include_top=include_top, + pretrained=pretrained, + classes=classes, + weights=weights, + ) + model = build_model( + **CONFIG_L, + patch_size=32, + name="vit-l32", + image_size=image_size, + classes=classes, + activation=activation, + include_top=include_top, + representation_size=1024 if weights == "imagenet21k" else None, + ) + if pretrained: + load_pretrained( + size="L_32", weights=weights, model=model, pretrained_top=pretrained_top + ) + return model diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/__init__.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/README.md b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/README.md new file mode 100644 index 0000000000000000000000000000000000000000..171a49e8a0dd8aa07685047ef7ff9dd0b6230688 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/README.md @@ -0,0 +1,5 @@ +# Computer vision common files + +This directory contains computer vision topologies related common files. + +For more information about training deep learning models on Gaudi, visit [developer.habana.ai](https://developer.habana.ai/resources/). \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/cifar_preprocessing.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/cifar_preprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..b7ba2963dcf2dabb206f985d69765b8a6cffb22a --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/cifar_preprocessing.py @@ -0,0 +1,159 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Provides utilities to Cifar-10 dataset.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +from absl import logging +import tensorflow as tf + +from TensorFlow.computer_vision.common import imagenet_preprocessing + +HEIGHT = 32 +WIDTH = 32 +NUM_CHANNELS = 3 +_DEFAULT_IMAGE_BYTES = HEIGHT * WIDTH * NUM_CHANNELS +# The record is the image plus a one-byte label +_RECORD_BYTES = _DEFAULT_IMAGE_BYTES + 1 + +# TODO(tobyboyd): Change to best practice 45K(train)/5K(val)/10K(test) splits. +NUM_IMAGES = { + 'train': 50000, + 'validation': 10000, +} +_NUM_DATA_FILES = 5 +NUM_CLASSES = 10 + + +def parse_record(raw_record, is_training, dtype): + """Parses a record containing a training example of an image. + + The input record is parsed into a label and image, and the image is passed + through preprocessing steps (cropping, flipping, and so on). + + This method converts the label to one hot to fit the loss function. + + Args: + raw_record: scalar Tensor tf.string containing a serialized + Example protocol buffer. + is_training: A boolean denoting whether the input is for training. + dtype: Data type to use for input images. + + Returns: + Tuple with processed image tensor and one-hot-encoded label tensor. + """ + # Convert bytes to a vector of uint8 that is record_bytes long. + record_vector = tf.io.decode_raw(raw_record, tf.uint8) + + # The first byte represents the label, which we convert from uint8 to int32 + # and then to one-hot. + label = tf.cast(record_vector[0], tf.int32) + + # The remaining bytes after the label represent the image, which we reshape + # from [depth * height * width] to [depth, height, width]. + depth_major = tf.reshape(record_vector[1:_RECORD_BYTES], + [NUM_CHANNELS, HEIGHT, WIDTH]) + + # Convert from [depth, height, width] to [height, width, depth], and cast as + # float32. + image = tf.cast(tf.transpose(a=depth_major, perm=[1, 2, 0]), tf.float32) + + image = preprocess_image(image, is_training) + image = tf.cast(image, dtype) + + return image, label + + +def preprocess_image(image, is_training): + """Preprocess a single image of layout [height, width, depth].""" + if is_training: + # Resize the image to add four extra pixels on each side. + image = tf.image.resize_with_crop_or_pad( + image, HEIGHT + 8, WIDTH + 8) + + # Randomly crop a [HEIGHT, WIDTH] section of the image. + image = tf.image.random_crop(image, [HEIGHT, WIDTH, NUM_CHANNELS]) + + # Randomly flip the image horizontally. + image = tf.image.random_flip_left_right(image) + + # Subtract off the mean and divide by the variance of the pixels. + image = tf.image.per_image_standardization(image) + return image + + +def get_filenames(is_training, data_dir): + """Returns a list of filenames.""" + assert tf.io.gfile.exists(data_dir), ( + 'Run cifar10_download_and_extract.py first to download and extract the ' + 'CIFAR-10 data.') + + if is_training: + return [ + os.path.join(data_dir, 'data_batch_%d.bin' % i) + for i in range(1, _NUM_DATA_FILES + 1) + ] + else: + return [os.path.join(data_dir, 'test_batch.bin')] + + +def input_fn(is_training, + data_dir, + batch_size, + dtype=tf.float32, + datasets_num_private_threads=None, + parse_record_fn=parse_record, + input_context=None, + drop_remainder=False): + """Input function which provides batches for train or eval. + + Args: + is_training: A boolean denoting whether the input is for training. + data_dir: The directory containing the input data. + batch_size: The number of samples per batch. + dtype: Data type to use for images/features + datasets_num_private_threads: Number of private threads for tf.data. + parse_record_fn: Function to use for parsing the records. + input_context: A `tf.distribute.InputContext` object passed in by + `tf.distribute.Strategy`. + drop_remainder: A boolean indicates whether to drop the remainder of the + batches. If True, the batch dimension will be static. + + Returns: + A dataset that can be used for iteration. + """ + filenames = get_filenames(is_training, data_dir) + dataset = tf.data.FixedLengthRecordDataset(filenames, _RECORD_BYTES) + + if input_context: + logging.info( + 'Sharding the dataset: input_pipeline_id=%d num_input_pipelines=%d', + input_context.input_pipeline_id, input_context.num_input_pipelines) + dataset = dataset.shard(input_context.num_input_pipelines, + input_context.input_pipeline_id) + + return imagenet_preprocessing.process_record_dataset( + dataset=dataset, + is_training=is_training, + batch_size=batch_size, + shuffle_buffer=NUM_IMAGES['train'], + parse_record_fn=parse_record_fn, + dtype=dtype, + datasets_num_private_threads=datasets_num_private_threads, + drop_remainder=drop_remainder + ) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/imagenet_dataset.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/imagenet_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f8138ae066e7414a8cdf603fee02b704dd8bbc --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/imagenet_dataset.py @@ -0,0 +1,92 @@ +# Copyright (C) 2022-2023 Habana Labs, Ltd. an Intel Company + +import os + +import tensorflow as tf + +from habana_frameworks.tensorflow.multinode_helpers import comm_size, comm_rank + +def media_loader_can_be_used(jpeg_data_dir): + try: + import habana_frameworks.medialoaders + import habana_frameworks.mediapipe + except: + return False + + if jpeg_data_dir is None: + return False + + from habana_frameworks.tensorflow import habana_device + # Media loader is not available for first-gen Gaudi + return habana_device.get_type().split()[0] != "GAUDI" + +def habana_imagenet_dataset(is_training, + jpeg_data_dir, + batch_size, + num_channels, + img_size, + data_type, + use_distributed_eval, + use_pytorch_style_crop=False): + """ + Function responsible for preparing TF dataset with media loader + Args: + is_training: A boolean denoting whether the input is for training. + tf_data_dir: The directory containing the input data in tf_record format - used for fallback. + jpeg_data_dir: The directory containing the input data in jpeg format - used for media loader. + batch_size: The number of samples per batch. + num_channels: Number of channels. + img_size: Image size. + data_type: Data type to use for images/features. + use_distributed_eval: Whether or not to use distributed evaluation. + use_pytorch_style_crop: Whether or not to use pytorch style crop function (using tf algorithm by default) + Returns: + A dataset that can be used for iteration. + """ + + from habana_frameworks.mediapipe.media_types import dtype + if data_type == tf.float32: + media_data_type = dtype.FLOAT32 + elif data_type == tf.bfloat16: + media_data_type = dtype.BFLOAT16 + else: + raise RuntimeError("Unsupported data type {}.".format(data_type)) + + if comm_size() > 1 and (is_training or use_distributed_eval): + num_slices = comm_size() + slice_index = comm_rank() + else: + num_slices = 1 + slice_index = 0 + + from habana_frameworks.mediapipe.media_types import randomCropType + if not is_training: + crop_type = randomCropType.CENTER_CROP + elif use_pytorch_style_crop: + crop_type = randomCropType.RANDOMIZED_AREA_AND_ASPECT_RATIO_CROP + else: + crop_type = randomCropType.RANDOMIZED_ASPECT_RATIO_CROP + + if jpeg_data_dir is not None: + if is_training: + data_dir = os.path.join(jpeg_data_dir, 'train') + else: + data_dir = os.path.join(jpeg_data_dir, 'val') + else: + raise RuntimeError("--jpeg_data_dir not provided") + + queue_depth = 3 + + from TensorFlow.computer_vision.common.resnet_media_pipe import ResnetPipe + pipe = ResnetPipe("hpu", queue_depth, batch_size, num_channels, img_size, img_size, is_training, + data_dir, media_data_type, num_slices, slice_index, crop_type) + + from habana_frameworks.tensorflow.media.habana_dataset import HabanaDataset + dataset = HabanaDataset(output_shapes=[(batch_size, + img_size, + img_size, + num_channels), + (batch_size,)], + output_types=[data_type, tf.float32], pipeline=pipe) + dataset = dataset.prefetch(buffer_size=tf.data.AUTOTUNE) + return dataset diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/imagenet_preprocessing.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/imagenet_preprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..cf88f438be7be4743c2ebafabab585082961a686 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/imagenet_preprocessing.py @@ -0,0 +1,642 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# List of changes: +# - added support for prefetching to HPU +# - flag to specify seed used for dataset shuffling +# - flags to control image preprocessing +# - flag to influence parallelism of dataset processing +# - add habana_imagenet_dataset function call for HPU accelerated data loading +# - move original code of input_fn to imagenet_dataset_fallback +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company + + +"""Provides utilities to preprocess images. + +Training images are sampled using the provided bounding boxes, and subsequently +cropped to the sampled bounding box. Images are additionally flipped randomly, +then resized to the target output size (without aspect-ratio preservation). + +Images used during evaluation are resized (with aspect-ratio preservation) and +centrally cropped. + +All images undergo mean color subtraction. + +Note that these steps are colloquially referred to as "ResNet preprocessing," +and they differ from "VGG preprocessing," which does not use bounding boxes +and instead does an aspect-preserving resize followed by random crop during +training. (These both differ from "Inception preprocessing," which introduces +color distortion steps.) + +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os + +from absl import flags, logging +import tensorflow as tf +try: + import horovod.tensorflow as hvd +except ImportError: + hvd = None + +from TensorFlow.computer_vision.common import imagenet_dataset + +DEFAULT_IMAGE_SIZE = 224 +NUM_CHANNELS = 3 +NUM_CLASSES = 1001 + +NUM_IMAGES = { + 'train': 1281167, + 'validation': 50000, +} + +_NUM_TRAIN_FILES = 1024 +_SHUFFLE_BUFFER = 10000 + +_R_MEAN = 123.68 +_G_MEAN = 116.78 +_B_MEAN = 103.94 +CHANNEL_MEANS = [_R_MEAN, _G_MEAN, _B_MEAN] + +# The lower bound for the smallest side of the image for aspect-preserving +# resizing. For example, if an image is 500 x 1000, it will be resized to +# _RESIZE_MIN x (_RESIZE_MIN * 2). +_RESIZE_MIN = 256 + +flags.DEFINE_integer(name='shuffle_seed', default=None, help='Seed used for dataset shuffling') +flags.DEFINE_integer(name='sample_distorted_bounding_box_seed', default=0, help='Seed used in image preprocessing') +flags.DEFINE_integer(name='random_flip_left_right_seed', default=None, help='Seed used in image preprocessing') +flags.DEFINE_integer(name='dataset_parallel_calls', default=tf.data.experimental.AUTOTUNE, help='Determines the number of parallel calls in dataset operations') +flags.DEFINE_integer(name='interleave_cycle_length', default=10, help='Determines cycle lenght for dataset interleave function') + +def process_record_dataset(dataset, + is_training, + batch_size, + shuffle_buffer, + parse_record_fn, + dtype=tf.float32, + datasets_num_private_threads=None, + drop_remainder=False, + tf_data_experimental_slack=False, + experimental_preloading=False): + """Given a Dataset with raw records, return an iterator over the records. + + Args: + dataset: A Dataset representing raw records + is_training: A boolean denoting whether the input is for training. + batch_size: The number of samples per batch. + shuffle_buffer: The buffer size to use when shuffling records. A larger + value results in better randomness, but smaller values reduce startup + time and use less memory. + parse_record_fn: A function that takes a raw record and returns the + corresponding (image, label) pair. + dtype: Data type to use for images/features. + datasets_num_private_threads: Number of threads for a private + threadpool created for all datasets computation. + drop_remainder: A boolean indicates whether to drop the remainder of the + batches. If True, the batch dimension will be static. + tf_data_experimental_slack: Whether to enable tf.data's + `experimental_slack` option. + + Returns: + Dataset of (image, label) pairs ready for iteration. + """ + # Defines a specific size thread pool for tf.data operations. + if datasets_num_private_threads: + options = tf.data.Options() + options.experimental_threading.private_threadpool_size = ( + datasets_num_private_threads) + dataset = dataset.with_options(options) + logging.info( + 'datasets_num_private_threads: %s', datasets_num_private_threads) + + if is_training: + # Shuffles records before repeating to respect epoch boundaries. + dataset = dataset.shuffle(buffer_size=shuffle_buffer, seed=flags.FLAGS.shuffle_seed) + # Repeats the dataset for the number of epochs to train. + dataset = dataset.repeat() + + if hvd and hvd.is_initialized() and flags.FLAGS.dataset_parallel_calls == tf.data.experimental.AUTOTUNE: + num_parallel_calls = 16 + else: + num_parallel_calls = flags.FLAGS.dataset_parallel_calls + # Parses the raw records into images and labels. + dataset = dataset.map( + lambda value: parse_record_fn(value, is_training, dtype), + num_parallel_calls=num_parallel_calls, deterministic=False) + dataset = dataset.batch(batch_size, drop_remainder=drop_remainder) + + # Operations between the final prefetch and the get_next call to the iterator + # will happen synchronously during run time. We prefetch here again to + # background all of the above processing work and keep it out of the + # critical training path. Setting buffer_size to tf.data.experimental.AUTOTUNE + # allows DistributionStrategies to adjust how many batches to fetch based + # on how many devices are present. + if experimental_preloading: + device = "/device:HPU:0" + with tf.device(device): + dataset = dataset.apply(tf.data.experimental.prefetch_to_device(device)) + else: + dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) + + options = tf.data.Options() + options.experimental_slack = tf_data_experimental_slack + dataset = dataset.with_options(options) + + return dataset + + +def get_filenames(is_training, data_dir): + """Return filenames for dataset.""" + if is_training: + return [ + os.path.join(data_dir, 'train/train-%05d-of-01024' % i) + for i in range(_NUM_TRAIN_FILES)] + else: + return [ + os.path.join(data_dir, 'validation/validation-%05d-of-00128' % i) + for i in range(128)] + + +def parse_example_proto(example_serialized): + """Parses an Example proto containing a training example of an image. + + The output of the build_image_data.py image preprocessing script is a dataset + containing serialized Example protocol buffers. Each Example proto contains + the following fields (values are included as examples): + + image/height: 462 + image/width: 581 + image/colorspace: 'RGB' + image/channels: 3 + image/class/label: 615 + image/class/synset: 'n03623198' + image/class/text: 'knee pad' + image/object/bbox/xmin: 0.1 + image/object/bbox/xmax: 0.9 + image/object/bbox/ymin: 0.2 + image/object/bbox/ymax: 0.6 + image/object/bbox/label: 615 + image/format: 'JPEG' + image/filename: 'ILSVRC2012_val_00041207.JPEG' + image/encoded: + + Args: + example_serialized: scalar Tensor tf.string containing a serialized + Example protocol buffer. + + Returns: + image_buffer: Tensor tf.string containing the contents of a JPEG file. + label: Tensor tf.int32 containing the label. + bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] + where each coordinate is [0, 1) and the coordinates are arranged as + [ymin, xmin, ymax, xmax]. + """ + # Dense features in Example proto. + feature_map = { + 'image/encoded': tf.io.FixedLenFeature([], dtype=tf.string, + default_value=''), + 'image/class/label': tf.io.FixedLenFeature([], dtype=tf.int64, + default_value=-1), + 'image/class/text': tf.io.FixedLenFeature([], dtype=tf.string, + default_value=''), + } + sparse_float32 = tf.io.VarLenFeature(dtype=tf.float32) + # Sparse features in Example proto. + feature_map.update( + {k: sparse_float32 for k in [ + 'image/object/bbox/xmin', 'image/object/bbox/ymin', + 'image/object/bbox/xmax', 'image/object/bbox/ymax']}) + + features = tf.io.parse_single_example(serialized=example_serialized, + features=feature_map) + label = tf.cast(features['image/class/label'], dtype=tf.int32) + + xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, 0) + ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, 0) + xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, 0) + ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, 0) + + # Note that we impose an ordering of (y, x) just to make life difficult. + bbox = tf.concat([ymin, xmin, ymax, xmax], 0) + + # Force the variable number of bounding boxes into the shape + # [1, num_boxes, coords]. + bbox = tf.expand_dims(bbox, 0) + bbox = tf.transpose(a=bbox, perm=[0, 2, 1]) + + return features['image/encoded'], label, bbox + + +def parse_record(raw_record, is_training, dtype): + """Parses a record containing a training example of an image. + + The input record is parsed into a label and image, and the image is passed + through preprocessing steps (cropping, flipping, and so on). + + Args: + raw_record: scalar Tensor tf.string containing a serialized + Example protocol buffer. + is_training: A boolean denoting whether the input is for training. + dtype: data type to use for images/features. + + Returns: + Tuple with processed image tensor in a channel-last format and + one-hot-encoded label tensor. + """ + image_buffer, label, bbox = parse_example_proto(raw_record) + + image = preprocess_image( + image_buffer=image_buffer, + bbox=bbox, + output_height=DEFAULT_IMAGE_SIZE, + output_width=DEFAULT_IMAGE_SIZE, + num_channels=NUM_CHANNELS, + is_training=is_training) + image = tf.cast(image, dtype) + + # Subtract one so that labels are in [0, 1000), and cast to float32 for + # Keras model. + label = tf.cast(tf.cast(tf.reshape(label, shape=[1]), dtype=tf.int32) - 1, + dtype=tf.float32) + return image, label + + +def get_parse_record_fn(use_keras_image_data_format=False): + """Get a function for parsing the records, accounting for image format. + + This is useful by handling different types of Keras models. For instance, + the current resnet_model.resnet50 input format is always channel-last, + whereas the keras_applications mobilenet input format depends on + tf.keras.backend.image_data_format(). We should set + use_keras_image_data_format=False for the former and True for the latter. + + Args: + use_keras_image_data_format: A boolean denoting whether data format is keras + backend image data format. If False, the image format is channel-last. If + True, the image format matches tf.keras.backend.image_data_format(). + + Returns: + Function to use for parsing the records. + """ + def parse_record_fn(raw_record, is_training, dtype): + image, label = parse_record(raw_record, is_training, dtype) + if use_keras_image_data_format: + if tf.keras.backend.image_data_format() == 'channels_first': + image = tf.transpose(image, perm=[2, 0, 1]) + return image, label + return parse_record_fn + + +def imagenet_dataset_fallback(is_training, + data_dir, + batch_size, + dtype=tf.float32, + datasets_num_private_threads=None, + parse_record_fn=parse_record, + input_context=None, + drop_remainder=False, + tf_data_experimental_slack=False, + training_dataset_cache=False, + filenames=None, + experimental_preloading=False, + use_distributed_eval=False): + if filenames is None: + filenames = get_filenames(is_training, data_dir) + dataset = tf.data.Dataset.from_tensor_slices(filenames) + + if hvd and hvd.is_initialized() and (is_training or use_distributed_eval): + logging.info( + 'HVD sharding the dataset: input_pipeline_id=%d num_input_pipelines=%d', + hvd.rank(), hvd.size()) + dataset = dataset.shard(hvd.size(), hvd.rank()) + + if input_context: + logging.info( + 'Sharding the dataset: input_pipeline_id=%d num_input_pipelines=%d', + input_context.input_pipeline_id, input_context.num_input_pipelines) + dataset = dataset.shard(input_context.num_input_pipelines, + input_context.input_pipeline_id) + + if is_training: + # Shuffle the input files + dataset = dataset.shuffle(buffer_size=_NUM_TRAIN_FILES, seed=flags.FLAGS.shuffle_seed) + + # Convert to individual records. + # cycle_length = 10 means that up to 10 files will be read and deserialized in + # parallel. You may want to increase this number if you have a large number of + # CPU cores. + dataset = dataset.interleave( + tf.data.TFRecordDataset, + cycle_length=flags.FLAGS.interleave_cycle_length, + num_parallel_calls=flags.FLAGS.dataset_parallel_calls) + + if is_training and training_dataset_cache: + # Improve training performance when training data is in remote storage and + # can fit into worker memory. + dataset = dataset.cache() + + return process_record_dataset( + dataset=dataset, + is_training=is_training, + batch_size=batch_size, + shuffle_buffer=_SHUFFLE_BUFFER, + parse_record_fn=parse_record_fn, + dtype=dtype, + datasets_num_private_threads=datasets_num_private_threads, + drop_remainder=drop_remainder, + tf_data_experimental_slack=tf_data_experimental_slack, + experimental_preloading=experimental_preloading + ) + + +def input_fn(is_training, + data_dir, + jpeg_data_dir, + batch_size, + dtype=tf.float32, + datasets_num_private_threads=None, + parse_record_fn=parse_record, + input_context=None, + drop_remainder=False, + tf_data_experimental_slack=False, + training_dataset_cache=False, + filenames=None, + experimental_preloading=False, + use_distributed_eval=False): + """Input function which provides batches for train or eval. + + Args: + is_training: A boolean denoting whether the input is for training. + data_dir: The directory containing the input data. + batch_size: The number of samples per batch. + dtype: Data type to use for images/features + datasets_num_private_threads: Number of private threads for tf.data. + parse_record_fn: Function to use for parsing the records. + input_context: A `tf.distribute.InputContext` object passed in by + `tf.distribute.Strategy`. + drop_remainder: A boolean indicates whether to drop the remainder of the + batches. If True, the batch dimension will be static. + tf_data_experimental_slack: Whether to enable tf.data's + `experimental_slack` option. + training_dataset_cache: Whether to cache the training dataset on workers. + Typically used to improve training performance when training data is in + remote storage and can fit into worker memory. + filenames: Optional field for providing the file names of the TFRecords. + + Returns: + A dataset that can be used for iteration. + """ + if imagenet_dataset.media_loader_can_be_used(jpeg_data_dir) is True: + return imagenet_dataset.habana_imagenet_dataset(is_training=is_training, + jpeg_data_dir=jpeg_data_dir, + batch_size=batch_size, + num_channels=NUM_CHANNELS, + img_size=DEFAULT_IMAGE_SIZE, + data_type=dtype, + use_distributed_eval=use_distributed_eval, + use_pytorch_style_crop=True) + else: + return imagenet_dataset_fallback(is_training=is_training, + data_dir=data_dir, + batch_size=batch_size, + dtype=dtype, + datasets_num_private_threads=datasets_num_private_threads, + parse_record_fn=parse_record_fn, + input_context=input_context, + drop_remainder=drop_remainder, + tf_data_experimental_slack=tf_data_experimental_slack, + training_dataset_cache=training_dataset_cache, + filenames=filenames, + experimental_preloading=experimental_preloading, + use_distributed_eval=use_distributed_eval) + + +def _decode_crop_and_flip(image_buffer, bbox, num_channels): + """Crops the given image to a random part of the image, and randomly flips. + + We use the fused decode_and_crop op, which performs better than the two ops + used separately in series, but note that this requires that the image be + passed in as an un-decoded string Tensor. + + Args: + image_buffer: scalar string Tensor representing the raw JPEG image buffer. + bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] + where each coordinate is [0, 1) and the coordinates are arranged as + [ymin, xmin, ymax, xmax]. + num_channels: Integer depth of the image buffer for decoding. + + Returns: + 3-D tensor with cropped image. + + """ + # A large fraction of image datasets contain a human-annotated bounding box + # delineating the region of the image containing the object of interest. We + # choose to create a new bounding box for the object which is a randomly + # distorted version of the human-annotated bounding box that obeys an + # allowed range of aspect ratios, sizes and overlap with the human-annotated + # bounding box. If no box is supplied, then we assume the bounding box is + # the entire image. + sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box( + tf.image.extract_jpeg_shape(image_buffer), + bounding_boxes=bbox, + seed=flags.FLAGS.sample_distorted_bounding_box_seed, + min_object_covered=0.1, + aspect_ratio_range=[0.75, 1.33], + area_range=[0.05, 1.0], + max_attempts=100, + use_image_if_no_bounding_boxes=True) + bbox_begin, bbox_size, _ = sample_distorted_bounding_box + + # Reassemble the bounding box in the format the crop op requires. + offset_y, offset_x, _ = tf.unstack(bbox_begin) + target_height, target_width, _ = tf.unstack(bbox_size) + crop_window = tf.stack([offset_y, offset_x, target_height, target_width]) + + # Use the fused decode and crop op here, which is faster than each in series. + cropped = tf.image.decode_and_crop_jpeg( + image_buffer, crop_window, channels=num_channels) + + # Flip to add a little more random distortion in. + cropped = tf.image.random_flip_left_right(cropped, seed=flags.FLAGS.random_flip_left_right_seed) + return cropped + + +def _central_crop(image, crop_height, crop_width): + """Performs central crops of the given image list. + + Args: + image: a 3-D image tensor + crop_height: the height of the image following the crop. + crop_width: the width of the image following the crop. + + Returns: + 3-D tensor with cropped image. + """ + shape = tf.shape(input=image) + height, width = shape[0], shape[1] + + amount_to_be_cropped_h = (height - crop_height) + crop_top = amount_to_be_cropped_h // 2 + amount_to_be_cropped_w = (width - crop_width) + crop_left = amount_to_be_cropped_w // 2 + return tf.slice( + image, [crop_top, crop_left, 0], [crop_height, crop_width, -1]) + + +def _mean_image_subtraction(image, means, num_channels): + """Subtracts the given means from each image channel. + + For example: + means = [123.68, 116.779, 103.939] + image = _mean_image_subtraction(image, means) + + Note that the rank of `image` must be known. + + Args: + image: a tensor of size [height, width, C]. + means: a C-vector of values to subtract from each channel. + num_channels: number of color channels in the image that will be distorted. + + Returns: + the centered image. + + Raises: + ValueError: If the rank of `image` is unknown, if `image` has a rank other + than three or if the number of channels in `image` doesn't match the + number of values in `means`. + """ + if image.get_shape().ndims != 3: + raise ValueError('Input must be of size [height, width, C>0]') + + if len(means) != num_channels: + raise ValueError('len(means) must match the number of channels') + + # We have a 1-D tensor of means; convert to 3-D. + # Note(b/130245863): we explicitly call `broadcast` instead of simply + # expanding dimensions for better performance. + means = tf.broadcast_to(means, tf.shape(image)) + + return image - means + + +def _smallest_size_at_least(height, width, resize_min): + """Computes new shape with the smallest side equal to `smallest_side`. + + Computes new shape with the smallest side equal to `smallest_side` while + preserving the original aspect ratio. + + Args: + height: an int32 scalar tensor indicating the current height. + width: an int32 scalar tensor indicating the current width. + resize_min: A python integer or scalar `Tensor` indicating the size of + the smallest side after resize. + + Returns: + new_height: an int32 scalar tensor indicating the new height. + new_width: an int32 scalar tensor indicating the new width. + """ + resize_min = tf.cast(resize_min, tf.float32) + + # Convert to floats to make subsequent calculations go smoothly. + height, width = tf.cast(height, tf.float32), tf.cast(width, tf.float32) + + smaller_dim = tf.minimum(height, width) + scale_ratio = resize_min / smaller_dim + + # Convert back to ints to make heights and widths that TF ops will accept. + new_height = tf.cast(height * scale_ratio, tf.int32) + new_width = tf.cast(width * scale_ratio, tf.int32) + + return new_height, new_width + + +def _aspect_preserving_resize(image, resize_min): + """Resize images preserving the original aspect ratio. + + Args: + image: A 3-D image `Tensor`. + resize_min: A python integer or scalar `Tensor` indicating the size of + the smallest side after resize. + + Returns: + resized_image: A 3-D tensor containing the resized image. + """ + shape = tf.shape(input=image) + height, width = shape[0], shape[1] + + new_height, new_width = _smallest_size_at_least(height, width, resize_min) + + return _resize_image(image, new_height, new_width) + + +def _resize_image(image, height, width): + """Simple wrapper around tf.resize_images. + + This is primarily to make sure we use the same `ResizeMethod` and other + details each time. + + Args: + image: A 3-D image `Tensor`. + height: The target height for the resized image. + width: The target width for the resized image. + + Returns: + resized_image: A 3-D tensor containing the resized image. The first two + dimensions have the shape [height, width]. + """ + return tf.compat.v1.image.resize( + image, [height, width], method=tf.image.ResizeMethod.BILINEAR, + align_corners=False) + + +def preprocess_image(image_buffer, bbox, output_height, output_width, + num_channels, is_training=False): + """Preprocesses the given image. + + Preprocessing includes decoding, cropping, and resizing for both training + and eval images. Training preprocessing, however, introduces some random + distortion of the image to improve accuracy. + + Args: + image_buffer: scalar string Tensor representing the raw JPEG image buffer. + bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] + where each coordinate is [0, 1) and the coordinates are arranged as + [ymin, xmin, ymax, xmax]. + output_height: The height of the image after preprocessing. + output_width: The width of the image after preprocessing. + num_channels: Integer depth of the image buffer for decoding. + is_training: `True` if we're preprocessing the image for training and + `False` otherwise. + + Returns: + A preprocessed image. + """ + if is_training: + # For training, we want to randomize some of the distortions. + image = _decode_crop_and_flip(image_buffer, bbox, num_channels) + image = _resize_image(image, output_height, output_width) + else: + # For validation, we want to decode, resize, then just crop the middle. + image = tf.image.decode_jpeg(image_buffer, channels=num_channels) + image = _aspect_preserving_resize(image, _RESIZE_MIN) + image = _central_crop(image, output_height, output_width) + + image.set_shape([output_height, output_width, num_channels]) + + return _mean_image_subtraction(image, CHANNEL_MEANS, num_channels) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/media_pipe_settings.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/media_pipe_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..804722bcb9827895f7fdff15d3865316feb3e0e9 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/media_pipe_settings.py @@ -0,0 +1,18 @@ +# Copyright (C) 2022 Habana Labs, Ltd. an Intel Company + +DECODER_SCALE_MIN = 0.08 +DECODER_SCALE_MAX = 1.0 +DECODER_RATIO_MIN = 3./4. +DECODER_RATIO_MAX = 4./3. + +USE_HORIZONTAL_FLIP = 1 +FLIP_PROBABILITY = 0.5 + +RGB_MEAN_VALUES = [123.68, 116.78, 103.94] + +EVAL_RESIZE = 256 + +EVAL_CROP_X = 0.5 +EVAL_CROP_Y = 0.5 + +TRANSPOSE_DIMS = [2, 0, 1, 3] diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/resnet_media_pipe.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/resnet_media_pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..844534401cee372fc0b95afd73a92689369d9667 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/common/resnet_media_pipe.py @@ -0,0 +1,172 @@ +# Copyright (C) 2022 Habana Labs, Ltd. an Intel Company + +import time + +import numpy as np + +import TensorFlow.computer_vision.common.media_pipe_settings as settings + +try: + from habana_frameworks.mediapipe import fn + from habana_frameworks.mediapipe.mediapipe import MediaPipe + from habana_frameworks.mediapipe.media_types import imgtype, dtype + from habana_frameworks.mediapipe.operators.cpu_nodes.cpu_nodes import media_function + from habana_frameworks.mediapipe.plugins.readers.tfrecord_reader_cpp import tfr_reader_cpp, tfr_reader_params +except: + pass + +class ResnetPipe(MediaPipe): + """ + Class defining resnet media pipe. + + """ + instance_count = 0 + + def __init__(self, device, queue_depth, batch_size, + channel, height, width, is_training, data_dir, + out_dtype, num_slices, slice_index, + random_crop_type): + """ + :params device: device name. + :params queue_depth: Number of preloaded image batches for every slice in mediapipe. <1/2/3> + :params channel: mediapipe image output channel size. + :params height: mediapipe image output height. + :params width: mediapipe image output width. + :params is_training: bool value to state is training pipe or validation pipe. + :params data_dir: dataset directory to be used by dataset reader. + :params out_dtype: output image datatype. + :params num_slices: Total number of slice to be performed on dataset. + :params slice_index: Slice index to be used for this instance of mediapipe. + """ + pipe_type = "Train" if is_training else "Eval" + ResnetPipe.instance_count += 1 + pipe_name = "{}:{}".format( + self.__class__.__name__ + pipe_type, ResnetPipe.instance_count) + pipe_name = str(pipe_name) + + super( + ResnetPipe, + self).__init__( + device=device, + prefetch_depth=queue_depth, + batch_size=batch_size, + pipe_name=pipe_name) + + # Setting repeat count to -1 means there is no predefined limit on number of image batches + # to be iterated through by MediaPipe. With this setting MediaPipe will iterate through + # all batches allocated to the given slice. + self.set_repeat_count(-1) + + self.is_training = is_training + self.out_dtype = out_dtype + + mediapipe_seed = int(time.time_ns() % (2**31 - 1)) + print("media data loader {}/{} seed : {}".format(slice_index, + num_slices, + mediapipe_seed)) + print("media data loader: data_dir:", data_dir) + + # file reader Node + self.input = fn.ReadImageDatasetFromDir(dir=data_dir, format="JPEG", + seed=mediapipe_seed, + shuffle=True, + label_dtype=dtype.FLOAT32, + num_slices=num_slices, + slice_index=slice_index) + + # decoder node + if is_training == True: + self.decode = fn.ImageDecoder(device="Gaudi2", + output_format=imgtype.RGB_P, + random_crop_type=random_crop_type, + resize=[height, width], + scale_min=settings.DECODER_SCALE_MIN, + scale_max=settings.DECODER_SCALE_MAX, + ratio_min=settings.DECODER_RATIO_MIN, + ratio_max=settings.DECODER_RATIO_MAX, + seed=mediapipe_seed) + else: + self.decode = fn.ImageDecoder(device="Gaudi2", + output_format=imgtype.RGB_P, + random_crop_type=random_crop_type, + resize=[settings.EVAL_RESIZE, + settings.EVAL_RESIZE]) + + self.crop = fn.Crop(crop_w=width, + crop_h=height, + crop_pos_x=settings.EVAL_CROP_X, + crop_pos_y=settings.EVAL_CROP_Y) + # Random Flip node + self.random_flip_input = fn.MediaFunc(func=RandomFlipFunction, + shape=[batch_size], + dtype=dtype.UINT8, + seed=mediapipe_seed) + + self.random_flip = fn.RandomFlip(horizontal=settings.USE_HORIZONTAL_FLIP) + # cast data to bf16 for subtraction + self.cast_pre = fn.Cast(dtype=dtype.BFLOAT16) + # substract mean node + mean_data = np.array(settings.RGB_MEAN_VALUES, + dtype=dtype.BFLOAT16) + + self.mean_node = fn.MediaConst(data=mean_data, + shape=[1, 1, mean_data.size], + dtype=dtype.BFLOAT16) + + self.sub = fn.Sub(dtype=dtype.BFLOAT16) + # cast to output datatype + self.cast_pst = fn.Cast(dtype=out_dtype) + # Transpose node + self.pst_transp = fn.Transpose(permutation=settings.TRANSPOSE_DIMS, + tensorDim=len(settings.TRANSPOSE_DIMS), + dtype=out_dtype) + + def definegraph(self): + """ + Method defining dataflow between nodes. + + :returns : output nodes of the graph defined. + """ + jpegs, data = self.input() + if self.is_training == True: + images = self.decode(jpegs) + random_flip_input = self.random_flip_input() + images = self.random_flip(images, random_flip_input) + else: + images = self.decode(jpegs) + images = self.crop(images) + mean = self.mean_node() + images = self.cast_pre(images) + images = self.sub(images, mean) + if self.out_dtype != dtype.BFLOAT16: + images = self.cast_pst(images) + images = self.pst_transp(images) + return images, data + +class RandomFlipFunction(media_function): + """ + Class defining the random flip implementation. + + """ + + def __init__(self, params): + """ + :params params: dictionary of params conatining + shape: output shape of this class. + dtype: output dtype of this class. + seed: seed to be used for randomization. + """ + self.np_shape = params['shape'][::-1] + self.np_dtype = params['dtype'] + self.seed = params['seed'] + self.rng = np.random.default_rng(self.seed) + + def __call__(self): + """ + :returns : random flip values calculated per image. + """ + probabilities = [1.0 - settings.FLIP_PROBABILITY, + settings.FLIP_PROBABILITY] + a = self.rng.choice([0, 1], p=probabilities, size=self.np_shape) + a = np.array(a, dtype=self.np_dtype) + return a diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/LICENSE b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e1c505efcfd17f87243f87874767aa052d526b06 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2021 Habana Labs, Ltd. an Intel Company + +MIT License + +Copyright (c) 2017 Felix Yu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/README.md b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4c8b6b9169f5de062556d6aad4070431479ffb45 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/README.md @@ -0,0 +1,230 @@ +# DenseNet Keras for TensorFlow + +This directory provides a script and recipe to train a DenseNet121 model to achieve state of the art accuracy, and is tested and maintained by Habana. +For further information on performance, refer to [Habana Model Performance Data page](https://developer.habana.ai/resources/habana-training-models/#performance). + +For further information on training deep learning models using Gaudi, refer to [developer.habana.ai](https://developer.habana.ai/resources/). + +## Table Of Contents + +* [Model-References](../../../README.md) +* [Model Overview](#model-overview) +* [Setup](#setup) +* [Training Examples](#training-examples) +* [Advanced](#advanced) +* [Supported Configuration](#supported-configuration) +* [Changelog](#changelog) + +## Model Overview + +For further information on DenseNet Keras model, refer to [Densely Connected Convolutional Networks](https://arxiv.org/abs/1608.06993). + +### Model Changes + +The DenseNet Keras model is a modified version of the original model located in [Fine-tune Convolutional Neural Network in Keras](https://github.com/flyyufelix/cnn_finetune). + +The below lists the major changes applied to the model: + +* Changed some scripts to run the model on Gaudi. This includes loading Habana TensorFlow modules and using multiple Gaudi cards helpers. +* Added support for distributed training using HPUStrategy. +* Optimized data pipeline. +* Removed color distortion and random image rotation from training data augmentation. +* Added learning rate scheduler with warmup and set as default. +* Added kernel and bias regularization including Conv2D and Dense layers. +* Added further TensorBoard and performance logging options. +* Added further synthetic data and tensor dumping options. + + +## Setup + +Please follow the instructions provided in the [Gaudi Installation Guide](https://docs.habana.ai/en/latest/Installation_Guide/GAUDI_Installation_Guide.html) to set up the environment including the `$PYTHON` environment variable. To achieve the best performance, please follow the methods outlined in the [Optimizing Training Platform guide](https://docs.habana.ai/en/latest/TensorFlow/Model_Optimization_TensorFlow/Optimization_Training_Platform.html). +The guides will walk you through the process of setting up your system to run the model on Gaudi. + +### Training Data + +The DenseNet121 script operates on ImageNet 1k, a widely popular image classification dataset from the ILSVRC challenge. +To obtain the dataset, perform the following steps: +1. Sign up with http://image-net.org/download-images and acquire the rights to download original images. +2. Follow the link to the 2012 ILSVRC and download `ILSVRC2012_img_val.tar` and `ILSVRC2012_img_train.tar`. +3. Use the below commands to prepare the dataset under `/data/tensorflow_datasets/imagenet/tf_records`. This is the default data_dir for the training script. + +```bash +export IMAGENET_HOME=/data/tensorflow_datasets/imagenet +mkdir -p $IMAGENET_HOME/validation +mkdir -p $IMAGENET_HOME/train +tar xf ILSVRC2012_img_val.tar -C $IMAGENET_HOME/validation +tar xf ILSVRC2012_img_train.tar -C $IMAGENET_HOME/train +cd $IMAGENET_HOME/train +for f in *.tar; do + d=`basename $f .tar` + mkdir $d + tar xf $f -C $d +done +cd $IMAGENET_HOME +rm $IMAGENET_HOME/train/*.tar # optional +wget -O synset_labels.txt https://raw.githubusercontent.com/tensorflow/models/master/research/slim/datasets/imagenet_2012_validation_synset_labels.txt + +cd Model-References/TensorFlow/computer_vision/Resnets +$PYTHON preprocess_imagenet.py \ + --raw_data_dir=$IMAGENET_HOME \ + --local_scratch_dir=$IMAGENET_HOME/tf_records +``` + +### Clone Habana Model-References + +In the docker container, clone this repository and switch to the branch that matches your SynapseAI version. You can run the [`hl-smi`](https://docs.habana.ai/en/latest/Management_and_Monitoring/System_Management_Tools_Guide/System_Management_Tools.html#hl-smi-utility-options) utility to determine the SynapseAI version. + +```bash +git clone -b [SynapseAI version] https://github.com/HabanaAI/Model-References /root/Model-References +``` + +**Note:** If Model-References repository path is not in the PYTHONPATH, make sure you update it: +```bash +export PYTHONPATH=$PYTHONPATH:/root/Model-References +``` + +### Install Model Requirements + +1. In the docker container, go to the DenseNet directory: + +```bash +cd /root/Model-References/TensorFlow/computer_vision/densenet +``` + +2. Install the required packages using pip: + +```bash +$PYTHON -m pip install -r requirements.txt +``` + +## Training Examples + +### Single Card and Multi-Card Training Examples + +**Run training on 1 HPU:** + +- 1 HPU, batch 256, 90 epochs, BF16 precision, SGD: + + ```bash + $PYTHON train.py \ + --dataset_dir /data/tensorflow_datasets/imagenet/tf_records \ + --dtype bf16 \ + --model densenet121 \ + --optimizer sgd \ + --batch_size 256 \ + --epochs 90 \ + --run_on_hpu + ``` +- 1 HPU, batch 128, 1 epoch, FP32 precision, SGD: + + ```bash + $PYTHON train.py \ + --dataset_dir /data/tensorflow_datasets/imagenet/tf_records \ + --dtype fp32 \ + --model densenet121 \ + --optimizer sgd \ + --batch_size 128 \ + --epochs 1 \ + --run_on_hpu + ``` + +**Run training on 8 HPUs - tf.distribute:** + +**NOTE:** mpirun map-by PE attribute value may vary on your setup. For the recommended calculation, refer to the instructions detailed in [mpirun Configuration](https://docs.habana.ai/en/latest/TensorFlow/Tensorflow_Scaling_Guide/Horovod_Scaling/index.html#mpirun-configuration). + +8 HPUs on 1 server, batch 1024 (128 per HPU), 90 epochs, BF16 precision, SGD: + + ```bash + mpirun --allow-run-as-root --bind-to core --map-by socket:PE=6 -np 8 \ + $PYTHON train.py \ + --dataset_dir /data/tensorflow_datasets/imagenet/tf_records \ + --dtype bf16 \ + --model densenet121 \ + --optimizer sgd \ + --batch_size 1024 \ + --initial_lr 0.28 \ + --epochs 90 \ + --run_on_hpu \ + --use_hpu_strategy + ``` + +## Advanced + +The following sections provide further information on the dataset, running training and inference, and the training results. + +### Scripts and Sample Code + +The following lists the critical files in the root directory: + +* `train.py` - Serves as the entry point to the application, and encapsulates the training routine. +* `densenet.py`- Defines the model architecture. + +The `utils/` folder contains the following required utilities to train a DenseNet model: +* `arguments.py` - Defines the command line argument parser. +* `dataset.py`- Implements the functions defining the data pipeline. +* `image_processing.py` - Implements the data preprocessing and augmentation. + +The `models/` folder contains the following required utilities to allow training: +* `models.py`: Defines utilities necessary for training. +* `optimizers.py`: Defines optimizer utilities. + +### Parameters + +The list of the available parameters for the `train.py` script contains the following: + +``` +Optional arguments: + Name Type Description + --dataset_dir string Path to dataset (default: /data/imagenet/tf_records) + --model_dir string Directory for storing saved model and logs (default:./) + --dtype string Training precision {fp32,bf16} (default: bf16) + --dropout_rate float Dropout rate (default: 0.000000) + --optimizer string Optimizer used for training {sgd,adam,rmsprop} + --batch_size int Training batch size (default: 256) + --initial_lr float Initial lerning rate (default: 0.100000) + --weight_decay float Weight decay (default: 0.000100) + --epochs int Total number of epochs for training (default: 90) + --steps_per_epoch int Number of steps per epoch (default: None) + --validation_steps int Number of validation steps, set to 0 to disable validation (default: None) + --model string Model size {densenet121,densenet161,densenet169} + --train_subset string Name of training subset from dataset_dir + --val_subset string Name of validation subset from dataset_dir + --resume_from_checkpoint_path string Path to checkpoint from which to resume training (default: None) + --resume_from_epoch int Epoch from which to resume training (used in conjunction with resume_from_checkpoint_path argument) (default: 0) + --evaluate_checkpoint_path string Checkpoint path for evaluating the model on --val_subset (default: None) + --seed int Random seed (default: None) + --warmup_epochs int Number of epochs with learning rate warmup (default: 5) + --save_summary_steps int Steps between saving summaries to TensorBoard; when None, logging to TensorBoard is disabled. (enabling this option might affect the performance) (default: None) + +Optional switches: + Name Description + --run_on_hpu Whether to use HPU for training (default: False) + --use_hpu_strategy Enables HPU strategy for distributed training + -h, --help Show this help message and exit +``` +## Supported Configuration + +| Validated on | SynapseAI Version | TensorFlow Version(s) | Mode | +|:------:|:-----------------:|:-----:|:----------:| +| Gaudi | 1.10.0 | 2.12.0 | Training | + +## Changelog + +### 1.4.0 + +* Introduced the `--dataset_num_parallel_calls` script parameter to manipulate a number of threads used to pre-process the dataset in parallel. +* Replaced references to the custom demo script by community entry points in the README. + +### 1.3.0 + +* Aligned the script with new imagenet naming conventions `img_train->train` and `img_val->validation`. +* Added multiple servers configuration. +* Fixed for incorrect LR when checkpoint is loaded. +* Updated the requirements.txt. + +### 1.2.0 + +* Decreased the recommended batch size in the README to 128 per HPU for 1 server scenario to reach accuracy target after 90 epochs. +* Set `--initial_lr` to 0.28 in the README for 128 batch size on 1 server. + * Removed in-code rescaling of the learning rate provided as `--initial_lr` + diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/config.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a5489bb5e353771b3d476a23d71b6254609cca1a --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/config.py @@ -0,0 +1,24 @@ +"""config.py +""" + +import os +import types + + +config = types.SimpleNamespace() + +# Subdirectory name for saving trained weights and models +config.SAVE_DIR = 'saves' + +# Subdirectory name for saving TensorBoard log files +config.LOG_DIR = 'logs' + + +# Default path to the ImageNet TFRecords dataset files +config.DEFAULT_DATASET_DIR = '' + +# Number of parallel workers for generating training/validation data +config.NUM_DATA_WORKERS = 128 + +# Do image data augmentation or not +config.DATA_AUGMENTATION = True diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/densenet.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/densenet.py new file mode 100644 index 0000000000000000000000000000000000000000..f7140ed1a14b7679a494ab8ab5394893a01d95e7 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/densenet.py @@ -0,0 +1,202 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# List of changes: +# - Added Conv2D and Dense kernel and bias regularization +# - Added densent general configuration to support densent121, densenet161, densenet169 + +import tensorflow as tf + +from tensorflow.keras.layers import Input, Concatenate, ZeroPadding2D +from tensorflow.keras.layers import Dense, Dropout, Activation +from tensorflow.keras.layers import Conv2D +from tensorflow.keras.layers import AveragePooling2D, GlobalAveragePooling2D, MaxPooling2D +from tensorflow.keras.layers import BatchNormalization +from tensorflow.keras.models import Model + + +def densenet_model(img_rows, img_cols, color_type=1, nb_dense_block=4, growth_rate=32, nb_filter=64,nb_layers=[6, 12, 24, 16], reduction=0.5, + dropout_rate=0.0, weight_decay=1e-4, num_classes=None): + ''' + DenseNet 121 Model for Keras + + Model Schema is based on + https://github.com/flyyufelix/DenseNet-Keras + + ImageNet Pretrained Weights + Theano: https://drive.google.com/open?id=0Byy2AcGyEVxfMlRYb3YzV210VzQ + TensorFlow: https://drive.google.com/open?id=0Byy2AcGyEVxfSTA4SHJVOHNuTXc + + # Arguments + nb_dense_block: number of dense blocks to add to end + growth_rate: number of filters to add per dense block + nb_filter: initial number of filters + reduction: reduction factor of transition blocks. + dropout_rate: dropout rate + weight_decay: weight decay factor + classes: optional number of classes to classify images + weights_path: path to pre-trained weights + # Returns + A Keras model instance. + ''' + eps = 1.1e-5 + + # compute compression factor + compression = 1.0 - reduction + + # Handle Dimension Ordering for different backends + global concat_axis + + concat_axis = 3 + img_input = Input(shape=(img_rows, img_cols, color_type), name='data') + + + # Initial convolution + x = ZeroPadding2D((3, 3), name='conv1_zeropadding')(img_input) + x = Conv2D(nb_filter, 7, strides=(2, 2), name='conv1', use_bias=False, + kernel_regularizer=tf.keras.regularizers.l2(weight_decay), + bias_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + x = BatchNormalization(epsilon=eps, axis=concat_axis, name='conv1_bn', + beta_regularizer=tf.keras.regularizers.l2(weight_decay), + gamma_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + # x = Scale(axis=concat_axis, name='conv1_scale')(x) + x = Activation('relu', name='relu1')(x) + x = ZeroPadding2D((1, 1), name='pool1_zeropadding')(x) + x = MaxPooling2D((3, 3), strides=(2, 2), name='pool1')(x) + + # Add dense blocks + for block_idx in range(nb_dense_block - 1): + stage = block_idx + 2 + x, nb_filter = dense_block(x, stage, nb_layers[block_idx], nb_filter, growth_rate, dropout_rate=dropout_rate, + weight_decay=weight_decay) + + # Add transition_block + x = transition_block(x, stage, nb_filter, compression=compression, dropout_rate=dropout_rate, + weight_decay=weight_decay) + nb_filter = int(nb_filter * compression) + + final_stage = stage + 1 + x, nb_filter = dense_block(x, final_stage, nb_layers[-1], nb_filter, growth_rate, dropout_rate=dropout_rate, + weight_decay=weight_decay) + + x = BatchNormalization(epsilon=eps, axis=concat_axis, name='conv' + str(final_stage) + '_blk_bn', + beta_regularizer=tf.keras.regularizers.l2(weight_decay), + gamma_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + # x = Scale(axis=concat_axis, name='conv'+str(final_stage)+'_blk_scale')(x) + x = Activation('relu', name='relu' + str(final_stage) + '_blk')(x) + + x_fc = GlobalAveragePooling2D(name='pool' + str(final_stage))(x) + x_fc = Dense(num_classes, kernel_regularizer=tf.keras.regularizers.l2(weight_decay), + bias_regularizer=tf.keras.regularizers.l2(weight_decay), name='fc6')(x_fc) + x_fc = Activation('softmax', name='prob')(x_fc) + + model = Model(img_input, x_fc, name='densenet') + + return model + + +def conv_block(x, stage, branch, nb_filter, dropout_rate=None, weight_decay=1e-4): + '''Apply BatchNorm, Relu, bottleneck 1x1 Conv2D, 3x3 Conv2D, and option dropout + # Arguments + x: input tensor + stage: index for dense block + branch: layer index within each dense block + nb_filter: number of filters + dropout_rate: dropout rate + weight_decay: weight decay factor + ''' + eps = 1.1e-5 + conv_name_base = 'conv' + str(stage) + '_' + str(branch) + relu_name_base = 'relu' + str(stage) + '_' + str(branch) + + # 1x1 Convolution (Bottleneck layer) + inter_channel = nb_filter * 4 + x = BatchNormalization(epsilon=eps, axis=concat_axis, name=conv_name_base + '_x1_bn', + beta_regularizer=tf.keras.regularizers.l2(weight_decay), + gamma_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + # x = Scale(axis=concat_axis, name=conv_name_base+'_x1_scale')(x) + x = Activation('relu', name=relu_name_base + '_x1')(x) + x = Conv2D(inter_channel, 1, name=conv_name_base + '_x1', use_bias=False, + kernel_regularizer=tf.keras.regularizers.l2(weight_decay), + bias_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + + if dropout_rate: + x = Dropout(dropout_rate)(x) + + # 3x3 Convolution + x = BatchNormalization(epsilon=eps, axis=concat_axis, name=conv_name_base + '_x2_bn', + beta_regularizer=tf.keras.regularizers.l2(weight_decay), + gamma_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + # x = Scale(axis=concat_axis, name=conv_name_base+'_x2_scale')(x) + x = Activation('relu', name=relu_name_base + '_x2')(x) + x = ZeroPadding2D((1, 1), name=conv_name_base + '_x2_zeropadding')(x) + x = Conv2D(nb_filter, 3, name=conv_name_base + '_x2', use_bias=False, + kernel_regularizer=tf.keras.regularizers.l2(weight_decay), + bias_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + + if dropout_rate: + x = Dropout(dropout_rate)(x) + + return x + + +def transition_block(x, stage, nb_filter, compression=1.0, dropout_rate=None, weight_decay=1E-4): + ''' Apply BatchNorm, 1x1 Convolution, averagePooling, optional compression, dropout + # Arguments + x: input tensor + stage: index for dense block + nb_filter: number of filters + compression: calculated as 1 - reduction. Reduces the number of feature maps in the transition block. + dropout_rate: dropout rate + weight_decay: weight decay factor + ''' + + eps = 1.1e-5 + conv_name_base = 'conv' + str(stage) + '_blk' + relu_name_base = 'relu' + str(stage) + '_blk' + pool_name_base = 'pool' + str(stage) + + x = BatchNormalization(epsilon=eps, axis=concat_axis, name=conv_name_base + '_bn', + beta_regularizer=tf.keras.regularizers.l2(weight_decay), + gamma_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + # x = Scale(axis=concat_axis, name=conv_name_base+'_scale')(x) + x = Activation('relu', name=relu_name_base)(x) + x = Conv2D(int(nb_filter * compression), 1, name=conv_name_base, use_bias=False, + kernel_regularizer=tf.keras.regularizers.l2(weight_decay), + bias_regularizer=tf.keras.regularizers.l2(weight_decay))(x) + + if dropout_rate: + x = Dropout(dropout_rate)(x) + + x = AveragePooling2D((2, 2), strides=(2, 2), name=pool_name_base)(x) + + return x + + +def dense_block(x, stage, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1e-4, + grow_nb_filters=True): + ''' Build a dense_block where the output of each conv_block is fed to subsequent ones + # Arguments + x: input tensor + stage: index for dense block + nb_layers: the number of layers of conv_block to append to the model. + nb_filter: number of filters + growth_rate: growth rate + dropout_rate: dropout rate + weight_decay: weight decay factor + grow_nb_filters: flag to decide to allow number of filters to grow + ''' + + eps = 1.1e-5 + concat_feat = x + + for i in range(nb_layers): + branch = i + 1 + x = conv_block(concat_feat, stage, branch, growth_rate, dropout_rate, weight_decay) + concat_feat = Concatenate()([concat_feat, x]) + + if grow_nb_filters: + nb_filter += growth_rate + + return concat_feat, nb_filter + diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/LICENSE b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e88239cf6f1ba2a21e9b31863da6db27e9abf0b5 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/LICENSE @@ -0,0 +1,205 @@ +Copyright (c) 2021 Habana Labs, Ltd. an Intel Company + +Copyright 2019 The TensorFlow Authors. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/__init__.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/models.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/models.py new file mode 100644 index 0000000000000000000000000000000000000000..50e720118dfa7a55c91b5567bb56a487e86558e3 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/models.py @@ -0,0 +1,77 @@ +"""models.py + +Implemented model: Densenet121 ('densenet121') +""" +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# Changes: +# -- Removed get_lr_func() method +# -- Added step_decay_with_warmup and StepLearningRateScheduleWithWarmup() + +import tensorflow as tf +import numpy as np +from tensorflow import keras +from tensorflow.keras import backend +from tensorflow.python.framework import ops +from config import config +from .adamw import AdamW +from .optimizer import convert_to_accum_optimizer +from .optimizer import convert_to_lookahead_optimizer + + +def step_decay_with_warmup(global_step, initial_lr, warmup_steps, decay_schedule): + if global_step < warmup_steps: + return initial_lr * float(global_step) / warmup_steps + else: + decay_multiplier = [mulitplier for (decay_step, mulitplier) in decay_schedule.items() + if decay_step <= global_step][-1] + return initial_lr * decay_multiplier + + +class StepLearningRateScheduleWithWarmup(tf.keras.callbacks.Callback): + def __init__(self, initial_lr, initial_global_step, warmup_steps, decay_schedule, verbose=0): + super(StepLearningRateScheduleWithWarmup, self).__init__() + + self.warmup_steps = warmup_steps + self.initial_lr = initial_lr + self.global_step = initial_global_step + self.verbose = verbose + self.decay_schedule = decay_schedule + self.learning_rates = [] + self.verbose = verbose + + def on_train_batch_end(self, batch, logs=None): + learning_rate = tf.keras.backend.get_value(self.model.optimizer.learning_rate) + self.learning_rates.append((self.global_step, learning_rate)) + self.global_step = self.global_step + 1 + + def on_train_batch_begin(self, batch, logs=None): + learning_rate = step_decay_with_warmup(global_step = self.global_step, + initial_lr = self.initial_lr, + warmup_steps = self.warmup_steps, + decay_schedule = self.decay_schedule) + tf.keras.backend.set_value(self.model.optimizer.learning_rate, learning_rate) + if self.verbose > 0 and (self.global_step + 1) % 100 == 0: + print('Step %5d: learning rate: %.5f' % (self.global_step + 1, learning_rate)) + + +def get_optimizer(model_name, optim_name, initial_lr, epsilon=1e-2): + """get_optimizer + + Note: + 1. Learning rate decay is implemented as a callback in model.fit(), + so I do not specify 'decay' in the optimizers here. + 2. Refer to the following for information about 'epsilon' in Adam: + https://github.com/tensorflow/tensorflow/blob/v1.14.0/tensorflow/python/keras/optimizer_v2/adam.py#L93 + """ + if optim_name == 'sgd': + return tf.keras.optimizers.legacy.SGD(learning_rate=initial_lr, momentum=0.9, nesterov=True) + elif optim_name == 'adam': + return tf.keras.optimizers.legacy.Adam(learning_rate=initial_lr, epsilon=epsilon) + elif optim_name == 'rmsprop': + return tf.keras.optimizers.legacy.RMSprop(learning_rate=initial_lr, epsilon=epsilon, + rho=0.9) + else: + # implementation of 'AdamW' is removed temporarily + raise ValueError \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/optimizer.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..64d5322eacd260fb0237c2cd3630ccda7dac36f3 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/models/optimizer.py @@ -0,0 +1,149 @@ +"""optimizer.py + +Code modified from: +https://github.com/keras-team/keras/issues/3556#issuecomment-490375678 + +NOTE: This code most likely does not work for keras OptimizerV2 (in +tensorflow 1.13.0+). +""" + + +import tensorflow as tf +from tensorflow.keras import backend as K + + +def convert_to_accum_optimizer(optimizer, iter_size, do_mean=True): + """Convert a Keras optimizer to make it support 'iter_size' + + # Args + optimizer: the original optimizer + iter_size: accumulate gradients for this meany iterations + do_mean: use mean (average) grandient instead of sum + """ + ver = tf.__version__.split('.') + if int(ver[0]) >= 2 or int(ver[1]) >= 13: + raise RuntimeError('convert_to_accum_optimizer() only supports ' + 'tensorflow version <= 1.12.x!') + if iter_size < 1: + raise ValueError('iter_size must be >= 1') + if hasattr(optimizer, 'iter_size'): + raise RuntimeError('optimizer already has iter_size!') + if hasattr(optimizer, 'orig_get_updates'): + raise RuntimeError('optimizer already has orig_get_updates!') + optimizer.orig_get_gradients = optimizer.get_gradients + optimizer.orig_get_updates = optimizer.get_updates + optimizer.iter_size = K.variable( + iter_size, dtype='int64', name='iter_size') + optimizer.do_mean = do_mean + optimizer.accumulated_iterations = K.variable( + 0, dtype='int64', name='accumulated_iterations') + + def new_get_gradients(self, loss, params): + return self.accumulated_grads + + def new_get_updates(self, loss, params): + self.accumulated_grads = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) + for p in params] + update_iter = [K.update_add(self.accumulated_iterations, 1)] + new_grads = self.orig_get_gradients(loss, params) + if self.do_mean: + new_grads = [g / K.cast(self.iter_size, K.dtype(g)) + for g in new_grads] + update_grads = [K.update_add(p, g) + for p, g in zip(self.accumulated_grads, new_grads)] + + def update_func(): + with tf.control_dependencies(self.orig_get_updates(loss, params)): + reset_grads = [ + K.update(p, K.zeros(K.int_shape(p), dtype=K.dtype(p))) + for p in self.accumulated_grads] + return tf.group(*(reset_grads + update_iter)) + + def just_iter_func(): + return tf.group(*update_iter) + + # do the original get_updates() computations only once every + # 'iter_size' iterations + update_switch = K.equal( + self.accumulated_iterations % self.iter_size, 0) + with tf.control_dependencies(update_grads): + self.updates = [ + K.switch(update_switch, update_func, just_iter_func)] + return self.updates + + # convert new_get_gradients() and new_get_updates() to class methods + optimizer.get_gradients = new_get_gradients.__get__( + optimizer, type(optimizer)) + optimizer.get_updates = new_get_updates.__get__( + optimizer, type(optimizer)) + return optimizer + + +def convert_to_lookahead_optimizer(optimizer, k=5, slow_step=0.5): + """Convert a Keras optimizer to a 'Lookahead' optimizer. + + Refernce: https://arxiv.org/abs/1907.08610 + + # Args + optimizer: the original optimizer + k: update 'slow weights' every k iterations + slow_step: 'slow weights step' in the original paper + """ + ver = tf.__version__.split('.') + if int(ver[0]) >= 2 or int(ver[1]) >= 13: + raise RuntimeError('convert_to_llokahead_optimizer() only supports ' + 'tensorflow version <= 1.12.x!') + if k < 1: + raise ValueError('k must be >= 1') + if slow_step < 0. or slow_step > 1.: + raise ValueError('slow_step must be between 0 and 1') + if hasattr(optimizer, 'orig_get_updates'): + raise RuntimeError('optimizer already has orig_get_updates!') + optimizer.orig_get_gradients = optimizer.get_gradients + optimizer.orig_get_updates = optimizer.get_updates + optimizer.k = K.variable( + k, dtype='int64', name='k') + optimizer.slow_ratio = K.variable( + 1 - slow_step, dtype='float32', name='slow_ratio') + optimizer.fast_ratio = K.variable( + slow_step, dtype='float32', name='fast_ratio') + optimizer.lookahead_iterations = K.variable( + 0, dtype='int64', name='lookahead_iterations') + + def new_get_updates(self, loss, params): + self.slow_params = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) + for p in params] + update_iter = [K.update_add(self.lookahead_iterations, 1)] + + def just_copy_func(): + copy_slow_params = [ + K.update(p, q) for p, q in zip(self.slow_params, params)] + return tf.group(*copy_slow_params) + + def update_func(): + update_params = [ + K.update(q, p * self.slow_ratio + q * self.fast_ratio) + for p, q in zip(self.slow_params, params)] + with tf.control_dependencies(update_params): + reset_slow_params = [ + K.update(p, q) for p, q in zip(self.slow_params, params)] + return tf.group(*(reset_slow_params + update_iter)) + + def just_iter_func(): + return tf.group(*update_iter) + + # copy params to self.slow_params at iteration 0 + copy_switch = K.equal(self.lookahead_iterations, 0) + copy_params = [K.switch(copy_switch, just_copy_func, tf.no_op())] + with tf.control_dependencies(copy_params): + # do the 'slow weights update' every 'k' iterations + update_switch = K.equal(self.lookahead_iterations % self.k, 0) + with tf.control_dependencies(self.orig_get_updates(loss, params)): + self.updates = [ + K.switch(update_switch, update_func, just_iter_func)] + return self.updates + + # convert new_get_updates() to class method + optimizer.get_updates = new_get_updates.__get__( + optimizer, type(optimizer)) + return optimizer diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/requirements.txt b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..1ea3b3aaeaec3ba956b64cc6ab9ee1f091bda777 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/requirements.txt @@ -0,0 +1 @@ +PyYAML==6.0.0 \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/train.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/train.py new file mode 100644 index 0000000000000000000000000000000000000000..0695485d73ed98a4b362a31f203b319c8dc87316 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/train.py @@ -0,0 +1,242 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# List of changes: +# - Added evaluation from saved chekpoint via --evaluate_checkpoint_path flag +# - Added resuming from checkpoint via --resume_from_checkpoint_path and --resume_from_epoch flags +# - Added seed via --seed flag +# - Added densent general configuration to support densent121, densenet161, densenet169 via --model flag +# - Added warmup epochs via --warmup_epochs flag +# - Added support for HPU training with --run_on_hpu flag +# - Added HPUStrategy() distributed training with --use_hpu_strategy +# - Added steps-based training duration specification via --steps_per_epoch and --validation_steps flags +# - Added StepLearningRateScheduleWithWarmup learning rate scheduler for warmup +# - Added deterministic mode + +import tensorflow as tf + +from utils.dataset import get_dataset +from utils.arguments import DenseNetArgumentParser +from utils.misc import distribution_utils +from models.models import StepLearningRateScheduleWithWarmup +from models.models import get_optimizer +from config import config +from densenet import densenet_model + +from TensorFlow.common.debug import dump_callback +from habana_frameworks.tensorflow import load_habana_module +from habana_frameworks.tensorflow.multinode_helpers import comm_size, comm_rank +from habana_frameworks.tensorflow.distribute import HPUStrategy +from TensorFlow.common.tb_utils import ( + TensorBoardWithHParamsV2, ExamplesPerSecondKerasHookV2, TimeToTrainKerasHook) + +import os +import random +import numpy as np + +def set_deterministic(): + os.environ['TF_DETERMINISTIC_OPS'] = '1' + np.random.seed(0) + random.seed(0) + tf.random.set_seed(0) + +def main(): + parser = DenseNetArgumentParser( + description=( + "train.py is the main training/evaluation script for DenseNet. " + "In order to run training on multiple Gaudi cards, run " + "train.py with mpirun.")) + args, _ = parser.parse_known_args() + + strategy = None + verbose = 2 + + if args.deterministic: + if args.inputs is None: + raise ValueError("Must provide inputs for deterministic mode") + if args.resume_from_checkpoint_path is None: + raise ValueError("Must provide checkpoint for deterministic mode") + + if args.dtype == 'bf16': + os.environ['TF_BF16_CONVERSION'] = '1' + + if args.run_on_hpu: + load_habana_module() + if args.use_hpu_strategy: + hls_addresses = str(os.environ.get( + "MULTI_HLS_IPS", "127.0.0.1")).split(",") + TF_BASE_PORT = 2410 + mpi_rank = comm_rank() + mpi_size = comm_size() + if mpi_rank > 0: + verbose = 0 + worker_hosts = ",".join([",".join([address + ':' + str(TF_BASE_PORT + rank) + for rank in range(mpi_size//len(hls_addresses))]) + for address in hls_addresses]) + task_index = mpi_rank + + # Configures cluster spec for distribution strategy. + _ = distribution_utils.configure_cluster(worker_hosts, task_index) + strategy = HPUStrategy() + print('Number of devices: {}'.format( + strategy.num_replicas_in_sync)) + else: + strategy = tf.distribute.MultiWorkerMirroredStrategy() + print('Number of devices: {}'.format(strategy.num_replicas_in_sync)) + + if args.seed is not None: + os.environ['TF_DETERMINISTIC_OPS'] = '1' + random.seed(args.seed) + np.random.seed(args.seed) + tf.random.set_seed(args.seed) + + img_rows, img_cols = 224, 224 # Resolution of inputs + channel = 3 + num_classes = 1000 + batch_size = args.batch_size + nb_epoch = args.epochs + dataset_dir = args.dataset_dir + resume_from_checkpoint_path = args.resume_from_checkpoint_path + resume_from_epoch = args.resume_from_epoch + dropout_rate = args.dropout_rate + weight_decay = args.weight_decay + optim_name = args.optimizer + initial_lr = args.initial_lr + model_name = args.model + save_summary_steps = args.save_summary_steps + + if model_name == "densenet121": + growth_rate = 32 + nb_filter = 64 + nb_layers = [6, 12, 24, 16] + + elif model_name == "densenet161": + growth_rate = 48 + nb_filter = 96 + nb_layers = [6, 12, 36, 24] + + elif model_name == "densenet169": + growth_rate = 32 + nb_filter = 64 + nb_layers = [6, 12, 32, 32] + + else: + print("model is not supported") + exit(1) + + # Load our model + if strategy: + with strategy.scope(): + model = densenet_model(img_rows=img_rows, img_cols=img_cols, color_type=channel, + dropout_rate=dropout_rate, weight_decay=weight_decay, num_classes=num_classes, + growth_rate=growth_rate, nb_filter=nb_filter, nb_layers=nb_layers) + optimizer = get_optimizer( + model_name, optim_name, initial_lr, epsilon=1e-2) + model.compile(optimizer=optimizer, + loss='categorical_crossentropy', metrics=['accuracy']) + else: + model = densenet_model(img_rows=img_rows, img_cols=img_cols, color_type=channel, + dropout_rate=dropout_rate, weight_decay=weight_decay, num_classes=num_classes, + growth_rate=growth_rate, nb_filter=nb_filter, nb_layers=nb_layers) + optimizer = get_optimizer( + model_name, optim_name, initial_lr, epsilon=1e-2) + model.compile(optimizer=optimizer, + loss='categorical_crossentropy', metrics=['accuracy']) + + # Start training + steps_per_epoch = 1281167 // batch_size + if args.steps_per_epoch is not None: + steps_per_epoch = args.steps_per_epoch + validation_steps = 50000 // batch_size + if args.validation_steps is not None: + validation_steps = args.validation_steps + warmup_steps = args.warmup_epochs * steps_per_epoch + lr_sched = {0: 1, 30: 0.1, 60: 0.01, 80: 0.001} + lr_sched_steps = { + epoch * steps_per_epoch: multiplier for (epoch, multiplier) in lr_sched.items()} + init_step=steps_per_epoch * resume_from_epoch if resume_from_epoch is not None else 0 + + lrate = StepLearningRateScheduleWithWarmup(initial_lr=initial_lr, + initial_global_step=init_step, + warmup_steps=warmup_steps, + decay_schedule=lr_sched_steps, + verbose=0) + + save_name = model_name if not model_name.endswith('.h5') else \ + os.path.split(model_name)[-1].split('.')[0].split('-')[0] + + model_ckpt = tf.keras.callbacks.ModelCheckpoint( + os.path.join(args.model_dir, config.SAVE_DIR, + save_name) + '-ckpt-{epoch:03d}.h5', + monitor='train_loss') + + log_dir = os.path.join(args.model_dir, config.LOG_DIR) + ttt = TimeToTrainKerasHook(output_dir=log_dir) + + callbacks = [lrate, model_ckpt, ttt] + + if save_summary_steps is not None and save_summary_steps > 0: + local_batch_size = batch_size + + if args.use_hpu_strategy: + log_dir = os.path.join(log_dir, 'worker_' + str(comm_rank())) + local_batch_size = batch_size // strategy.num_replicas_in_sync + + callbacks += [ + TensorBoardWithHParamsV2( + args.__dict__, log_dir=log_dir, + update_freq=save_summary_steps, profile_batch=0), + ExamplesPerSecondKerasHookV2( + save_summary_steps, output_dir=log_dir, + batch_size=local_batch_size), + ] + + if (args.evaluate_checkpoint_path is not None): + model.load_weights(args.evaluate_checkpoint_path) + results = model.evaluate(x=ds_valid, steps=validation_steps) + print("Test loss, Test acc:", results) + exit() + + if ((resume_from_epoch is not None) and (resume_from_checkpoint_path is not None)): + model.load_weights(resume_from_checkpoint_path) + + if args.deterministic: + set_deterministic() + if not os.path.isfile(args.dump_config): + raise FileNotFoundError("wrong dump config path") + + import pickle + x_path = os.path.join(args.inputs, "input") + y_path = os.path.join(args.inputs, "target") + x = pickle.load(open(x_path, 'rb')) + y = pickle.load(open(y_path, 'rb')) + + with dump_callback(args.dump_config): + model.fit(x=x, y=y, + steps_per_epoch=steps_per_epoch, + callbacks=callbacks, + initial_epoch=resume_from_epoch, + epochs=nb_epoch, + shuffle=False, + verbose=verbose, + validation_data=None, + validation_steps=0, + ) + else: + ds_train = get_dataset(dataset_dir, args.train_subset, batch_size, args.dataset_num_parallel_calls) + ds_valid = get_dataset(dataset_dir, args.val_subset, batch_size, args.dataset_num_parallel_calls) + + model.fit(x=ds_train, y=None, + steps_per_epoch=steps_per_epoch, + callbacks=callbacks, + initial_epoch=resume_from_epoch, + epochs=nb_epoch, + shuffle=True, + verbose=verbose, + validation_data=(ds_valid, None), + validation_steps=validation_steps, + validation_freq=1, + ) + +if __name__ == '__main__': + main() diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/__init__.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/arguments.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..434bb3b980884e9e999ec0f65daad95e609862cc --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/arguments.py @@ -0,0 +1,67 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### + +import argparse + +import tensorflow as tf + + +class DenseNetArgumentParser(argparse.ArgumentParser): + def __init__(self, description): + super().__init__(formatter_class=argparse.ArgumentDefaultsHelpFormatter, + description=description, allow_abbrev=False) + + self.add_argument('--dataset_dir', type=str, default='/data/imagenet/tf_records', + help='path to dataset') + self.add_argument('--model_dir', type=str, default='./', + help='directory for storing saved model and logs') + self.add_argument('--dtype', type=str, choices=['fp32', 'bf16'], default='bf16', + help='data type used during training') + self.add_argument('--dropout_rate', type=float, default=0.0, + help='(default: %(default)f)') + self.add_argument('--optimizer', type=str, default='sgd', + choices=['sgd', 'adam', 'rmsprop']) + self.add_argument('--batch_size', type=int, default=256, + help='(default: %(default)d)') + self.add_argument('--initial_lr', type=float, default=1e-1, + help='(default: %(default)f)') + self.add_argument('--weight_decay', type=float, default=1e-4, + help='(default: %(default)f)') + self.add_argument('--epochs', type=int, default=90, + help='total number of epochs for training') + self.add_argument('--steps_per_epoch', type=int, default=None, + help='number of steps per epoch') + self.add_argument('--validation_steps', type=int, default=None, + help='number of validation steps, set to 0 to disable validation') + self.add_argument('--model', type=str, default='densenet121', + choices=['densenet121', 'densenet161', 'densenet169']) + self.add_argument('--train_subset', type=str, default='train') + self.add_argument('--val_subset', type=str, default='validation') + self.add_argument('--resume_from_checkpoint_path', + type=str, default=None, + help='path to checkpoint from which to resume training') + self.add_argument('--resume_from_epoch', type=int, default=0, + help='from which epoch to resume training (used in ' + 'conjunction with resume_from_checkpoint_path argument)') + self.add_argument('--evaluate_checkpoint_path', type=str, default=None, + help='checkpoint path for evaluating the model on --val_subset ') + self.add_argument('--seed', type=int, default=None, + help='seed for randomness') + self.add_argument('--warmup_epochs', type=int, default=5, + help='number of epochs with learning rate warmup') + self.add_argument('--save_summary_steps', type=int, default=None, + help='steps between saving summaries to TensorBoard; ' + 'when None, logging to TensorBoard is disabled. ' + '(enabling this option might affect the performance)') + self.add_argument('--run_on_hpu', action='store_true', + help='whether to use HPU for training') + self.add_argument('--use_hpu_strategy', action='store_true', + help='enables HPU strategy for distributed training') + self.add_argument('--dump_config', + help='Side-by-side config file. Internal, do not use.') + self.add_argument('--deterministic', action='store_true') + self.add_argument('--inputs', type=str, + help="--inputs . required for deterministic mode") + self.add_argument('--dataset_num_parallel_calls', type=int, default=tf.data.experimental.AUTOTUNE, + help='Determines the number of parallel calls in dataset operations') diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/dataset.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..4c4e29708a850c2a245c9ce7d65602ae18e1b7a3 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/dataset.py @@ -0,0 +1,130 @@ +"""dataset.py + +This module implements functions for reading ImageNet (ILSVRC2012) +dataset in TFRecords format. +""" +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### +# List of changes: +# - Removed dataset.prefetch() from get_dataset() function +# Modified the pipeline in order to used using fused jpeg decode and crop for training +# Set value of num_parallel calls in interleave() and map() calls to +# tf.data.experimental.AUTOTUNE + +import os +from functools import partial + +import tensorflow as tf + +from config import config +from utils.image_processing import preprocess_for_eval, preprocess_for_train + + +def decode_jpeg(image_buffer, scope=None): + """Decode a JPEG string into one 3-D float image Tensor. + + Args: + image_buffer: scalar string Tensor. + scope: Optional scope for name_scope. + Returns: + 3-D float Tensor with values ranging from [0, 1). + """ + with tf.compat.v1.name_scope(values=[image_buffer], name=scope, + default_name='decode_jpeg'): + # Decode the string as an RGB JPEG. + # Note that the resulting image contains an unknown height + # and width that is set dynamically by decode_jpeg. In other + # words, the height and width of image is unknown at compile-i + # time. + image = tf.image.decode_jpeg(image_buffer, channels=3) + + # After this point, all image pixels reside in [0,1) + # until the very end, when they're rescaled to (-1, 1). + # The various adjust_* ops all require this range for dtype + # float. + image = tf.image.convert_image_dtype(image, dtype=tf.float32) + return image + + +def _parse_fn(example_serialized, is_training): + """Helper function for parse_fn_train() and parse_fn_valid() + + Each Example proto (TFRecord) contains the following fields: + + image/height: 462 + image/width: 581 + image/colorspace: 'RGB' + image/channels: 3 + image/class/label: 615 + image/class/synset: 'n03623198' + image/class/text: 'knee pad' + image/format: 'JPEG' + image/filename: 'ILSVRC2012_val_00041207.JPEG' + image/encoded: + + Args: + example_serialized: scalar Tensor tf.string containing a + serialized Example protocol buffer. + is_training: training (True) or validation (False). + + Returns: + image_buffer: Tensor tf.string containing the contents of + a JPEG file. + label: Tensor tf.int32 containing the label. + text: Tensor tf.string containing the human-readable label. + """ + feature_map = { + 'image/encoded': tf.io.FixedLenFeature([], dtype=tf.string, + default_value=''), + 'image/class/label': tf.io.FixedLenFeature([], dtype=tf.int64, + default_value=-1), + 'image/class/text': tf.io.FixedLenFeature([], dtype=tf.string, + default_value=''), + } + parsed = tf.io.parse_single_example(serialized=example_serialized, features=feature_map) + + if is_training: + bbox = tf.constant([0.0, 0.0, 1.0, 1.0], + dtype=tf.float32, + shape=[1, 1, 4]) + image_buffer = parsed['image/encoded'] + # We pass undecoded image buffer for train in order to perform + # fused decode and crop + image = preprocess_for_train(image_buffer, 224, 224, bbox, fast_mode=True) + else: + image = decode_jpeg(parsed['image/encoded']) + image = preprocess_for_eval(image, 224, 224) + + # The label in the tfrecords is 1~1000 (0 not used). + # So I think the minus 1 (of class label) is needed below. + label = tf.one_hot(parsed['image/class/label'] - 1, 1000, dtype=tf.float32) + return (image, label) + + +def get_dataset(tfrecords_dir, subset, batch_size, dataset_num_parallel_calls): + """Read TFRecords files and turn them into a TFRecordDataset.""" + if subset == 'train': + tfrecords_dir = os.path.join(tfrecords_dir, "train") + subset = 'train' + is_training = True + elif subset == 'validation': + tfrecords_dir = os.path.join(tfrecords_dir, "validation") + subset = 'validation' + is_training = False + + files = tf.io.matching_files(os.path.join(tfrecords_dir, '%s-*' % subset)) + shards = tf.data.Dataset.from_tensor_slices(files) + shards = shards.shuffle(tf.cast(tf.shape(input=files)[0], tf.int64)) + shards = shards.repeat() + dataset = shards.interleave(tf.data.TFRecordDataset, + cycle_length=10, + num_parallel_calls=dataset_num_parallel_calls) + dataset = dataset.shuffle(buffer_size=8192) + + parser = partial(_parse_fn, is_training=is_training) + + dataset = dataset.map(map_func=parser, num_parallel_calls=dataset_num_parallel_calls) + dataset = dataset.batch(batch_size=batch_size, drop_remainder=True) + + return dataset \ No newline at end of file diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/keras_callbacks.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/keras_callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..292f01f3ac8112531bed37d25550efe6064f2043 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/keras_callbacks.py @@ -0,0 +1,115 @@ +############################################################################### +# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company +############################################################################### + +import tensorflow as tf +import numpy as np +import random as python_random +import pickle +import os +from tensorflow import keras +import json +from collections import ChainMap +import tensorflow.compat.v1.keras.backend as K +import time + + +def save_output_pickle(output: list, pickle_path: str, fetches: list) -> None: + dump_list = [] + + for idx, fetch in enumerate(fetches): + dump_list.append((fetch, output[idx],)) + + os.makedirs(os.path.dirname(pickle_path), exist_ok=True) + + with open(pickle_path, "wb") as f_out: + pickle.dump(dump_list, f_out) + + +class KerasTensorExtractionCallback(keras.callbacks.Callback): + def __init__(self, model, json_config_file_path): + wights_path = '' + with open(json_config_file_path) as f: + data = json.load(f) + self.wights_path = data['weights'] + # Construction of graph inputs - + self.feed_dict = {} + inputs_dict = dict(ChainMap(*data['inputs'])) + for input_name, path in inputs_dict.items(): + self.feed_dict[input_name] = pickle.load(open(path, 'rb')) + self.dump_tensor_names = data['outputs'] + self.outputDumpPath = data['dump_path'] + self.model = model + + def get_input(self) -> np.ndarray: + return self.feed_dict['input_1:0'] + + def get_target(self)-> np.ndarray: + return self.feed_dict['Logits_target:0'] + + def on_train_batch_begin(self, batch, logs=None) -> None: + # Force deterministic behavior + os.environ['TF_DETERMINISTIC_OPS'] = '1' + np.random.seed(0) + python_random.seed(0) + tf.random.set_seed(0) + + print('KerasTensorExtractionCallback: loading weights from: ' + self.wights_path) + self.model.load_weights(self.wights_path) + + session = K.get_session() + + ops = session.graph.get_operations() + + print('Keras sbs callback: Running the session') + output = session.run(self.dump_tensor_names, self.feed_dict) + + print('KerasTensorExtractionCallback: Saving tensors to - ' + self.outputDumpPath) + save_output_pickle(output, self.outputDumpPath, self.dump_tensor_names) + + print("KerasTensorExtractionCallback: Exiting.") + exit() + + def on_train_batch_end(self, batch, logs=None): + keys = list(logs.keys()) + print("...Training: end of batch {}; got log keys: {}".format(batch, keys)) + + +class KerasMeasurePerfCallback(keras.callbacks.Callback): + def __init__(self, model, batch): + self.model = model + self.batch = batch + self.batch_start = 0 + self.batch_end = 0 + self.max_img_per_sec = 0 + self.average_img_per_sec = 0 + + def on_epoch_begin(self, epoch, logs=None): + keys = list(logs.keys()) + print("Start epoch {} of training; got log keys: {}".format(epoch, keys)) + + def on_epoch_end(self, epoch, logs=None): + keys = list(logs.keys()) + print("End epoch {} of training; got log keys: {}".format(epoch, keys)) + + def on_train_batch_begin(self, batch, logs=None) -> None: + keys = list(logs.keys()) + self.batch_start = start = time.time() + print("Training: start of batch {}; Done comparing tensors. Exiting training.") + + def on_train_batch_end(self, batch, logs=None): + keys = list(logs.keys()) + self.batch_end = time.time() + batch_execution_time = self.batch_end - self.batch_start + images_per_second = self.batch/batch_execution_time + if images_per_second > self.max_img_per_sec: + self.max_img_per_sec = images_per_second + if batch > 0: + self.average_img_per_sec = ((self.average_img_per_sec*(batch))+images_per_second)/(batch+1) + else: + self.average_img_per_sec = images_per_second + print("Images per second : {}".format(images_per_second)) + print("Max Images per second : {}".format(self.max_img_per_sec)) + print("Average Images per second : {}".format(self.average_img_per_sec)) + print(" Batch execution time : {}".format(batch_execution_time)) + print(" Batch size : {}".format(self.batch)) diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/__init__.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e419af524b5f349fe04abfa820c3cb51b777d422 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/distribution_utils.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/distribution_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d194e0ced7b0540862f063f9c64adea4e71f08ef --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/distribution_utils.py @@ -0,0 +1,367 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helper functions for running models in a distributed setting.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import json +import os +import random +import string +import tensorflow as tf + +from TensorFlow.computer_vision.densenet.utils.misc import tpu_lib + +from habana_frameworks.tensorflow.distribute import HPUStrategy + +def _collective_communication(all_reduce_alg): + """Return a CollectiveCommunication based on all_reduce_alg. + + Args: + all_reduce_alg: a string specifying which collective communication to pick, + or None. + + Returns: + tf.distribute.experimental.CollectiveCommunication object + + Raises: + ValueError: if `all_reduce_alg` not in [None, 'ring', 'nccl'] + """ + collective_communication_options = { + None: tf.distribute.experimental.CollectiveCommunication.AUTO, + "ring": tf.distribute.experimental.CollectiveCommunication.RING, + "nccl": tf.distribute.experimental.CollectiveCommunication.NCCL + } + if all_reduce_alg not in collective_communication_options: + raise ValueError( + "When used with `multi_worker_mirrored`, valid values for " + "all_reduce_alg are ['ring', 'nccl']. Supplied value: {}".format( + all_reduce_alg)) + return collective_communication_options[all_reduce_alg] + + +def _mirrored_cross_device_ops(all_reduce_alg, num_packs): + """Return a CrossDeviceOps based on all_reduce_alg and num_packs. + + Args: + all_reduce_alg: a string specifying which cross device op to pick, or None. + num_packs: an integer specifying number of packs for the cross device op. + + Returns: + tf.distribute.CrossDeviceOps object or None. + + Raises: + ValueError: if `all_reduce_alg` not in [None, 'nccl', 'hierarchical_copy']. + """ + if all_reduce_alg is None: + return None + mirrored_all_reduce_options = { + "nccl": tf.distribute.NcclAllReduce, + "hierarchical_copy": tf.distribute.HierarchicalCopyAllReduce + } + if all_reduce_alg not in mirrored_all_reduce_options: + raise ValueError( + "When used with `mirrored`, valid values for all_reduce_alg are " + "['nccl', 'hierarchical_copy']. Supplied value: {}".format( + all_reduce_alg)) + cross_device_ops_class = mirrored_all_reduce_options[all_reduce_alg] + return cross_device_ops_class(num_packs=num_packs) + + +def get_distribution_strategy(distribution_strategy="default", + num_gpus=0, + num_hpus=0, + num_workers=1, + all_reduce_alg=None, + num_packs=1, + tpu_address=None): + """Return a DistributionStrategy for running the model. + + Args: + distribution_strategy: a string specifying which distribution strategy to + use. Accepted values are 'off', 'default', 'one_device', 'mirrored', + 'parameter_server', 'multi_worker_mirrored', and 'tpu' -- case insensitive. + 'off' means not to use Distribution Strategy; 'default' means to choose from + `MirroredStrategy`, `MultiWorkerMirroredStrategy`, or `OneDeviceStrategy` + according to the number of GPUs and number of workers. 'tpu' means to use + TPUStrategy using `tpu_address`. + num_gpus: Number of GPUs to run this model. + num_workers: Number of workers to run this model. + all_reduce_alg: Optional. Specifies which algorithm to use when performing + all-reduce. For `MirroredStrategy`, valid values are "nccl" and + "hierarchical_copy". For `MultiWorkerMirroredStrategy`, valid values are + "ring" and "nccl". If None, DistributionStrategy will choose based on + device topology. + num_packs: Optional. Sets the `num_packs` in `tf.distribute.NcclAllReduce` + or `tf.distribute.HierarchicalCopyAllReduce` for `MirroredStrategy`. + tpu_address: Optional. String that represents TPU to connect to. Must not + be None if `distribution_strategy` is set to `tpu`. + Returns: + tf.distribute.DistibutionStrategy object. + Raises: + ValueError: if `distribution_strategy` is 'off' or 'one_device' and + `num_gpus` is larger than 1; or `num_gpus` is negative or if + `distribution_strategy` is `tpu` but `tpu_address` is not specified. + """ + if num_gpus < 0: + raise ValueError("`num_gpus` can not be negative.") + + distribution_strategy = distribution_strategy.lower() + if distribution_strategy == "off": + if num_gpus > 1: + raise ValueError( + "When {} GPUs and {} workers are specified, distribution_strategy " + "flag cannot be set to 'off'.".format(num_gpus, num_workers)) + return None + + if distribution_strategy == "hpu": + return HPUStrategy() + + if distribution_strategy == "tpu": + # When tpu_address is an empty string, we communicate with local TPUs. + # Initialize TPU System. + cluster_resolver = tpu_lib.tpu_initialize(tpu_address) + return tf.distribute.experimental.TPUStrategy(cluster_resolver) + + if distribution_strategy == "multi_worker_mirrored": + return tf.distribute.experimental.MultiWorkerMirroredStrategy( + communication=_collective_communication(all_reduce_alg)) + + if distribution_strategy == "one_device": + if num_gpus == 0 and num_hpus == 0: + return tf.distribute.OneDeviceStrategy("device:CPU:0") + if num_hpus == 1: + return tf.distribute.OneDeviceStrategy("device:HPU:0") + if num_gpus > 1 or num_hpus > 1: + raise ValueError("`OneDeviceStrategy` can not be used for more than " + "one device.") + return tf.distribute.OneDeviceStrategy("device:GPU:0") + + if distribution_strategy in ("mirrored", "default"): + if num_gpus == 0: + assert distribution_strategy == "mirrored" + devices = ["device:CPU:0"] + else: + devices = ["device:HPU:%d" % i for i in range(num_gpus)] + return tf.distribute.MirroredStrategy( + devices=devices, + cross_device_ops=_mirrored_cross_device_ops(all_reduce_alg, num_packs)) + + if distribution_strategy == "parameter_server": + return tf.distribute.experimental.ParameterServerStrategy() + + raise ValueError( + "Unrecognized Distribution Strategy: %r" % distribution_strategy) + + +def per_replica_batch_size(batch_size, num_gpus): + """For multi-gpu, batch-size must be a multiple of the number of GPUs. + + + Note that distribution strategy handles this automatically when used with + Keras. For using with Estimator, we need to get per GPU batch. + + Args: + batch_size: Global batch size to be divided among devices. This should be + equal to num_gpus times the single-GPU batch_size for multi-gpu training. + num_gpus: How many GPUs are used with DistributionStrategies. + + Returns: + Batch size per device. + + Raises: + ValueError: if batch_size is not divisible by number of devices + """ + if num_gpus <= 1: + return batch_size + + remainder = batch_size % num_gpus + if remainder: + err = ('When running with multiple GPUs, batch size ' + 'must be a multiple of the number of available GPUs. Found {} ' + 'GPUs with a batch size of {}; try --batch_size={} instead.' + ).format(num_gpus, batch_size, batch_size - remainder) + raise ValueError(err) + return int(batch_size / num_gpus) + + +# The `SyntheticDataset` is a temporary solution for generating synthetic data +# directly on devices. It is only useful for Keras with Distribution +# Strategies. We will have better support in `tf.data` or Distribution Strategy +# later. +class SyntheticDataset(object): + """A dataset that generates synthetic data on each device.""" + + def __init__(self, dataset, split_by=1): + # dataset.take(1) doesn't have GPU kernel. + with tf.device('device:CPU:0'): + tensor = tf.data.experimental.get_single_element(dataset.take(1)) + flat_tensor = tf.nest.flatten(tensor) + variable_data = [] + initializers = [] + for t in flat_tensor: + rebatched_t = tf.split(t, num_or_size_splits=split_by, axis=0)[0] + assert rebatched_t.shape.is_fully_defined(), rebatched_t.shape + v = tf.compat.v1.get_local_variable(self._random_name(), + initializer=rebatched_t) + variable_data.append(v) + initializers.append(v.initializer) + input_data = tf.nest.pack_sequence_as(tensor, variable_data) + self._iterator = SyntheticIterator(input_data, initializers) + + def _random_name(self, size=10, chars=string.ascii_uppercase + string.digits): + return ''.join(random.choice(chars) for _ in range(size)) + + def __iter__(self): + return self._iterator + + def make_one_shot_iterator(self): + return self._iterator + + def make_initializable_iterator(self): + return self._iterator + + +class SyntheticIterator(object): + """A dataset that generates synthetic data on each device.""" + + def __init__(self, input_data, initializers): + self._input_data = input_data + self._initializers = initializers + + def get_next(self): + return self._input_data + + def next(self): + return self.__next__() + + def __next__(self): + try: + return self.get_next() + except tf.errors.OutOfRangeError: + raise StopIteration + + def initialize(self): + if tf.executing_eagerly(): + return tf.no_op() + else: + return self._initializers + + +def _monkey_patch_dataset_method(strategy): + """Monkey-patch `strategy`'s `make_dataset_iterator` method.""" + def make_dataset(self, dataset): + tf.compat.v1.logging.info('Using pure synthetic data.') + with self.scope(): + if self.extended._global_batch_size: # pylint: disable=protected-access + return SyntheticDataset(dataset, self.num_replicas_in_sync) + else: + return SyntheticDataset(dataset) + + def make_iterator(self, dataset): + dist_dataset = make_dataset(self, dataset) + return iter(dist_dataset) + + strategy.orig_make_dataset_iterator = strategy.make_dataset_iterator + strategy.make_dataset_iterator = make_iterator + strategy.orig_distribute_dataset = strategy.experimental_distribute_dataset + strategy.experimental_distribute_dataset = make_dataset + + +def _undo_monkey_patch_dataset_method(strategy): + if hasattr(strategy, 'orig_make_dataset_iterator'): + strategy.make_dataset_iterator = strategy.orig_make_dataset_iterator + if hasattr(strategy, 'orig_distribute_dataset'): + strategy.make_dataset_iterator = strategy.orig_distribute_dataset + + +def set_up_synthetic_data(): + _monkey_patch_dataset_method(tf.distribute.OneDeviceStrategy) + _monkey_patch_dataset_method(tf.distribute.MirroredStrategy) + _monkey_patch_dataset_method( + tf.distribute.experimental.MultiWorkerMirroredStrategy) + # TODO(tobyboyd): Remove when contrib.distribute is all in core. + if hasattr(tf, 'contrib'): + _monkey_patch_dataset_method(tf.contrib.distribute.MirroredStrategy) + _monkey_patch_dataset_method(tf.contrib.distribute.OneDeviceStrategy) + _monkey_patch_dataset_method( + tf.contrib.distribute.CollectiveAllReduceStrategy) + else: + print('Contrib missing: Skip monkey patch tf.contrib.distribute.*') + + +def undo_set_up_synthetic_data(): + _undo_monkey_patch_dataset_method(tf.distribute.OneDeviceStrategy) + _undo_monkey_patch_dataset_method(tf.distribute.MirroredStrategy) + _undo_monkey_patch_dataset_method( + tf.distribute.experimental.MultiWorkerMirroredStrategy) + # TODO(tobyboyd): Remove when contrib.distribute is all in core. + if hasattr(tf, 'contrib'): + _undo_monkey_patch_dataset_method(tf.contrib.distribute.MirroredStrategy) + _undo_monkey_patch_dataset_method(tf.contrib.distribute.OneDeviceStrategy) + _undo_monkey_patch_dataset_method( + tf.contrib.distribute.CollectiveAllReduceStrategy) + else: + print('Contrib missing: Skip remove monkey patch tf.contrib.distribute.*') + + +def configure_cluster(worker_hosts=None, task_index=-1): + """Set multi-worker cluster spec in TF_CONFIG environment variable. + + Args: + worker_hosts: comma-separated list of worker ip:port pairs. + + Returns: + Number of workers in the cluster. + """ + tf_config = json.loads(os.environ.get('TF_CONFIG', '{}')) + if tf_config: + num_workers = (len(tf_config['cluster'].get('chief', [])) + + len(tf_config['cluster'].get('worker', []))) + elif worker_hosts: + workers = worker_hosts.split(',') + num_workers = len(workers) + if num_workers > 1 and task_index < 0: + raise ValueError('Must specify task_index when number of workers > 1') + task_index = 0 if num_workers == 1 else task_index + os.environ['TF_CONFIG'] = json.dumps({ + 'cluster': { + 'worker': workers + }, + 'task': {'type': 'worker', 'index': task_index} + }) + else: + num_workers = 1 + return num_workers + + +def get_strategy_scope(strategy): + if strategy: + strategy_scope = strategy.scope() + else: + strategy_scope = DummyContextManager() + + return strategy_scope + + +class DummyContextManager(object): + + def __enter__(self): + pass + + def __exit__(self, *args): + pass diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/tpu_lib.py b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/tpu_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..0a20cbeebcc83d7ea10f8c4dbe5780b7df728a31 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/densenet/utils/misc/tpu_lib.py @@ -0,0 +1,38 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Initializes TPU system for TF 2.0.""" + +import tensorflow as tf + + +def tpu_initialize(tpu_address): + """Initializes TPU for TF 2.0 training. + + Args: + tpu_address: string, bns address of TPU workers. + + Returns: + A TPUClusterResolver. + """ + cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( + tpu=tpu_address) + tf.config.experimental_connect_to_host(cluster_resolver.master()) + tf.tpu.experimental.initialize_tpu_system(cluster_resolver) + return cluster_resolver + + +def get_primary_cpu_task(use_remote_tpu=False): + """Returns remote TPU worker address. No-op for GPU/CPU training.""" + return "/job:worker" if use_remote_tpu else "" diff --git a/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/maskrcnn/LICENSE b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/maskrcnn/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..57787c796703717732ac12430832510fcb754fd2 --- /dev/null +++ b/docker/intel_code/llama13b/Model-References/TensorFlow/computer_vision/maskrcnn/LICENSE @@ -0,0 +1,203 @@ +Copyright (c) 2021 Habana Labs, Ltd. an Intel Company + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2019 NVIDIA Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/docker/output_bkp/hf_ckpt/pytorch_model.bin b/docker/output_bkp/hf_ckpt/pytorch_model.bin new file mode 100644 index 0000000000000000000000000000000000000000..d013a72eb95e7d7e2860d351612dd3d1edfd0d0c --- /dev/null +++ b/docker/output_bkp/hf_ckpt/pytorch_model.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7262454108c256412fb075e3cd9597f27adae42d744cf950713efd086226ebe +size 22377348706 diff --git a/utilities/l3-routes b/utilities/l3-routes new file mode 100644 index 0000000000000000000000000000000000000000..9e4872333db61b141d7064613a75e999d5e93107 --- /dev/null +++ b/utilities/l3-routes @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56e35cab088d4052276deed055dbb4b80dc4c60edf0fdb09c6b64bd2a1b414c0 +size 3222751