π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Add tpu-testing in circleci (#787)
Edgar Riba0cc446656324
diff --git a/.circleci/config.yml b/.circleci/config.ymlnew file mode 100644index 000000000..33b48c02f--- /dev/null+++ b/.circleci/config.yml@@ -0,0 +1,137 @@+# Python CircleCI 2.1 configuration file.+version: 2.1+orbs:+ gcp-gke: circleci/[email protected]+ go: circleci/[email protected]+ #codecov: codecov/[email protected]++references:++ checkout_ml_testing: &checkout_ml_testing+ run:+ name: Checkout ml-testing-accelerators+ command: |+ git clone https://github.com/GoogleCloudPlatform/ml-testing-accelerators.git+ cd ml-testing-accelerators+ git fetch origin 5e88ac24f631c27045e62f0e8d5dfcf34e425e25:stable+ git checkout stable+ cd ..+ build_push_docker: &build_push_docker+ run:+ name: Build and push Docker image+ command: |+ gcloud --quiet auth configure-docker+ cd docker/tpu-tests+ docker build --tag "$GCR_IMAGE_PATH:$CIRCLE_WORKFLOW_JOB_ID" -f Dockerfile --build-arg "PYTHON_VERSION=$PYTHON_VER" --build-arg "PYTORCH_VERSION=$PYTORCH_VER" --build-arg "GITHUB_REF=pull/$CIRCLE_PR_NUMBER/head" .+ docker push "$GCR_IMAGE_PATH:$CIRCLE_WORKFLOW_JOB_ID"++ deploy_cluster: &deploy_cluster+ run:+ name: Deploy the job on the kubernetes cluster+ command: |+ go get github.com/google/go-jsonnet/cmd/jsonnet+ export PATH=$PATH:$HOME/go/bin+ job_name=$(jsonnet -J ml-testing-accelerators/ docker/tpu-tests/tpu_test_cases.jsonnet --ext-str image=$GCR_IMAGE_PATH --ext-str image-tag=$CIRCLE_WORKFLOW_JOB_ID | kubectl create -f -)+ job_name=${job_name#job.batch/}+ job_name=${job_name% created}+ echo "Waiting on kubernetes job: $job_name"+ i=0 && \+ # N checks spaced 30s apart = 900s total.+ status_code=2 && \+ # Check on the job periodically. Set the status code depending on what+ # happened to the job in Kubernetes. If we try MAX_CHECKS times and+ # still the job hasn't finished, give up and return the starting+ # non-zero status code.+ printf "Waiting for job to finish: " && \+ while [ $i -lt $MAX_CHECKS ]; do ((i++)); if kubectl get jobs $job_name -o jsonpath='Failed:{.status.failed}' | grep "Failed:1"; then status_code=1 && break; elif kubectl get jobs $job_name -o jsonpath='Succeeded:{.status.succeeded}' | grep "Succeeded:1" ; then status_code=0 && break; else printf "."; fi; sleep $CHECK_SPEEP; done && \+ echo "Done waiting. Job status code: $status_code" && \+ pod_name=$(kubectl get po -l controller-uid=`kubectl get job $job_name -o "jsonpath={.metadata.labels.controller-uid}"` | awk 'match($0,!/NAME/) {print $1}') && \+ echo "GKE pod name: $pod_name" && \+ kubectl logs -f $pod_name --container=train > /tmp/full_output.txt+ if grep -q '<?xml version="1.0" ?>' /tmp/full_output.txt ; then csplit /tmp/full_output.txt '/<?xml version="1.0" ?>/'; else mv /tmp/full_output.txt xx00; fi && \+ # First portion is the test logs. Print these to Github Action stdout.+ cat xx00 && \+ echo "Done with log retrieval attempt." && \+ gcloud container images delete "$GCR_IMAGE_PATH:$CIRCLE_WORKFLOW_JOB_ID" --force-delete-tags && \+ exit $status_code++ delete_gke_jobs: &delete_gke_jobs+ run:+ name: Delete GKE Jobs+ command: |+ # Match jobs whose age matches patterns like '1h' or '1d', i.e. any job+ # that has been around longer than 1hr. First print all columns for+ # matches, then execute the delete.+ jobs_to_delete=$(kubectl get job | awk 'match($4,/[0-9]+[dh]/) {print $0}')+ echo $jobs_to_delete+ if [ ${#jobs_to_delete} -gt 1 ];+ then kubectl delete job $(kubectl get job | awk 'match($4,/[0-9]+[dh]/) {print $1}');+ fi+jobs:++ TPU-tests:+ parameters:+ python:+ type: string+ pytorch:+ type: string+ docker:+ - image: circleci/python:3.7+ environment:+ - PYTHON_VER: << parameters.python >>+ - PYTORCH_VER: << parameters.pytorch >>+ - MAX_CHECKS: 240+ - CHECK_SPEEP: 5+ steps:+ - checkout+ - go/install+ - *checkout_ml_testing+ - gcp-gke/install+ - gcp-gke/update-kubeconfig-with-credentials:+ cluster: $GKE_CLUSTER+ perform-login: true+ - setup_remote_docker+ - *build_push_docker+ - *deploy_cluster+ #- *stats+ #- codecov/upload:+ # file: coverage.xml+ # flags: tpu,pytest+ # upload_name: TPU-coverage++ #- store_artifacts:+ # path: coverage.xml++ cleanup-gke-jobs:+ docker:+ - image: circleci/python:3.7+ steps:+ - gcp-gke/install+ - gcp-gke/update-kubeconfig-with-credentials:+ cluster: $GKE_CLUSTER+ perform-login: true+ - *delete_gke_jobs+++workflows:+ version: 2+ tpu-tests:+ jobs:+ - TPU-tests:+ matrix:+ parameters:+ python: ["3.6", "3.7"]+ pytorch: ["nightly"]+ tpu-cleanup:+ triggers:+ - schedule:+ # The cron format is:+ # min (0-59) hour (0-23) monthday (1-31) month (1-12) weekday (0-6, 0=Sun)+ # Set to run at the first minute of every hour.+ cron: "0 * * * *"+ filters:+ branches:+ only:+ - master+ jobs:+ - cleanup-gke-jobsdiff --git a/conftest.py b/conftest.pyindex fbb7b5050..485130abf 100644--- a/conftest.py+++ b/conftest.py@@ -43,7 +43,14 @@ DEVICE_DTYPE_BLACKLIST = {('cpu', 'float16')}@pytest.fixture()def device(device_name) -> torch.device:- if device_name not in TEST_DEVICES:+ # To work with TPUs on Colab:+ # pip install cloud-tpu-client==0.10+ # pip install https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.6-cp36-cp36m-linux_x86_64.whl+ # Issue: gradcheck on TPUs takes ages...+ if device_name == "tpu":+ import torch_xla.core.xla_model as xm+ return xm.xla_device()+ elif device_name not in TEST_DEVICES:pytest.skip(f"Unsupported device type: {device_name}")return TEST_DEVICES[device_name]diff --git a/docker/tpu-tests/Dockerfile b/docker/tpu-tests/Dockerfilenew file mode 100644index 000000000..5b245e07c--- /dev/null+++ b/docker/tpu-tests/Dockerfile@@ -0,0 +1,64 @@+FROM google/cloud-sdk:slim++# Build args.+ARG GITHUB_REF=refs/heads/master++# TODO: This Dockerfile installs pytorch/xla 3.6 wheels. There are also 3.7+# wheels available; see below.+ARG PYTHON_VERSION=3.6++ARG PYTORCH_VERSION=1.7++RUN apt-get update && apt-get install -y --no-install-recommends \+ build-essential \+ cmake \+ git \+ curl \+ ca-certificates++# Install conda and python.+# NOTE new Conda does not forward the exit status... https://github.com/conda/conda/issues/8385+RUN curl -o ~/miniconda.sh https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-Linux-x86_64.sh && \+ chmod +x ~/miniconda.sh && \+ ~/miniconda.sh -b && \+ rm ~/miniconda.sh++ENV PATH=/root/miniconda3/bin:$PATH++RUN conda create -y --name container python=$PYTHON_VERSION++# Run the rest of commands within the new conda env.+# Use absolute path to appease Codefactor.+SHELL ["/root/miniconda3/bin/conda", "run", "-n", "container", "/bin/bash", "-c"]+RUN conda install -y python=$PYTHON_VERSION mkl++RUN pip uninstall -y torch && \+ # Python 3.7 wheels are available. Replace cp36-cp36m with cp37-cp37m+ gsutil cp 'gs://tpu-pytorch/wheels/torch-${PYTORCH_VERSION}-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' . && \+ gsutil cp 'gs://tpu-pytorch/wheels/torch_xla-${PYTORCH_VERSION}-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' . && \+ pip install 'torch-${PYTORCH_VERSION}-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \+ pip install 'torch_xla-${PYTORCH_VERSION}-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \+ rm 'torch-${PYTORCH_VERSION}-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \+ rm 'torch_xla-${PYTORCH_VERSION}-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \+ apt-get install -y libomp5++ENV LD_LIBRARY_PATH=root/miniconda3/envs/container/lib++# Install kornia/kornia at the current PR, plus dependencies.+RUN git clone https://github.com/kornia/kornia.git && \+ cd kornia && \+ git fetch origin $GITHUB_REF:CI && \+ git checkout CI && \+ python setup.py install && \+ pip install pytest++RUN conda init bash++RUN python -c "import torch; print(torch.__version__)"+RUN python -c "import torch_xla; print(torch_xla.__version__)"+RUN python -c "import kornia as K; print(K.__version__)"+COPY docker-entrypoint.sh /usr/local/bin/+RUN chmod +x /usr/local/bin/docker-entrypoint.sh++ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]+CMD ["bash"]diff --git a/docker/tpu-tests/docker-entrypoint.sh b/docker/tpu-tests/docker-entrypoint.shnew file mode 100644index 000000000..fbe59566f--- /dev/null+++ b/docker/tpu-tests/docker-entrypoint.sh@@ -0,0 +1,8 @@+#!/bin/bash+source ~/.bashrc+echo "running docker-entrypoint.sh"+conda activate container+echo $KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS+echo "printed TPU info"+export XRT_TPU_CONFIG="tpu_worker;0;${KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS:7}"+exec "$@"#!/bin/bashdiff --git a/docker/tpu-tests/tpu_test_cases.jsonnet b/docker/tpu-tests/tpu_test_cases.jsonnetnew file mode 100644index 000000000..36bce8861--- /dev/null+++ b/docker/tpu-tests/tpu_test_cases.jsonnet@@ -0,0 +1,34 @@+local base = import 'templates/base.libsonnet';+local tpus = import 'templates/tpus.libsonnet';+local utils = import "templates/utils.libsonnet";++local tputests = base.BaseTest {+ frameworkPrefix: 'kornia',+ modelName: 'tpu-tests',+ mode: 'postsubmit',+ configMaps: [],++ timeout: 900, # 15 minutes, in seconds.++ image: std.extVar('image'),+ imageTag: std.extVar('image-tag'),++ tpuSettings+: {+ softwareVersion: 'pytorch-nightly',+ },+ accelerator: tpus.v3_8,++ command: utils.scriptCommand(+ |||+ python -c "import torch; print(torch.__version__)"+ python -c "import torch_xla; print(torch_xla.__version__)"+ python -c "import kornia; print(kornia.__version__)"+ pytest -v kornia/test/color --device tpu --dtype float32 -k "not gradcheck"+ test_exit_code=$?+ echo "\nFinished running commands.\n"+ test $test_exit_code -eq 0+ |||+ ),+};++tputests.oneshotJobdiff --git a/setup_dev_env.sh b/setup_dev_env.shindex 528d38ec7..1c87eddac 100755--- a/setup_dev_env.sh+++ b/setup_dev_env.sh@@ -39,7 +39,14 @@ python_version=${PYTHON_VERSION:-"3.7"}pytorch_version=${PYTORCH_VERSION:-"1.6.0"}pytorch_mode=${PYTORCH_MODE:-""} # use `cpuonly` for CPU or leave it in blank for GPUcuda_version=${CUDA_VERSION:-""}+pytorch_channel="pytorch"+# configure for nightly builds+if [ "$pytorch_version" == "nightly" ]; then+ pytorch_version=""+ pytorch_channel="pytorch-nightly"++# configure cudatoolkitcuda_toolkit=""if [ ! -z "$cuda_version" ]then@@ -64,4 +71,4 @@ pip install -r requirements-dev.txt# install documentation dependenciespip install -r docs/requirements.txt-conda deactivate # close the `venv` environment+conda deactivate # close the `venv` environment\ No newline at end of filediff --git a/test/color/test_gray.py b/test/color/test_gray.pyindex 109c26b4b..ee3013453 100644--- a/test/color/test_gray.py+++ b/test/color/test_gray.py@@ -54,13 +54,13 @@ class TestRgbToGrayscale(BaseTester):], device=device, dtype=dtype)# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)- expected = torch.tensor([+ expected = torch.tensor([[[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],[0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],[0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],[0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],[0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]- ], device=device, dtype=dtype)+ ]], device=device, dtype=dtype)img_gray = kornia.rgb_to_grayscale(data)assert_allclose(img_gray, expected)@@ -134,13 +134,13 @@ class TestBgrToGrayscale(BaseTester):], device=device, dtype=dtype)# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)- expected = torch.tensor([+ expected = torch.tensor([[[0.4485849, 0.8233618, 0.6262833, 0.6218331, 0.6341921],[0.3200093, 0.4340172, 0.7107211, 0.5454938, 0.2801398],[0.6149265, 0.7018101, 0.3503231, 0.4891168, 0.5292346],[0.5096100, 0.4336508, 0.6704276, 0.4525143, 0.2134447],[0.7878902, 0.6494595, 0.5211386, 0.6623823, 0.6660464],- ], device=device, dtype=dtype)+ ]], device=device, dtype=dtype)img_gray = kornia.bgr_to_grayscale(data)assert_allclose(img_gray, expected)diff --git a/test/color/test_luv.py b/test/color/test_luv.pyindex 19f8fc319..bc4061551 100644--- a/test/color/test_luv.py+++ b/test/color/test_luv.py@@ -8,6 +8,14 @@ from torch.autograd import gradcheckfrom torch.testing import assert_allclose+def _get_precision(device: torch.device, dtype: torch.dtype) -> float:+ if 'xla' in device.type:+ return 1e-2+ elif dtype == torch.float16:+ return 1e-3+ return 1e-4++class TestRgbToLuv(BaseTester):def test_smoke(self, device, dtype):C, H, W = 3, 4, 5@@ -64,7 +72,8 @@ class TestRgbToLuv(BaseTester):[-38.39783859, -31.71204376, -46.63606644, 50.16629410, -84.74416351]]], device=device, dtype=dtype)- assert_allclose(kornia.color.rgb_to_luv(data), expected)+ tol_val: float = _get_precision(device, dtype)+ assert_allclose(kornia.color.rgb_to_luv(data), expected, rtol=tol_val, atol=tol_val)def test_forth_and_back(self, device, dtype):data = torch.rand(3, 4, 5, device=device, dtype=dtype)@@ -154,7 +163,7 @@ class TestLuvToRgb(BaseTester):[0.06325728, 0.78878325, 0.74280596, 0.99514300, 0.47176042]]]], device=device, dtype=dtype)- assert_allclose(kornia.color.luv_to_rgb(data), expected)+ assert_allclose(kornia.color.luv_to_rgb(data), expected, rtol=1e-4, atol=1e-4)def test_forth_and_back(self, device, dtype):data = torch.rand(3, 4, 5, device=device, dtype=dtype)